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:
JavaScript
x
7
1
def callback(number):
2
print "button", number
3
4
Button(text="one", command=lambda: callback(1))
5
Button(text="two", command=lambda: callback(2))
6
Button(text="three", command=lambda: callback(3))
7
If you want the Button instance as a callback argument you can do something like:
JavaScript
1
19
19
1
import Tkinter
2
class ButtonBis(Tkinter.Button):
3
def __init__(self, master=None, cnf={}, **kw):
4
Tkinter.Button.__init__(self, master, cnf, command =self.callback, **kw)
5
def callback(self):
6
#Or whatever you want to do with self
7
print "clicked!", self.cget('text')
8
9
b = ButtonBis(text="one")
10
b.pack()
11
12
b = ButtonBis(text="two")
13
b.pack()
14
15
b = ButtonBis(text="three")
16
b.pack()
17
18
Tkinter.mainloop()
19