为什么我的 Tk 按钮会被自动按下? [英] Why is my Tk button being pressed automatically?
本文介绍了为什么我的 Tk 按钮会被自动按下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,单击按钮应该将黑色文本从 Hello 更改为 Goodbye.但是当我运行程序时,它立即说再见.
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()
推荐答案
因为您在创建 self.button1
按钮时正在调用 self.bpress
:
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())
# ^^
只需删除括号并将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)
这篇关于为什么我的 Tk 按钮会被自动按下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文