pythontkintertkinter-menu

Adding a list to a file submenu in tkinter


The variable ports_available contains an array of COMPORTS. I want these to be added to the submenu "ports_menu" on startup of the GUI so that I can select any one of them for selecting the 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]

Thank you, Dhruv Gupta


Solution

  • Based on the comments you posted, what you're wanting is to set a variable based on a menu selection. You can add radiobuttons to a menu with add_radiobutton. The use of radiobuttons will allow the user to make an exclusive choice.

    Here's an example:

    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()