-1

I am writing code to pass two variables to a function on the click of a button. The issue is that it is doing so before the button is pressed. What am I doing wrong?

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)

2 Answers2

0

When you do window.calc(5,10) the function gets executed.

You need to wrap it in another function:

command=lambda: window.calc(5,10)
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

You aren't passing the function as an argument to the Button constructor; you are passing the return value of one particular call to that function. Wrap the call in a zero-argument function to defer the actual call until the button is clicked.

calcButton = Button(window,
                    text="Calculate Weight",
                    command=lambda : window.calc(5,10))
chepner
  • 497,756
  • 71
  • 530
  • 681