【问题标题】:Tkinter - get selected COM port from comboboxTkinter - 从组合框中获取选定的 COM 端口
【发布时间】:2020-05-05 21:50:36
【问题描述】:

我有一个包含所有串行端口列表的复选框,用户从组合框中选择一个,以便稍后与 arduino 交互。

以下是有趣的部分:

# --- functions ---
def serial_ports():    
    return serial.tools.list_ports.comports()

def on_select(event=None):

    # get selection from event    
    print("event.widget:", event.widget.get())

    # or get selection directly from combobox
    print("comboboxes: ", cb.get())

# --- functions ---



label0 = tk.Label(frame1, text="Select the COM port that the device is plugged in: ")
label0.config(font=("TkDefaultFont", 8))
label0.place(relx = 0.1, rely=0.3, relwidth=0.3, relheight=0.5)


cb = ttk.Combobox(frame1, values=serial_ports())
cb.place(relx=0.5, rely=0.5, anchor='center')
# assign function to combobox
cb.bind('<<ComboboxSelected>>', on_select)

cb.bind() 将选择设为on_select()。但是,当我使用 on_select() 函数打印用户选择的数据时,我得到:

event.widget: COM14 - Arduino Mega 2560 (COM14)

我只想获取 COM 端口,例如“COM14” 这样就可以在变量中赋值,以后可以这样使用:

ser = serial.Serial('COM14', baudRate, timeout=0, writeTimeout=0)

在哪里而不是'COM14',我将只拥有我的变量。

有没有pySerial的方法,只获取COM端口,没有完整的描述?

【问题讨论】:

    标签: python tkinter serial-port pyserial


    【解决方案1】:

    serial.tools.list_ports.comports() 的结果是serial.tools.list_ports.ListPortInfo 实例的列表。

    因此,如果您只想拥有端口名称,请更改

    def serial_ports():
        return serial.tools.list_ports.comports()
    

    def serial_ports():
        return [p.device for p in serial.tools.list_ports.comports()]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2022-08-18
      相关资源
      最近更新 更多