How to bind multiple events with one "bind" in Tkinter?


For a particular application, if we want to perform multiple tasks with the help of buttons defined in it, then we can use the bind(Button, callback) method which binds the button and the event together to schedule the running of the event in the application.

Let us suppose we want to bind multiple events or callback with a single <bind>, then we have to first iterate over all the widgets to get it as one entity. The entity can be now configurable to bind the multiple widgets in the application.

Example

# 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()

Output

If we run the above code, it will display a window that contains a button.

When we hover over the button, it will change the background color of the Label. Leaving the button will change the font color of the Label widget.

Updated on: 18-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements