Widget Text ใน Tkinter รองรับการป้อนข้อมูลหลายบรรทัด ตั้งค่าคุณสมบัติ Text widget ด้วย configure()
สร้างแอปพลิเคชันนับตัวอักษรที่พิมพ์อยู่ใน Text widget ขั้นตอน:
- สร้าง Text widget กำหนด width และ height
- ต้องการ label widget แสดงจำนวนตัวอักษรทั้งหมด
- กำหนด event <KeyPress> และ <KeyRelease> อัปเดตจำนวนตัวอักษรใน label
- ฟังก์ชันมี label config อัปเดตเมื่อ event เกิดขึ้น แสดงจำนวนตัวอักษรด้วยการแปลงความยาวข้อความ
- Pack widgets และแสดงผล
ตัวอย่าง
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define a function to get the length of the current text
def update(event):
label.config(text="Total Characters: "+str(len(text.get("1.0", 'end-1c'))))
# Create a text widget
text=Text(win, width=50, height=10, font=('Calibri 14'))
text.pack()
# Create a Label widget
label=Label(win, text="", justify=CENTER, font=('11'))
label.pack()
# Bind the buttons with the event
text.bind('', update)
text.bind('', update)
win.mainloop()
ผลลัพธ์
รันโค้ด จะแสดง text editor และ label widget ที่ด้านล่าง เมื่อพิมพ์ใน text editor จะอัปเดต "Total Characters:"
