-1

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?

  • In your case, `self.selectData()` should expect a argument which is the selected item. – acw1668 Jun 17 '20 at 05:47
  • What argument exactly? I'm a bit confused...in `self.selectData()`, I'm trying to print out the selected option from the OptionMenu. – ephemeralhappiness Jun 17 '20 at 06:12
  • 1
    The `selectData` function should be something like that: `def selectData(self, selected)` where `selected` will be the selected item of the `OptionMenu`. Or you can use `self.clicked.get()` inside the function to get the selected item. – acw1668 Jun 17 '20 at 06:20
  • If I were to do `def selectData(self, selected)`, would the code inside simply be `print(selected.get())` by calling `self.selectData(self.clicked)`. Also, the `self.clicked.get()` worked for me. – ephemeralhappiness Jun 17 '20 at 06:28

2 Answers2

1

The selectData() function should have the following signature:

def selectData(self, selected):
    print(selected)
    # or print(self.clicked.get())
acw1668
  • 40,144
  • 5
  • 22
  • 34
0

This will print the dropdown selection to the console. but my suggestion is to avoid console in GUI based applications. create a text indicator and print output to it

from tkinter import *
tk = Tk()
def OptionMenu_SelectionEvent(event):
    print(var.get())
    pass
var = StringVar(); var.set("one")
options = ["one", "two", "three"]
OptionMenu(tk, var, *(options), command = OptionMenu_SelectionEvent).pack()
tk.mainloop()
Vignesh
  • 1,553
  • 1
  • 10
  • 25