从一个函数(从tkinter交互调用)设置串行对象



我设法让我的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按钮上有传输。

但是,文本框架上不显示任何内容。在此之前,当我硬编码所有内容并在程序开始时设置serialobject,并在程序结束时启动readSerial()函数时,一切都正常。

on_select函数中,您在调用readSerial()函数之前调用了returnreturn语句终止函数的执行,其后的任何语句都不会被执行。删除它将使程序工作。

此外,由于on_select是下拉框的回调,return语句是多余的,因为它没有任何地方可以返回。global ser负责将新值全局赋给ser变量。

您不需要在每次选择新选项时都调用readSerial()函数(否则,每次都会增加计划调用的数量)。你可以有一个按钮,一旦你初始配置它并从on_select中删除对readSerial()的调用,或者创建一个标志,确保它只被调用一次。


根据您的评论,我创建了以下示例,您可以尝试这样做

from tkinter import *
def on_select(event):
global value
value=option.get()
if stop_:
start_button['state']='normal'
def start():
global stop_
stop_=False
readSerial()
start_button['state']='disabled'
stop_button['state']='normal'
def stop():
global stop_
stop_=True
root.after_cancel(after_id)
start_button['state']='normal'
stop_button['state']='disabled'
def readSerial():
global after_id
text.insert(END,value)
after_id=root.after(100,readSerial)
root=Tk()
text=Text(root)
text.pack(side='bottom')
options=['1','2']
option=StringVar()
om=OptionMenu(root,option,*options,command=on_select)
om.pack(side='left')
start_button=Button(root,text='start',command=start,state='disabled')
start_button.pack(side='left')
stop_button=Button(root,text='stop',command=stop,state='disabled')
stop_button.pack(side='left')
stop_=True
root.mainloop()

最新更新