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