การปรับขนาดฟอนต์ของ Text Widget ใน Tkinter ทำได้โดยพารามิเตอร์ font=('family', size, 'style') ใน Constructor หรือ configure()
ตัวอย่างโค้ด
from tkinter import *
win = Tk()
win.geometry("750x250")
# Font: (Family, Size, Style)
text = Text(win, width=60, height=10, font=('Century Schoolbook', 20, 'italic'))
text.insert(INSERT, "Hello\nWelcome to TutorialsPoint.com!")
text.pack(fill=BOTH, expand=True, padx=20, pady=20)
win.mainloop()
การเปลี่ยนฟอนต์ Dynamic
import tkinter.font as tkFont
# ใช้ Font Object เพื่อเปลี่ยนได้ทุกที่
editor_font = tkFont.Font(family='Consolas', size=12)
text = Text(win, font=editor_font)
text.pack(fill=BOTH, expand=True)
def zoom_in():
editor_font.configure(size=editor_font.cget('size') + 2)
def zoom_out():
if editor_font.cget('size') > 8:
editor_font.configure(size=editor_font.cget('size') - 2)
def reset_zoom():
editor_font.configure(size=12)
# Toolbar
toolbar = Frame(win)
ttk.Button(toolbar, text="Zoom In (+)", command=zoom_in).pack(side=LEFT)
ttk.Button(toolbar, text="Zoom Out (-)", command=zoom_out).pack(side=LEFT)
ttk.Button(toolbar, text="Reset", command=reset_zoom).pack(side=LEFT)
toolbar.pack(fill=X, pady=5)
Font Families ที่ปลอดภัย Cross-platform
- Serif:
Times New Roman,Georgia,Palatino - Sans-Serif:
Arial,Helvetica,Verdana,Tahoma,Calibri - Monospace:
Courier New,Consolas,Monospace,DejaVu Sans Mono - System:
TkDefaultFont,TkTextFont,TkFixedFont
การใช้ Tag สำหรับหลายฟอนต์ใน Text Widget เดียว
text.tag_configure("big_bold", font=('Arial', 18, 'bold'), foreground='blue')
text.tag_configure("small_red", font=('Arial', 10), foreground='red')
text.insert(END, "Big Bold Text\n", "big_bold")
text.insert(END, "Small Red Text\n", "small_red")
text.insert(END, "Normal Text")
การประยุกต์ใช้
Text Editor, Code Editor (Zoom), Note App, Chat App (Font Size Setting), Accessibility Features, Markdown Preview, Syntax Highlighting Base