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

2024-05-03 08:58:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须构建一个应用程序来维护一个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()

当它现在是我的图形用户界面打开,当我关闭它,序列开始阅读。在


Tags: theserialguirootvariableslabelpackreader
1条回答
网友
1楼 · 发布于 2024-05-03 08:58:48

您可以使用root.after(miliseconds, function_name_without_brackets)定期运行函数readserial,而不使用while 1。在

在Linux上测试了虚拟COM端口/dev/pts/5/dev/pts/6。在

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

相关问题 更多 >