Why is my Tk button being pressed automatically?

Deadly 提交于 2019-12-02 15:33:06

问题


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.

from Tkinter import *
from tkMessageBox import *
print "this is a test"


class Demo(Frame):
    def __init__(self):
        self.createGUI()
        print "init"
        #self.__mainWindow = Tk()
    def destroy(self):
        print "destroy"
    def createGUI(self):
        Frame.__init__(self)
        self.pack(expand = YES, fill = BOTH)
        self.master.title("Demo")
        self.trackLabel = StringVar()
        self.trackLabel.set("Hello")
        self.trackDisplay = Label(self, font = "Courier 14", textvariable = self.trackLabel, bg = "black", fg = "green")
        self.trackDisplay.grid(sticky = W+E+N+S)
        self.button1 = Button(self, text = "Click Me", width = 10, command = self.bpress())
        self.button1.grid(row = 2, column = 0, sticky = W+E+N+S)

    def bpress(self):
        self.trackLabel.set("Goodbye")
# run the program
def main():
    tts = Demo()
    tts.mainloop()

if __name__ == "__main__":
    main()

回答1:


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)



回答2:


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()


来源:https://stackoverflow.com/questions/27008343/why-is-my-tk-button-being-pressed-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!