การปรับแต่งฟอนต์ของ Text Widget ใน Tkinter ใช้พารามิเตอร์ font ใน Constructor หรือ configure() รูปแบบ Tuple: ('Font Family', size, 'style')
ตัวอย่างโค้ด
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("750x250")
# Text Widget พร้อมฟอนต์กำหนดเอง
text = Text(win, height=15, font=('Times New Roman', 17, 'bold'))
text.insert(INSERT, "Hey Folks!, Welcome to TutorialsPoint!")
text.pack(fill=BOTH, expand=True, padx=20, pady=20)
win.mainloop()
รูปแบบ Font Specification
| รูปแบบ | ตัวอย่าง | คำอธิบาย |
|---|---|---|
| Tuple | ('Arial', 12, 'bold') | Family, Size (pt), Style |
| String | "Arial 12 bold" | Space-separated (Tk format) |
| Font Object | tkFont.Font(...) | Object-oriented, reusable |
Font Styles ที่รองรับ
'normal'(default)'bold''italic''bold italic''underline''overstrike'(strikethrough)- รวมได้:
'bold italic underline'
การใช้ tkinter.font Module
import tkinter.font as tkFont
# สร้าง Font Object (ใช้ซ้ำได้)
custom_font = tkFont.Font(family='Consolas', size=14, weight='normal')
text = Text(win, font=custom_font)
text.pack()
# เปลี่ยนขนาด Dynamic
def increase_font():
current_size = custom_font.cget('size')
custom_font.configure(size=current_size + 2)
def decrease_font():
current_size = custom_font.cget('size')
if current_size > 8:
custom_font.configure(size=current_size - 2)
ttk.Button(win, text="A+", command=increase_font).pack()
ttk.Button(win, text="A-", command=decrease_font).pack()
Named Fonts (Built-in)
TkDefaultFont- Default GUI fontTkTextFont- For text widgetsTkFixedFont- MonospaceTkMenuFont- MenusTkHeadingFont- HeadingsTkCaptionFont- Window titlesTkSmallCaptionFont- Small captionsTkIconFont- Icon labelsTkTooltipFont- Tooltips
การประยุกต์ใช้
Text Editor, Code Editor (Monospace), Note App, Chat App, Document Viewer, Accessibility (Large Font Mode)