如何透過 Tkinter 中的單個“bind”繫結多個事件?
對於特定應用程式,若我們希望透過其中定義的按鈕執行多項任務,則可以使用 bind(Button, callback) 方法將按鈕與事件繫結在一起,以計劃在應用程式中執行該事件。
假設我們希望使用單個 <bind> 繫結多個事件或回撥,則必須首先遍歷所有小部件,才能將其作為單個實體。此實體現在可以進行配置,以便在應用程式中繫結多個小部件。
示例
# 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("<Enter>", change_bgcolor) b.bind("<Leave>", change_fgcolor) win.mainloop()
輸出
如果我們執行以上程式碼,它將顯示一個包含按鈕的視窗。
將滑鼠懸停在按鈕上時,它會更改標籤的背景顏色。離開按鈕將更改標籤小部件的字型顏色。
廣告