Tkinter ラベルのフォントサイズを変更する方法

このチュートリアルガイドは、Tkinter ラベルフォントサイズを変更する方法を示します。Tkinter ラベルのフォントサイズを増減するために、2つのボタン Increase
と Decrease
を作成します。
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 ラベルフォントファミリーの変更
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])
labelExample
の font
プロパティは font.families
リスト内の次のフォントに変更され、ラベルテキストはフォント名に更新されます。
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