Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีดึงชื่อ Widget จาก Event ใน Tkinter


Tkinter เป็นไลบรารี Python สร้างและพัฒนาแอปพลิเคชัน GUI Tkinter มี widgets สำหรับสร้างการแสดงผลและการทำงานของแอปพลิเคชัน

สมมติเรากำหนด widgets ในแอปพลิเคชัน หากต้องการดึงชื่อ widget ใน event สามารถทำได้โดยใช้ event.widget["text"] ภายในฟังก์ชัน สามารถพิมพ์ชื่อได้ด้วยฟังก์ชัน print()

ตัวอย่าง

# 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("700x300") 
# Define a function to delete the shape 
def on_click(): 
    print (win.winfo_children()) 
# Create a canvas widget 
canvas=Canvas(win, width=500, height=300) 
canvas.pack() 
# Create a button to delete the button 
Button(win, text="Click", command=on_click).pack() 
win.mainloop()

ผลลัพธ์

รันโค้ด จะแสดงหน้าต่างพร้อมปุ่ม

วิธีดึงชื่อ Widget จาก Event ใน Tkinter

คลิกปุ่ม จะแสดงชื่อ widget บนหน้าจอ

[, ]