การดูรายการ Font Families ที่ Tkinter รองรับ ใช้โมดูล tkinter.font และเมธอด font.families() แล้วแสดงใน Scrollable Frame
ขั้นตอนการทำงาน
- นำเข้า
tkinterและtkinter.font - ดึงรายการฟอนต์:
fonts = list(font.families())แล้วsort() - สร้าง Canvas + Scrollbar + Frame ภายใน Canvas
- Bind
ของ Frame เพื่อ Update Scrollregion - วนลูปสร้าง Label แต่ละ Font แสดงตัวอย่างตัวอักษร
ตัวอย่างโค้ด
from tkinter import *
from tkinter import font
win = Tk()
win.geometry("750x350")
win.title('Font List')
fonts = list(font.families())
fonts.sort()
def fill_frame(frame):
for f in fonts:
Label(frame, text=f, font=(f, 14)).pack(anchor=W)
def onFrameConfigure(canvas):
canvas.configure(scrollregion=canvas.bbox("all"))
canvas = Canvas(win, bd=1, background="white")
frame = Frame(canvas, background="white")
scroll_y = Scrollbar(win, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scroll_y.set)
scroll_y.pack(side="right", fill="y")
canvas.pack(side="left", expand=1, fill="both")
canvas.create_window((5, 4), window=frame, anchor="n")
frame.bind("", lambda e, canvas=canvas: onFrameConfigure(canvas))
fill_frame(frame)
win.mainloop()
การใช้ Font Object โดยตรง
import tkinter.font as tkFont
# ดูรายการ
families = tkFont.families()
print(families[:10]) # 10 ฟอนต์แรก
# สร้าง Font Object
f = tkFont.Font(family='Arial', size=12, weight='bold')
print(f.actual()) # ดูรายละเอียดจริงที่ระบบใช้
# วัดขนาดข้อความ
width = f.measure("Hello World")
height = f.metrics('linespace')
ascent = f.metrics('ascent')
descent = f.metrics('descent')
Named Fonts (System Fonts)
# ใช้ Named Font ที่ปลอดภัย Cross-platform
Label(win, text="Default", font="TkDefaultFont").pack()
Label(win, text="Text Font", font="TkTextFont").pack()
Label(win, text="Fixed Font", font="TkFixedFont").pack()
Label(win, text="Heading", font="TkHeadingFont").pack()
การประยุกต์ใช้
Font Selector Dialog, Theme Customizer, Typography Preview Tool, Accessibility Settings (Font Size), Document Editor Font Menu