我正在使用Python和TkInter来构建一个GUI,当按下按钮时会调用某个命令。相关代码如下所示:
class Main(Frame):
def __init__(self, parent):
self.generate_noise_button = Button(root, text="Add noise and save", command=self.generate_noise())
...
def generate_noise(self):
header.generate_noise()
如果我在generate_noise()
方法中放置断点并运行程序,即使从未调用或按下按钮,断点也会立即被触发。此外,每当我实际按下按钮时,方法永远不会被称为使按钮完全无用。为什么呢?
答案 0 :(得分:0)
self.generate_noise_button = Button(root, text="Add noise and save", command=self.generate_noise())
当您提供command
参数时,您不应该在末尾添加括号。
self.generate_noise_button = Button(root, text="Add noise and save", command=self.generate_noise)
您希望command
引用方法对象,而不是方法在调用后返回的值。