How to pass arguments to a Button command in Tkinter?

前端 未结 18 3112
夕颜
夕颜 2020-11-21 07:42

Suppose I have the following Button made with Tkinter in Python:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=         


        
18条回答
  •  广开言路
    2020-11-21 07:51

    The reason it invokes the method immediately and pressing the button does nothing is that action(somenumber) is evaluated and its return value is attributed as the command for the button. So if action prints something to tell you it has run and returns None, you just run action to evaluate its return value and given None as the command for the button.

    To have buttons to call functions with different arguments you can use global variables, although I can't recommend it:

    import Tkinter as Tk
    
    frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
    frame.grid(row=2,column=2)
    frame.pack(fill=Tk.X, padx=5, pady=5)
    def action():
        global output
        global variable
        output.insert(Tk.END,variable.get())
    button = Tk.Button(master=frame, text='press', command=action)
    button.pack()
    variable = Tk.Entry(master=frame)
    variable.pack()
    output = Tk.Text(master=frame)
    output.pack()
    
    if __name__ == '__main__':
        Tk.mainloop()
    

    What I would do is make a class whose objects would contain every variable required and methods to change those as needed:

    import Tkinter as Tk
    class Window:
        def __init__(self):
            self.frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
            self.frame.grid(row=2,column=2)
            self.frame.pack(fill=Tk.X, padx=5, pady=5)
    
            self.button = Tk.Button(master=self.frame, text='press', command=self.action)
            self.button.pack()
    
            self.variable = Tk.Entry(master=self.frame)
            self.variable.pack()
    
            self.output = Tk.Text(master=self.frame)
            self.output.pack()
    
        def action(self):
            self.output.insert(Tk.END,self.variable.get())
    
    if __name__ == '__main__':
        window = Window()
        Tk.mainloop()
    

提交回复
热议问题