我早些时候发布了一个与此类似的复杂问题,但是方式要简单得多。 主要问题是每当我从下拉菜单中选择端口并尝试打开端口以从Arduino或无线调制解调器读取数据时。
每次我都要面对串口未打开的错误。
我用来固定COM端口的硬代码运行得很好
下面提到的是我简化并尝试使用的代码
import serial
import serial.tools.list_ports
from tkinter import *
ard = serial.Serial();
ard.baudrate = 9600
master = Tk()
variable = StringVar(master)
a=serial.tools.list_ports.comports()
for w in a:
print(w.device)
dev = [w.device]
print(dev)
variable.set(dev[0]) # default value
w = OptionMenu(master, variable, *dev)
w.pack()
ard.port = str(w)
ard.open
ard.is_open
#print(k)
def ok():
print (variable.get())
k = ard.readline()
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
但是每次遇到错误
COM4
['COM4']
COM4
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Misha\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\Misha\Desktop\test\autoserial.py", line 27, in ok
k = ard.readline()
File "C:\Users\Misha\AppData\Local\Programs\Python\Python36\lib\site-packages\serial\serialwin32.py", line 267, in read
raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open
请建议尽量帮助我完成这项工作,您的线索将对我有很大帮助。
答案 0 :(得分:1)
您的代码中包含ard.open
,但实际上并不是在调用打开串行连接的方法。这就是为什么您在输入Attempting to use a port that is not open
时出错。尝试ard.open()
看看是否可行。这应该打开您的端口并使其可用。
但是,给定设置之后,您可能希望将其包装在一个回调中,可以将其绑定到另一个按钮或OptionMenu
。似乎您会想要灵活地选择端口,并且只在选择一个端口后才打开端口。
下面是一个小例子:
import tkinter as tk
import serial
import serial.tools.list_ports
ard = serial.Serial();
ard.baudrate = 9600
a = serial.tools.list_ports.comports()
ports = [port.device for port in a]
def open_serial():
ard.port = variable.get()
ard.open()
print(f'Port {variable.get()} opened')
def close_serial():
p = ard.port
ard.close()
print(f'Port {p} closed')
master = tk.Tk()
variable = tk.StringVar()
variable.set(ports[0])
options = tk.OptionMenu(master, variable, *ports)
options.pack()
button_open = tk.Button(master, text='Open', command=open_serial)
button_open.pack()
button_close = tk.Button(master, text='Close', command=close_serial)
button_close.pack()
tk.mainloop()