简体   繁体   中英

access to top level widget in Tkinter

How i can access to top level widget from function, which used as command for button or menu? There is way to add params in this command function by using command=lambda: f(params) , but i think it may be easier.

You could use a lambda, like you mentioned:

command=lambda: f(params)

or you could make a closure:

def make_callback(params):
    def callback():
        print(params)
    return callback
params = 1,2,3
button = tk.Button(master, text='Boink', command=make_callback(params))

or, you could use a class and pass a bound method. The attributes of self can contain the information that you would otherwise have had to pass as parameters.

import Tkinter as tk
class SimpleApp(object):
    def __init__(self, master, **kwargs):
        self.master = master
        self.params = (1,2,3)
        self.button = tk.Button(master, text='Boink', command=self.boink)
        self.button.pack()
    def boink(self):
        print(self.params)

root = tk.Tk()
app = SimpleApp(root)
root.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