-1

该变量ports_available包含一个 COMPORTS 数组。我希望在 GUI 启动时将这些添加到子菜单“ports_menu”中,以便我可以选择其中任何一个来选择 COMPORT。

global ports_available
ports_available = [comport.device for comport in serial.tools.list_ports.comports()]

global port_select
port_select = "COM1"

#Create Menu
my_menu = Menu(window)
window.config(menu = my_menu)

# Add Tool Menu
tool_menu = Menu(my_menu, tearoff = False)
my_menu.add_cascade(label = "Tools", menu = tool_menu)
tool_menu.add_command(label = "Bold", command =bold_it)
tool_menu.add_command(label = "Italic", command =italic_it)

#Menu for ports

ports_menu = Menu(tool_menu, tearoff = False)
tool_menu.add_cascade(label = "Ports", menu = ports_menu)

for name in ports_available:

    ports_menu.add_checkbutton(label = name, variable = port_select)

[![When i select any one of the option everything gets selected][1]][1]

谢谢你,德鲁夫·古普塔

4

1 回答 1

0

根据您发布的评论,您想要的是根据菜单选择设置一个变量。您可以使用 将单选按钮添加到菜单中add_radiobutton。单选按钮的使用将允许用户做出唯一的选择。

这是一个例子:

import tkinter as tk

ports = ["COM1", "COM2", "COM3"]

def show_value():
    print(f"selected port: {port_selection.get()}")

root = tk.Tk()

port_selection = tk.StringVar(value=ports[0])
menubar = tk.Menu(root)
port_menu = tk.Menu(menubar)
for port in ports:
    port_menu.add_radiobutton(label=port, value=port, variable=port_selection, command=show_value)

root.configure(menu=menubar)
menubar.add_cascade(label="Port", menu=port_menu)

root.mainloop()
于 2020-11-10T18:58:12.087 回答