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

bind, python, tkinter, widget

Solution

for b in [B1, B2, B3]:
    b.bind("<Enter>", SetColor)
    b.bind("<Leave>", ReturnColor)

You could go further and abstract all of your snippet:

for s in ["button 1", "button 2", "button 3"]:
    b=Button(root, text=s, bg="white")
    b.pack()
    b.bind("<Enter>", SetColor)
    b.bind("<Leave>", ReturnColor)

Now it's easy to add extra buttons (just add another entry to the input list). It's also easy to change what you do to all the buttons by changing the body of the `for` loop.

Problem

I am wondering how to bind multiple widgets with one "bind". For expample: I have three buttons and I want to change their color after hovering. ``` from Tkinter import * def SetColor(event): event.widget.config(bg="red") return def ReturnColor(event): event.widget.config(bg="white") return root = Tk() B1 = Button(root,text="Button 1", bg="white") B1.pack() B2 = Button(root, text="Button2", bg="white") B2.pack() B3 = Button(root, text= "Button 3", bg="white") B3.pack() B1.bind("<Enter>",SetColor) B2.bind("<Enter>",SetColor) B3.bind("<Enter>",SetColor) B1.bind("<Leave>",ReturnColor) B2.bind("<Leave>",ReturnColor) B3.bind("<Leave>",ReturnColor) root.mainloop() ``` And my goal is to have only two binds (for "Enter" and "Leave" events) instead of six as above. Thank you for any ideas

Original source

Related problems