我相信你是這樣的財產以後後:
import Tkinter
import time
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
button = Tkinter.Button(self,text=u"Click me !",
command=self.OnButtonClick)
button.grid(column=1,row=0)
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.i = 0; #<- make counter
def OnButtonClick(self):
print 'deep'
self.i += 1;
if self.i==10: return #<1-- stop if we hit 10 iterations
self.after(1000, self.OnButtonClick) #<- use this
def OnPressEnter(self,event):
self.labelVariable.set("You pressed enter !")
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('my application')
app.mainloop()
請看看的顯着變化。基本上,它更好地使用after
方法在給定時間做某事,而不是阻止整個tk窗口。因此,如果你想要執行某些東西10次,只需要保留計數器self.i
並使用self.after
方法調用OnButtonClick
。
作爲替代方案,您可以將循環放入單獨的線程中。例如:
import Tkinter
import time
import threading
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
button = Tkinter.Button(self,text=u"Click me !",
command=self.OnButtonClick)
button.grid(column=1,row=0)
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
# define a thread, but dont start it yet.
# start it when button is pressed.
self.t = threading.Thread(target=self.do_in_loop)
def do_in_loop(self):
# this will be executed in a separate thread.
for i in range(10):
print i, 'deep'
time.sleep(1)
def OnButtonClick(self):
# start the thread with the loop
# so that it does not block the tk.
if not self.t.isAlive():
self.t.start()
def OnPressEnter(self,event):
self.labelVariable.set("You pressed enter !")
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('my application')
app.mainloop()
你能分享任何日誌嗎? – aberna 2015-02-12 06:43:28
整個調試代碼在這裏。如果你可以運行,你可以很容易地看到在打印過程中掛着的「Click Me」按鈕 – 2015-02-12 06:46:09