Home > Blockchain >  Get dynamically which button uses function
Get dynamically which button uses function

Time:03-10

I have a question about buttons and binds, but it's better if I show you.

from tkinter import Tk,Button
root = Tk()
startbutton = Button(root,text="start button")
pingbutton = Button(root,text="ping button")

startbutton.pack()
pingbutton.pack()

def startenterbind(e):
    startbutton.config(relief='sunken')
def startleavebind(e):
    startbutton.config(relief='raised')
def pingenterbind(e):
    pingbutton.config(relief='sunken')
def pingleavebind(e):
    pingbutton.config(relief='raised')
startbutton.bind("<Enter>", startenterbind)
startbutton.bind("<Leave>", startleavebind)
pingbutton.bind("<Enter>", pingenterbind)
pingbutton.bind("<Leave>", pingleavebind)

root.mainloop()
        

This is my code, now I am wondering, is there a better way to do this? Maybe it's possible to get which button was hovered dynamically, to then change the button that was hovered?

This is so I can use one function for multiple buttons, while only affecting the one being <Enter>'d or <Leave>'d?

CodePudding user response:

You can reuse an event handler function by making use of the event object they are passed which has an attribute telling you the widget that triggered it.

from tkinter import Tk,Button
root = Tk()
startbutton = Button(root,text="start button")
pingbutton = Button(root,text="ping button")

startbutton.pack()
pingbutton.pack()

def startenterbind(event):
    event.widget.config(relief='sunken')

def startleavebind(event):
    event.widget.config(relief='raised')

startbutton.bind("<Enter>", startenterbind)
startbutton.bind("<Leave>", startleavebind)
pingbutton.bind("<Enter>", startenterbind)
pingbutton.bind("<Leave>", startleavebind)

root.mainloop()

You could go a bit further by writing a single function that simply toggled the state of the button whenever it was called. One way that could be accomplished is by making the new relief type depend on what it currently is which can be determined by calling the universal widget cget() method:

def enterleavebind(event):
    new_relief = 'sunken' if event.widget.cget('relief') == 'raised' else 'raised'
    event.widget.config(relief=new_relief)

startbutton.bind("<Enter>", enterleavebind)
startbutton.bind("<Leave>", enterleavebind)
pingbutton.bind("<Enter>", enterleavebind)
pingbutton.bind("<Leave>", enterleavebind)
  • Related