Created
April 8, 2018 09:30
-
-
Save roosnic1/f1d1d17c663476af3279ab6ae3e80206 to your computer and use it in GitHub Desktop.
Python Tkinter GUI and Thread example (Python 2.7)
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
from Tkinter import * | |
import Queue | |
import time | |
import threading | |
def bluetooth_loop(thread_queue=None, text_input=""): | |
time.sleep(15) | |
thread_queue.put(text_input) | |
class App: | |
def __init__(self, master): | |
frame = Frame(master) | |
frame.pack() | |
self.root = frame | |
self.quit_button = Button(frame, text="QUIT", fg="red", command=frame.quit) | |
self.quit_button.pack(side=LEFT) | |
self.update_btn = Button(frame, text="Update", command=self.update_text) | |
self.update_btn.pack(side=LEFT) | |
self.text_label = Label(frame) | |
self.text_label.config(text='No message') | |
self.text_label.pack(side=RIGHT) | |
self.text_input = Entry(frame, width=40) | |
self.text_input.pack(side=RIGHT) | |
def update_text(self): | |
''' | |
Spawn a new thread for running long loops in background | |
''' | |
self.text_label.config(text='Running loop') | |
self.thread_queue = Queue.Queue() | |
self.new_thread = threading.Thread( | |
target=bluetooth_loop, | |
kwargs={'thread_queue':self.thread_queue,'text_input':self.text_input.get()}) | |
self.new_thread.start() | |
self.root.after(100, self.listen_for_result) | |
def listen_for_result(self): | |
''' | |
Check if there is something in the queue | |
''' | |
try: | |
res = self.thread_queue.get(0) | |
self.text_label.config(text=res) | |
except Queue.Empty: | |
self.root.after(100, self.listen_for_result) | |
root = Tk() | |
app = App(root) | |
root.mainloop() | |
root.destroy() # optional; see description below |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 55? what description below?