2017-08-26 40 views
-1

我正在编写代码以通过单击按钮将两个变量传递给函数。问题是在按下按钮之前它是这样做的。我究竟做错了什么?python按钮命令在点击前执行

calcButton = Button(window, text="Calculate Weight", 
          command=window.calc(5,10)) 
     calcButton.place(x=225, y=85) 
     answertextLabel = Label(window, text="Answer:") 
     answertextLabel.place(x=225, y=65) 
     answerLabel = Label(window, text=answervar) 
     answerLabel.place(x=275, y=65) 

    def calc(window, diameter, density): 
     math = diameter + density 
     print (math) 

回答

0

当你做window.calc(5,10)函数被执行。

你需要用它在另一个功能:

command=lambda: window.calc(5,10) 
0

你是不是传递函数作为参数传递给Button构造;您正在将某个特定调用的返回值传递给该函数。将该调用包装在一个零参数函数中,以推迟实际调用,直到单击该按钮。

calcButton = Button(window, 
        text="Calculate Weight", 
        command=lambda : window.calc(5,10)) 
+0

谢谢。这工作,现在我开始明白为什么。当我能够时,我会接受答案! –