【问题标题】:Buttons activate on creation, then do not work按钮在创建时激活,然后不起作用
【发布时间】:2013-08-28 20:47:49
【问题描述】:

我对这种语言很陌生,我真的迷路了。

from tkinter import *

class App:

    def __init__(self,master):

        self.var = ""

        frame = Frame(master)
        frame.pack()

        self.action = Button(frame,text="action",command=self.doAction())
        self.action.pack(side=LEFT)

    def doAction(self):
        print(self.var)

root = Tk()

app = App(root)

root.mainloop()

【问题讨论】:

    标签: python button python-3.x tkinter


    【解决方案1】:

    command=self.doAction() 将在线路运行时(即创建时)调用 doAction。您需要删除括号,以便在按钮调用它之前不会调用该函数:

    self.action = Button(frame,text="action",command=self.doAction)
    

    要将参数(在创建时就知道)传递给函数,可以使用 lambda(匿名函数):

    self.action = Button(frame,text="action",command=lambda: self.doAction(x))
    

    这将创建一个调用self.doAction(x) 的新函数。等效地,您可以使用命名函数:

    def button_action(): 
        self.doAction(x)
    self.action = Button(frame,text="action",command=button_action)
    

    【讨论】:

    • 非常感谢。作为这个问题的扩展,我将如何使用需要输入的函数?例如:self.action = Button(frame,text="action",command=self.doAction(x))def doAction(self,x): print(x)
    猜你喜欢
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多