如何在 Tkinter 中使用自定義字型?


為了在 Python tkinter 中定義並顯示自定義字型,我們通常使用 tkinter 中定義的一個內建字型庫。為了在筆記本中匯入 tkinter Font 庫,請在 shell 中輸入以下內容:

from tkinter.font import Font

現在,使用 Font(..options) 函式建立一個 Font 物件並定義字型其他屬性,如字體系列、大小、粗細、傾斜、加下劃線、刪除線等。

示例

#Import the required library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
win.geometry("750x250")
#Create a String Object and set the default value
var = StringVar()
#Create a text label
label = Label(win, textvariable = var, font=('Consolas 20 bold'))
label.pack()
#Create an entry widget to change the variable value
text = Entry(win, textvariable = var)
text.pack()
win.mainloop()

輸出

執行上面的程式碼將顯示一個帶有 Entry 小部件和一個 Label 的視窗。每當我們在文字框中輸入某些關鍵詞時,Label 都會更新。

更新於: 16-4-2021

2K+ 閱讀

開始妳的 職業

完成課程以取得認證

開始
廣告