use*_*339 0 python user-interface tk-toolkit tkinter
在下面的代码中,单击按钮应该将黑色文本从 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()
Run Code Online (Sandbox Code Playgroud)
小智 5
因为您self.bpress在创建self.button1按钮时正在调用:
self.button1 = Button(self, text = "Click Me", width = 10, command = self.bpress())
# ^^
Run Code Online (Sandbox Code Playgroud)
只需删除括号并分配command给self.bpress函数对象本身:
self.button1 = Button(self, text = "Click Me", width = 10, command = self.bpress)
Run Code Online (Sandbox Code Playgroud)