pythontkinteroptionmenutkinter.optionmenu

How to get tkinter OptionMenu to display the name of the selected option?


In tkinter, I have created an option menu using the OptionMenu class. As an example, the OptionMenu below has options A, B, C, D, etc.:

self.clicked = tk.StringVar(self.parent)
self.clicked.set("Select Column")

self.drop = tk.OptionMenu(self.parent, self.clicked, 'Select Column', command=self.idle)
    for i in columnNames[:]:
        self.drop['menu'].add_command(label=i, command=tk._setit(self.clicked, i, self.select_data))
self.drop.pack()

Note: the function self.idle is just a lambda *args: None.

The function self.select_data is as follows:

def select_data(self):
    for col_name in df.columns:
        if col_name == self.clicked.get():
            self.option_display = col_name

The function self.select_data simply retrieves the option the user selects from the OptionMenu, but how would I update the OptionMenu to display the option selected in self.select_data?

As an example, if the user selects option A, how would I update the OptionMenu to show Aas selected?


Solution

  • The selectData() function should have the following signature:

    def selectData(self, selected):
        print(selected)
        # or print(self.clicked.get())