I believe you are after somthing like this:
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()
Please have a look at marked changes. Basically, its better to use after
method do do something at given time and not to block whole tk window. Thus if you want something to be executed 10 times, just make some veriable to hold the counter self.i
and call OnButtonClick
using self.after
method.
As an alternative, you can put the loop into a separate thread. For example:
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()