如何更改 Tkinter 標籤字型大小

Jinku Hu 2023年1月30日 2019年12月2日
  1. 更改 Tkinter 標籤字型大小
  2. 更改 Tkinter 標籤字型系列 font-family
如何更改 Tkinter 標籤字型大小

本教程指南介紹如何更改 Tkinter 標籤字型大小。我們建立兩個按鈕 IncreaseDecrease 來增大/減小 Tkinter 標籤的字型大小。

更改 Tkinter 標籤字型大小

Tkinter 更改標籤字型大小

import tkinter as tk
import tkinter.font as tkFont
    
app = tk.Tk()

fontStyle = tkFont.Font(family="Lucida Grande", size=20)

labelExample = tk.Label(app, text="20", font=fontStyle)

def increase_label_font():
    fontsize = fontStyle['size']
    labelExample['text'] = fontsize+2
    fontStyle.configure(size=fontsize+2)

def decrease_label_font():
    fontsize = fontStyle['size']
    labelExample['text'] = fontsize-2
    fontStyle.configure(size=fontsize-2)
    
buttonExample1 = tk.Button(app, text="Increase", width=30,
                          command=increase_label_font)
buttonExample2 = tk.Button(app, text="Decrease", width=30,
                          command=decrease_label_font)

buttonExample1.pack(side=tk.LEFT)
buttonExample2.pack(side=tk.LEFT)
labelExample.pack(side=tk.RIGHT)
app.mainloop()
fontStyle = tkFont.Font(family="Lucida Grande", size=20)

我們指定字型是 Lucida Grande 系列,字型大小為 20,並且將該字型賦給標籤 labelExample

def increase_label_font():
    fontsize = fontStyle['size']
    labelExample['text'] = fontsize+2
    fontStyle.configure(size=fontsize+2)

字型大小用 tkinter.font.configure() 方法更新。如從 gif 動畫中看到的,使用該特定字型的控制元件將會自動更新。

labelExample['text'] = fontsize+2

我們還將標籤文字更新為與字型大小相同,以使動畫更加直觀。

更改 Tkinter 標籤字型系列 font-family

我們還將介紹如何通過單擊按鈕來更改 Tkinter 標籤字型系列。

Tkinter 更改標籤字型系列

import tkinter as tk
import tkinter.font as tkFont

app = tk.Tk()

fontfamilylist = list(tkFont.families())

fontindex = 0

fontStyle = tkFont.Font(family=fontfamilylist[fontindex])

labelExample = tk.Label(app, text=fontfamilylist[fontindex], font=fontStyle)

def increase_label_font():
    global fontindex
    fontindex = fontindex + 1
    labelExample.configure(font=fontfamilylist[fontindex], text=fontfamilylist[fontindex])
    
    
buttonExample1 = tk.Button(app, text="Change Font", width=30,
                          command=increase_label_font)

buttonExample1.pack(side=tk.LEFT)
labelExample.pack(side=tk.RIGHT)

    
app.mainloop()
fontfamilylist = list(tkFont.families())

它將獲取可用的 Tkinter 字型系列列表。

labelExample.configure(font=fontfamilylist[fontindex], text=fontfamilylist[fontindex])

labelExamplefont 屬性將更改為 font.families 列表中的下一個字型,並且標籤文字也將更新為字型名稱。

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - Tkinter Label

相關文章 - Tkinter Font