我在Python中遇到了一个问题。通常,在tkinter对象中;字体"选项是一个字符串。但我希望它是一个变量或open((。我试图设置一个打开:
SystemFont = open("/home/pi/Desktop/___/.SystemFnt.txt")
然后,我尝试将字体选项设置为打开,如下所示:
lbl1 = Label(root2, text="My Apps:", font=SystemFont)
我不断得到这个错误作为回报。我想它想要一个整数。
Traceback (most recent call last):
File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "/home/pi/Desktop/___/____.py", line 24, in LogInCmd
lbl1 = Label(root2, text="My Apps:", font=SystemFont)
File "/usr/lib/python3.9/tkinter/__init__.py", line 3148, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/usr/lib/python3.9/tkinter/__init__.py", line 2572, in __init__
self.tk.call(
_tkinter.TclError: expected integer but got "name='/home/pi/Desktop/____/.SystemFnt.txt'"
不过,我想放一个open()
,而不是一个整数。
我认为您需要的是tkinter.font.Font
。为tkinter.font.Font
的实例指定font
选项,可以动态更改字体系列和大小。
下面是一个动态更改字体系列和标签大小的示例:
import tkinter as tk
from tkinter.font import Font
def change_font_family(val):
font['family'] = val
def change_font_size(val):
font['size'] = val
root = tk.Tk()
panel = tk.Frame(root, width=1000, height=300)
panel.pack()
font = Font(family='Arial', size=24)
lbl = tk.Label(panel, text='Hello World', font=font)
lbl.place(relwidth=1, relheight=1)
# select font family
families = ('Arial', 'Times', 'Consolas', 'Calibri')
family_var = tk.StringVar()
opt_family = tk.OptionMenu(root, family_var, *families, command=change_font_family)
opt_family.pack()
opt_family.config(width=20)
# select font size
opt_size = tk.Scale(root, from_=10, to_=100, orient='horizontal', length=300, command=change_font_size)
opt_size.pack()
root.mainloop()