[英]python tkinter gui window freeze after a while with arduino serial communication
[英]Python run GUI while serial reader is running
我必須構建一個在串行讀取器不斷在后台運行時維護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打開,一旦我關閉它,串行開始讀取。
您可以使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.