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

วิธีผูกหลายเหตุการณ์ด้วย bind เดียวใน Tkinter


สำหรับแอปพลิเคชันเฉพาะ หากต้องการทำหลายงานด้วยปุ่มที่กำหนด ให้ใช้เมธอด bind(Button, callback) ผูกปุ่มและเหตุการณ์ร่วมกันเพื่อจัดตารางการทำงานของเหตุการณ์ในแอปพลิเคชัน

สมมติว่าต้องการผูกหลายเหตุการณ์หรือ callback ด้วย เดียว ให้วนลูปผ่าน widget ทั้งหมดเพื่อรวมเป็นเอนทิตี้เดียว เอนทิตีีนี้สามารถกำหนดค่าเพื่อผูก widget หลายตัวในแอปพลิเคชันได้

ตัวอย่าง

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")

def change_bgcolor(e):
    label.config(background="#adad12")

def change_fgcolor(e):
    label.config(foreground="white")

# Add a Label widget
label = Label(win, text="Hello World! Welcome to Tutorialspoint", font=('Georgia 19 italic'))
label.pack(pady=30)

# Add Buttons to trigger the event
b1 = ttk.Button(win, text="Button-1")
b1.pack()

# Bind the events for b in [b1]:
    b.bind("", change_bgcolor)
    b.bind("", change_fgcolor)

win.mainloop()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างที่มีปุ่ม

วิธีผูกหลายเหตุการณ์ด้วย bind เดียวใน Tkinter

เมื่อ hover บนปุ่ม จะเปลี่ยนสีพื้นหลังของ Label การออกจากปุ่มจะเปลี่ยนสีฟอนต์ของ Label widget

วิธีผูกหลายเหตุการณ์ด้วย bind เดียวใน Tkinter