简体   繁体   中英

Determine which widget triggers the callback function in command

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!

Shamelessly copied from http://effbot.org/zone/tkinter-callbacks.htm 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM