更改 Tkinter 中所有微件的默认字体


让我们考虑一种情况,我们想要更改 Tkinter 应用程序的默认字体。要应用字体并将其设置为特定应用程序的默认字体,我们必须使用option_add(**options) 方法,其中我们指定属性,例如背景色、字体,等。在定义方法后进行的更改将强制所有微件继承相同的属性。

示例

在给定的脚本中,我们已经为应用程序设置了一个默认字体,以便可以在应用程序中定义的所有微件中使用它。

#Import the required libraries
from tkinter import *

#Create an instance of Tkinter frame
win = Tk()

win.geometry("700x350")
#Add fonts for all the widgets
win.option_add("*Font", "aerial")

#Set the font for the Label widget
win.option_add("*Label.Font", "aerial 18 bold")

# Define the backround color for all the idgets
win.option_add("*Background", "bisque")

#Display bunch of widgets
Label(win, text="Label").pack()
Button(win, text="Button").pack()

#Create a Listbox widget
w = Listbox(win)
for i in range(5):
   w.insert(i, "item %d" % (i+1))
w.pack()

w = Text(win, width=20, height=10)
w.insert(1.0, "a text widget")
w.pack()

win.mainloop()

输出

运行上面的代码将显示一个带有标签微件、按钮、列表框和文本微件的窗口。在给定的输出中,所有微件继承相同的属性。

更新时间: 25-May-2021

2K+ 浏览量

开启你的 职业

Get certified by completing the course

Get Started
Advertisements
© . All rights reserved.