在下面的代码中,单击按钮应将黑色文本从Hello更改为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()
答案 0 :(得分:4)
因为您在创建self.bpress
按钮时呼叫self.button1
:
self.button1 = Button(self, text = "Click Me", width = 10, command = self.bpress())
# ^^
只需删除括号并将command
指定给self.bpress
函数对象本身:
self.button1 = Button(self, text = "Click Me", width = 10, command = self.bpress)
答案 1 :(得分:0)
供将来参考:
如果您想将参数发送到该功能,只需添加lambda:
使用命令callback()
的按钮示例:
yourButton = Tkinter.Button(root, text="Go!", command= lambda: callback(variableOne, variableTwo, variableThree)).pack()