Advertisement
here2share

# safe_threading_demo.py

Apr 18th, 2019
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: iso-8859-1 -*-
  3.  
  4. # safe_threading_demo.py
  5.  
  6. import Tkinter,threading,time
  7.  
  8. class MyProcess(threading.Thread):
  9.     def __init__(self,startValue):
  10.         threading.Thread.__init__(self)
  11.         self._stop = False
  12.         self._value = startValue
  13.        
  14.     def run(self):
  15.         while self._value>0 and not self._stop:
  16.             self._value = self._value - 1
  17.             print u"Thread: I'm working... (value=%d)" % self._value
  18.             time.sleep(1)
  19.         print u"Thread: I have finished."
  20.            
  21.     def stop(self):
  22.         self._stop = True
  23.  
  24.     def result(self):
  25.         return self._value
  26.  
  27. class MyGUI(Tkinter.Tk):
  28.     def __init__(self,parent):
  29.         Tkinter.Tk.__init__(self,parent)
  30.         self.parent = parent
  31.         self.initialize()
  32.         self.worker = MyProcess(15)
  33.         self.worker.start()  # Start the worker thread
  34.  
  35.     def initialize(self):
  36.         ''' Create the GUI. '''
  37.         self.grid()
  38.         button = Tkinter.Button(self,text=u"Click Me To Stop",command=self.OnButtonClick)
  39.         button.grid(column=1,row=0)
  40.         self.labelVariable = Tkinter.StringVar()
  41.         label = Tkinter.Label(self,textvariable=self.labelVariable)
  42.         label.grid(column=0,row=0)
  43.         self.labelVariable.set(u"Hello...  ")
  44.  
  45.     def OnButtonClick(self):
  46.         '''' Called when button is clicked. '''
  47.         self.labelVariable.set( u"Button clicked" )
  48.         self.worker.stop()  # We ask the worker to stop (it may not stop immediately)
  49.         while self.worker.isAlive(): # We wait for the worker to stop.
  50.             time.sleep(0.2)
  51.         # We display the result:
  52.         self.labelVariable.set( u"Result: %d  " % self.worker.result() )
  53.  
  54. if __name__ == "__main__":
  55.     app = MyGUI(None)
  56.     app.title('My Application')
  57.     app.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement