code_junkie

How do you run your own code alongside Tkinter's event loop

Nov 13th, 2011
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. from Tkinter import *
  2. root=Tk()
  3. def task():
  4. print "hello"
  5. root.after(2000,task) # reschedule event in 2 seconds
  6.  
  7. root.after(2000,task)
  8. root.mainloop()
  9.  
  10. def after(self, ms, func=None, *args):
  11. """Call function once after given time.
  12.  
  13. MS specifies the time in milliseconds. FUNC gives the
  14. function which shall be called. Additional parameters
  15. are given as parameters to the function call. Return
  16. identifier to cancel scheduling with after_cancel."""
  17.  
  18. import Tkinter
  19. import threading
  20. class MyTkApp(threading.Thread):
  21. def __init__(self):
  22. threading.Thread.__init__(self)
  23. self.start()
  24. def callback(self):
  25. self.root.quit()
  26. def run(self):
  27. self.root=Tkinter.Tk()
  28. self.root.protocol("WM_DELETE_WINDOW", self.callback)
  29. self.s = Tkinter.StringVar()
  30. self.s.set('Foo')
  31. l = Tkinter.Label(self.root,textvariable=self.s)
  32. l.pack()
  33. self.root.mainloop()
  34. app = MyTkApp()
  35. print 'now can continue running code while mainloop runs'
  36.  
  37. import Tkinter
  38. import threading
  39.  
  40. class MyTkApp(threading.Thread):
  41. def __init__(self):
  42. self.root=Tkinter.Tk()
  43. self.s = Tkinter.StringVar()
  44. self.s.set('Foo')
  45. l = Tkinter.Label(self.root,textvariable=self.s)
  46. l.pack()
  47. threading.Thread.__init__(self)
  48.  
  49. def run(self):
  50. self.root.mainloop()
  51.  
  52.  
  53. app = MyTkApp()
  54. app.start()
  55.  
  56. # Now the app should be running and the value shown on the label
  57. # can be changed by changing the member variable s.
  58. # Like this:
  59. # app.s.set('Bar')
  60.  
  61. def task():
  62. #do stuff
  63. root.update()
  64. while 1:
  65. task()
Add Comment
Please, Sign In to add comment