更改 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