I am coding a GUI in python using tkinter. I assgined the same callback function to the “command” argument in 3 buttons. The purpose of these buttons is to specify a directory depending on the widget name. Is there any way that I can tell which widget triggered the callback function, and assign directory in the callback accordingly?
(of course, I can create different callback functions and assign to each individual widgets, but I wanna adopt a slick approach.)
Thx in advance!
Advertisement
Answer
(Shamelessly copied from Tkinter Callbacks.)
You could try something like:
def callback(number): print "button", number Button(text="one", command=lambda: callback(1)) Button(text="two", command=lambda: callback(2)) Button(text="three", command=lambda: callback(3))
If you want the Button instance as a callback argument you can do something like:
import Tkinter class ButtonBis(Tkinter.Button): def __init__(self, master=None, cnf={}, **kw): Tkinter.Button.__init__(self, master, cnf, command =self.callback, **kw) def callback(self): #Or whatever you want to do with self print "clicked!", self.cget('text') b = ButtonBis(text="one") b.pack() b = ButtonBis(text="two") b.pack() b = ButtonBis(text="three") b.pack() Tkinter.mainloop()