如題,需要實現的功能是在tkinter的UI界面能根據serial接收到的數據刷新內容。
在嘗試過while循環裏mainloop更新、通過StringVar更新、通過update函數更新、通過after和sleep函數定時更新等操作,終於找到了正確的方法——多線程。(不排除其他某些方法我還不會用)
簡版代碼:
import serial,threading
import tkinter as tk
from tkinter import StringVar
window = tk.Tk()
window.title("My window")
window.geometry('500x300')
str = StringVar()
str.set('Start')
ser = serial.Serial('COM6')#我這裏用到的串口是COM6,若不同注意修改
ser.baudrate=9600
ReadyToStart = True
def startButton():
if(ReadyToStart):
str.set('Running')
button = tk.Button(window, textvariable=str, command=startButton).grid()
OutputText = tk.Text(window, wrap=tk.WORD, width=70, height=20)
OutputText.grid()
def ReadUART():#接收串口數據
while (True):
try:
idx = int.from_bytes(ser.read(1), byteorder='big', signed=False)#轉化爲整型數字
OutputText.insert(tk.END, idx)
OutputText.insert(tk.END, ' ')
#print(idx, end='')
except:
print("Something wrong")
ReadUARTThread = threading.Thread(target=ReadUART)#多線程
ReadUARTThread.start()
window.mainloop()
上述代碼運行後,在下位機發送數據時能在下圖框內接收到。
小學期苦苦掙扎,完成完整的想法後再上傳代碼