【发布时间】:2021-03-06 21:37:32
【问题描述】:
我设法让我的 tkinter 应用程序在文本字段上显示文本。
我通过硬编码 COM 端口和波特率来做到这一点,然后在我的程序开始时设置一个串行对象。
baudRate = 9600
ser = serial.Serial('COM16', baudRate)
然后我的所有代码都会运行。
但问题在于所有内容都是硬编码的。 我希望用户能够从下拉列表中选择 COM 端口。 当他选择一个端口时,串行通信应该开始了。
所以我就是这样做的。这是我的相关代码。
#hardcoded baud rate
baudRate = 9600
# this is the global variable that will hold the serial object value
ser = 0 #initial value. will change at 'on_select()'
#this function populates the dropdown on frame1, with all the serial ports of the system
def serial_ports():
return serial.tools.list_ports.comports()
#when the user selects one serial port from the dropdown, this function will execute
def on_select(event=None):
global ser
COMPort = cb.get()
string_separator = "-"
COMPort = COMPort.split(string_separator, 1)[0] #remove everything after '-' character
COMPort = COMPort[:-1] #remove last character of the string (which is a space)
ser = serial.Serial(port = COMPort, baudrate=9600)
return ser
readSerial() #start reading
#this function reads the incoming data and inserts them into a text frame
def readSerial():
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
text.insert("end", ser_bytes)
if vsb.get()[1]==1.0:
text.see("end")
root.after(100, readSerial)
当我从下拉列表中选择一个 COM 端口时会发生什么,我在设备的 LED 按钮上看到了传输。
但是,文本框架上没有显示任何内容。之前,当我对所有内容进行硬编码并在程序开始时设置串行对象,并在程序结束时声明readSerial() 函数时,一切正常。
【问题讨论】:
标签: python-3.x tkinter serial-port pyserial