Python在串行阅读器运行时运行GUI

时间:2016-11-13 14:01:16

标签: python multithreading tkinter pyserial

我必须构建一个维护GUI的应用程序,同时串行读取器在后台持续运行。串行读取器更新我需要在GUI上显示的变量。到目前为止我有这个:

# 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()

现在我的gui打开了,当我关闭它时,序列开始读取。

1 个答案:

答案 0 :(得分:2)

您可以使用root.after(miliseconds, function_name_without_brackets)定期运行功能readserial - 不使用while 1

在具有虚拟COM端口/dev/pts/5/dev/pts/6

的Linux上测试
import tkinter as tk
import serial 

# --- functions ---

def readserial():
    b = ser.readline()
    if b.strip():
         label['text'] = b.decode('utf-8').strip()
    # run again after 100ms (mainloop will do 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 will do it)
root.after(100, readserial)

# start GUI
root.mainloop()
相关问题