การตัดบรรทัดอัตโนมัติ (Word Wrap) ใน Tkinter Text Widget ควบคุมด้วยพารามิเตอร์ wrap ค่าที่เป็นไปได้: WORD (ตัดที่คำ), CHAR (ตัดที่ตัวอักษร), NONE (ไม่ตัด ต้อง Scroll)
ตัวอย่างโค้ด
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("750x250")
# Word Wrap (ตัดที่ช่องว่าง/คำ)
text = Text(win, wrap=WORD)
text.insert(INSERT, "Python is an interpreted, high-level and general-purpose programming language. "
"Python's design philosophy emphasizes code readability with its notable use of significant indentation.")
text.pack(fill=BOTH, expand=True)
win.mainloop()
โหมด Wrap ทั้ง 3 แบบ
| Mode | พฤติกรรม | ใช้เมื่อ |
|---|---|---|
WORD | ตัดบรรทัดที่ช่องว่าง (ระหว่างคำ) | ข้อความทั่วไป อ่านง่าย (Default) |
CHAR | ตัดบรรทัดที่ตัวอักษรใดๆ | โค้ด/Serial number ที่ไม่มีช่องว่าง |
NONE | ไม่ตัด ต้อง Scroll แนวนอน | Programming editor, Log viewer |
การเปลี่ยนโหมดระหว่างรัน
text.configure(wrap=CHAR) # เปลี่ยนเป็น Char wrap
text.configure(wrap=NONE) # ปิด Wrap
การเพิ่ม Scrollbar
text = Text(win, wrap=WORD)
scrollbar = Scrollbar(win, orient=VERTICAL, command=text.yview)
text.configure(yscrollcommand=scrollbar.set)
text.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar.pack(side=RIGHT, fill=Y)
Text Widget Methods ที่เกี่ยวข้อง
text.index("insert")- ตำแหน่ง Cursor (line.char)text.see("insert")- Scroll ให้เห็น Cursortext.search(pattern, "1.0", stopindex=END)- ค้นหาข้อความtext.tag_add("sel", "1.0", "end")- Select ทั้งหมด
การประยุกต์ใช้
Text Editor, Log Viewer, Chat Window, Code Editor (ใช้ CHAR/NONE), Document Viewer, Note Taking App