Python 特金特意外行为

Python 特金特意外行为,python,tkinter,Python,Tkinter,我的程序中有一组方法,即使用Tkinter,它们的行为与我想象的不一样。我希望能够在窗口中按下一个按钮,显示更多的文本字段,并能够返回文本字段中的结果列表。以下是我所拥有的: def expandChoice(self): root = Tk() choices = [] plusButton = Button (root, text='+', command=self.addChoice(root, choices)) plusButton.pack()

我的程序中有一组方法,即使用Tkinter,它们的行为与我想象的不一样。我希望能够在窗口中按下一个按钮,显示更多的文本字段,并能够返回文本字段中的结果列表。以下是我所拥有的:

def expandChoice(self):
    root = Tk()

    choices = []

    plusButton = Button (root, text='+', command=self.addChoice(root, choices)) 
    plusButton.pack()

    quitButton = Button (root, text='Ok', command=root.destroy ) 
    quitButton.pack()

    root.mainloop()

    return choices

def addChoice(self, parent, variables):

    variables.append(StringVar())

    text = Entry(parent, textvariable=variables[len(variables)-1])
    text.pack()

当窗口加载(按钮上方)时,会出现一个文本字段,而加号按钮不起任何作用。我做错了什么?当调用第一个按钮的构造函数时,addChoice方法似乎会自动被调用,然后就不起作用了。

命令选项引用了一个可调用的。但是,您要立即调用
addChoice
,然后将该retuns(None)分配给
命令
选项

您需要执行类似于
按钮(…command=self.addChoice)

如果需要传递参数,则需要使用lambda或
functools.partial
。在本网站上搜索这两个问题中的任何一个--此问题的变体已被多次询问和回答。

可能重复