Why is my Tk button being pressed automatically?

前端 未结 2 1306
南笙
南笙 2021-01-28 07:28

In the code below, clicking the button should change the black text from Hello to Goodbye. But when I run the program, it immediately says Goodbye.

相关标签:
2条回答
  • 2021-01-28 08:02

    Because you are calling self.bpress when you create the self.button1 button:

    self.button1 = Button(self, text = "Click Me", width = 10, command = self.bpress())
    #                                                                               ^^
    

    Simply remove the parenthesis and assign command to the self.bpress function object itself:

    self.button1 = Button(self, text = "Click Me", width = 10, command = self.bpress)
    
    0 讨论(0)
  • 2021-01-28 08:05

    For future reference:

    If you want to send parameters to the function, simply add lambda:

    Example for a button with the command callback():

    yourButton = Tkinter.Button(root, text="Go!", command= lambda: callback(variableOne, variableTwo, variableThree)).pack()
    
    0 讨论(0)
提交回复
热议问题