multithreading - Python run GUI while serial reader is running -


i have build application maintains gui while serial reader running in background. serial reader updates variables need show on gui. far have this:

# these variables updated reader. var1 = 0 var2 = 0 var3 = 0  #serial reader def readserial(self): ser = serial.serial(port='com4', baudrate=9600, timeout=1) while 1:     b = ser.readline()     if b.strip():         #function set variables var1,var2,var3         handle_input(b.decode('utf-8'))  #simple gui show variables updating live root = tk() root.title("a simple gui")  gui_var1 = intvar() gui_var1.set(var1)  gui_var2 = intvar() gui_var2.set(var2)  gui_var3 = intvar() gui_var3.set(var3)  root.label = label(root, text="my gui") root.label.pack()  root.label1 = label(root, textvariable=gui_var1) root.label1.pack()  root.label2 = label(root, textvariable=gui_var2) root.label2.pack()  root.label3 = label(root, textvariable=gui_var3) root.label3.pack()  root.close_button = button(root, text="close", command=root.quit) root.close_button.pack()  #start gui , serial root.mainloop() readserial() 

as gui opens , close serial starts reading.

you can use root.after(miliseconds, function_name_without_brackets) run function readserial periodically - without while 1.

tested on linux virtual com ports /dev/pts/5, /dev/pts/6.

import tkinter tk import serial   # --- functions ---  def readserial():     b = ser.readline()     if b.strip():          label['text'] = b.decode('utf-8').strip()     # run again after 100ms (mainloop it)     root.after(100, readserial)  # --- main ---  ser = serial.serial(port='com4', baudrate=9600, timeout=1) #ser = serial.serial(port='/dev/pts/6', baudrate=9600, timeout=1)  root = tk.tk()  label = tk.label(root) label.pack()  button = tk.button(root, text="close", command=root.destroy) button.pack()  # run readserial first time after 100ms (mainloop it) root.after(100, readserial)  # start gui root.mainloop() 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -