Created
June 26, 2019 19:13
-
-
Save vobject/a5715ad2bf7365ec4a6750280432b1db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import tkinter as tk | |
import time | |
import datetime | |
import threading | |
import random | |
import queue | |
import enum | |
class WorkerThread(threading.Thread): | |
def __init__(self, msg_queue, is_running): | |
super().__init__() | |
self.msg_queue = msg_queue | |
self.is_running = is_running | |
def run(self): | |
while True: | |
if not self.is_running(): | |
break; | |
i = random.randint(1,101) | |
print(f'{datetime.datetime.now()}: put into queue {i} (size={self.msg_queue.qsize()})') | |
self.msg_queue.put(i) | |
time.sleep(.5) | |
print(str(datetime.datetime.now()) + ': shutting down thread') | |
class MainFrame(tk.Frame): | |
def __init__(self, master, msg_queue): | |
super().__init__(master) | |
self.msg_queue = msg_queue | |
self.val1 = tk.StringVar() | |
self.val2 = tk.StringVar() | |
self.val3 = tk.StringVar() | |
self.grid() | |
self.createWidgets() | |
self.cycle() | |
def createWidgets(self): | |
tk.Label(self, textvariable=self.val1).grid() | |
tk.Label(self, textvariable=self.val2).grid() | |
tk.Label(self, textvariable=self.val3).grid() | |
tk.Button(self, text='Quit', command=self.quit).grid() | |
def updateWidgets(self): | |
self.val1.set(str(datetime.datetime.now())) | |
while not self.msg_queue.empty(): | |
msg = self.msg_queue.get() | |
self.val2.set(str(msg)) | |
self.val3.set('thats it') | |
def cycle(self): | |
self.updateWidgets() | |
self.master.after(200, self.cycle) | |
class Application: | |
def __init__(self): | |
self.running = False | |
self.is_running = lambda: self.running | |
self.msg_queue = queue.Queue() | |
self.worker_thread = WorkerThread(self.msg_queue, self.is_running) | |
self.main_frame = None | |
def run(self): | |
self.running = True | |
self.worker_thread.start() | |
self.main_frame = MainFrame(None, self.msg_queue) | |
self.main_frame.master.title('Application Title') | |
self.main_frame.mainloop() | |
self.running = False | |
self.worker_thread.join() | |
def main(): | |
app = Application() | |
app.run() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment