Reputation: 590
In Tkinter, I am using root.after() to create thread and update GUI label according to function return value. I want to use same function recursively and update the label according to changing return value of function.
But, it seems thread is calling function only once and terminate. How do I make my thread to call function recursively ? Here is the code which print getData() only twice and terminate.
def recusriveDataFetch( self ):
self.sched = sched.scheduler(time.time, time.sleep)
self.sched.enter(100, 2, self.getData(), ()) #create getData() event after every 100 ms
self.sched.run()
def rootWindow( self ):
self.root = Tkinter.Tk()
self.root.title("Hello World")
self.getData()
self.root.after( 1000, thread.start_new_thread, self.recusriveDataFetch, () )
self.root.mainloop()
def getData( self ):
print " When I will be called multiple times\n "
Any help will be appreciated. Thanks
Upvotes: 0
Views: 4085
Reputation: 78
Something to note here, is to be very careful how you implement this. Tkinter is not threadsafe, and I've been bitten by this a couple of times. I really love it as far as a GUI toolkit, but you need to keep that in mind. Just make sure nothing inside the thread is interacting with anything in the Tkinter instance.
How I might do this:
def recusriveDataFetch(self):
self.sched = sched.scheduler(time.time, time.sleep)
self.sched.enter(100, 2, self.getData(), ()) #create getData() event after every 100 ms
self.sched.run()
def dataFetchWrapper(self, repeat=True):
thread.start_new_thread(self.recusriveDataFetch)
if repeat:
self.root.after(100, self.dataFetchWrapper)
def rootWindow(self):
self.root = Tkinter.Tk()
self.root.title("Hello World")
self.getData()
self.root.after(1000, self.dataFetchWrapper)
self.root.mainloop()
def getData(self):
print " When I will be called multiple times\n "
Upvotes: 1
Reputation: 538
Just make the getData function call the root.after method again:
def rootWindow(self):
self.root = Tkinter.Tk()
self.root.title("Hello World")
self.getData()
self.root.mainloop()
def getData(self):
print("I will be called multiple times")
self.root.after(1000, self.getData)
Hope this helps!
Upvotes: 2