如何在不知道小部件的字体系列/大小的情况下更改小部件的字体样式?
有没有办法在不知道小部件的字体系列和字体大小的情况下更改Tkinter小部件的字体样式?
用例:我们使用标准的Tkinter小部件(标签,条目,文本等)创建UI。 在我们的应用程序运行时,我们可能想使用.config()方法动态地将这些小部件的字体样式更改为粗体和/或斜体。 不幸的是,如果不指定字体的系列和大小,似乎无法指定字体规格。
以下是我们想要做的事的例子,但是这些例子都不起作用:
widget.config(font='bold')
要么
widget.config(font=( None, None, 'bold' ))
8个解决方案
51 votes
有一种比使用font.actual更改应用程序字体更好的方法,尤其是如果您的目标是更改整组小部件(或所有小部件)的字体时,尤其如此。
Tk真正的一大特色是“命名字体”的概念。 命名字体的优点在于,如果您更新字体,则使用该字体的所有小部件都会自动更新。 因此,只需配置一次小部件以使用这些自定义字体,然后更改属性就变得微不足道了。
这是一个简单的例子:
try:
import Tkinter as tk
import tkFont
# import ttk # not used here
except ImportError: # Python 3
import tkinter as tk
import tkinter.font as tkFont
# import tkinter.ttk as ttk # not used here
class App:
def __init__(self):
root=tk.Tk()
# create a custom font
self.customFont = tkFont.Font(family="Helvetica", size=12)
# create a couple widgets that use that font
buttonframe = tk.Frame()
label = tk.Label(root, text="Hello, world", font=self.customFont)
text = tk.Text(root, width=20, height=2, font=self.customFont)
buttonframe.pack(side="top", fill="x")
label.pack()
text.pack()
text.insert("end","press +/- buttons to change\nfont size")
# create buttons to adjust the font
bigger = tk.Button(root, text="+", command=self.OnBigger)
smaller = tk.Button(root, text="-", command=self.OnSmaller)
bigger.pack(in_=buttonframe, side="left")
smaller.pack(in_=buttonframe, side="left")
root.mainloop()
def OnBigger(self):
'''Make the font 2 points bigger'''
size = self.customFont['size']
self.customFont.configure(size=size+2)
def OnSmaller(self):
'''Make the font 2 points smaller'''
size = self.customFont['size']
self.customFont.configure(size=size-2)
app=App()
如果您不喜欢这种方法,或者希望将自定义字体设置为默认字体,或者只是更改一种或两种字体来表示状态,则可以使用font.actual获得字体的实际大小 给定的小部件。 例如:
import Tkinter as tk
import tkFont
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
font = tkFont.Font(font=label['font'])
print font.actual()
当我运行上面的代码时,我得到以下输出:
{'family': 'Lucida Grande',
'weight': 'normal',
'slant': 'roman',
'overstrike': False,
'underline': False,
'size': 13}
Bryan Oakley answered 2020-07-22T13:18:04Z
26 votes
只需一个标签就更短:
from Tkinter import *
import Tkinter as tk
root = tk.Tk()
# font="-weight bold" does your thing
example = Label(root, text="This is a bold example.", font="-weight bold")
example.pack()
root.mainloop()
user4226334 answered 2020-07-22T13:18:24Z
4 votes
只需使用特定小部件的基本属性,假设您想更改标签的字体。 您可以使用以下语法:
mlabel = Label(text="Your text", font=("Name of your font",size))
此代码适用于python 3.4
kybrdbnd answered 2020-07-22T13:18:49Z
4 votes
如果使用的是命名字体,则可以使用几个语句来获取所需的内容:
import tkFont
wfont = tkFont.nametofont(widget['font'])
wfont.config(weight='bold')
编辑以并入B. Oakley的评论。
Brandon answered 2020-07-22T13:19:13Z
0 votes
要将以上大部分信息简化为一个代码段:
lbl = ttk.Label(blah, blah) # Make a label
font = tkFont(lbl['font']) # Get its font
font.config(weight='bold') # Modify font attributes
lbl['font'] = font # Tell the label to use the modified font
这允许更改字体属性,而与使用的字体无关(只要字体支持该属性)。
您也可以即时执行此操作,以创建真正令人讨厌的字体效果。
user3712955 answered 2020-07-22T13:19:42Z
0 votes
尽管问这个问题已经有一段时间了,但是我最近不得不实施一个解决方案,我认为值得分享。 函数widget_font_config(...)在Python 2和3上运行。
本质上,小部件的字体的“当前值”被获取,修改然后放回去。 支持命名字体,默认的inplace_f值为True意味着将保留并修改命名字体。 但是标记也可以设置为False,这将导致命名字体替换为其他命名字体,以防用户不希望小部件字体的更改渗透到使用该小部件的所有其他小部件中。 命名字体。
def widget_font_config(widget, inplace_f = True, **kwargs):
import sys
if sys.version_info[0] is 2:
import tkFont
else:
import tkinter.font as tkFont
inplace_f = kwargs.pop('inplace', inplace_f)
font = None
if widget and 'font' in widget.config():
font_config = widget.config()['font']
current_font = font_config[4] #grabs current value
namedfont_f = False
try:
font = tkFont.nametofont(current_font)
namedfont_f = True
except:
font = current_font
if namedfont_f and inplace_f:
font.config(**kwargs)
else:
font_d = tkFont.Font(font=font).actual()
font_d.update(**kwargs)
font = tkFont.Font(**font_d)
widget.config(font=font)
widget.update_idletasks()
return font
if __name__ == '__main__':
import sys
pyVers = sys.version_info.major
if pyVers is 2:
import Tkinter as Tk, tkFont
else:
import tkinter as Tk, tkinter.font as tkFont
def go():
print(widget_font_config(root.label, slant='roman', underline=1).actual())
print(widget_font_config(root.button, overstrike=1).actual())
root = Tk.Tk()
font_s = 'Courier 20 italic'
font_d = dict(family='Courier', size=10, weight='normal', slant='italic')
font = tkFont.Font(**font_d)
root.label = Tk.Label(text='Label {}'.format(font_s), font=font_s)
root.label.pack()
root.button = Tk.Button(text='Button {}'.format(font), font=font, command=go)
root.button.pack()
root.mainloop()
Gary02127 answered 2020-07-22T13:20:07Z
0 votes
要获得默认字体而不触摸或没有窗口小部件,您可以使用默认字体的通用名称。
#!/usr/bin/env python3
import tkinter
import tkinter.font # Python3!
tkinter.Tk()
default_font = tkinter.font.Font(font='TkDefaultFont')
print(default_font.actual())
buhtz answered 2020-07-22T13:20:28Z
-1 votes
我知道这个问题确实很老,但是为了谷歌的人,我仍然要回答这个问题。
如果只想使文本大一点,可以执行.config()。请注意,无论输入什么数字,这似乎总是将字体大小设置为15。
如果需要准确的大小并且没有更改字体,则可以执行.config()。
(.config()是tkinter的默认字体)
您可以在创建时在小部件的参数中使用这些参数之一,或者稍后在.config()中使用它们。
在python 3.6.4中工作
Legosail answered 2020-07-22T13:21:10Z