I have to build an application that maintains a GUI while a serial reader is constantly running in the background. The serial reader updates variables that i need to show on my GUI. So far i have this:
# These variables are updated by the 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 to set variables var1,var2,var3
handle_input(b.decode('utf-8'))
#Simple GUI to show the 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 and Serial
root.mainloop()
readserial()
As it is now my gui opens and as soon as i close it the serial starts reading.
mainloop()doesn't return until the root window is destroyed?while 1andmainloop. They have to work at the same time. You can userthreadingmodule to runwhile 1in separated thread. Orroot.after(miliseconds, function_name)to runser.readline() ...periodicaly (withoutwhile 1).aftermay not work ifreadlineblocks program waiting for data.