执行python命令前的python命令按钮

2024-09-24 04:22:55 发布

您现在位置: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)

Tags: 函数代码textcalcplacebuttonmathwindow
2条回答

当您执行window.calc(5,10)时,函数将被执行。在

您需要将其包装在另一个函数中:

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

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

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

相关问题 更多 >