Adding a check next to the selected item in tkinter OptionMenu

320 Views Asked by At

How could I add a check sign next to the currently selected item (or highlight it) in a OptionMenu in a tkinter GUI? The idea is that when I click again to select another item, I can see easily which one is selected (similar to the following picture)

enter image description here

I just added a new example:

from tkinter import *

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
] 

app = Tk()

app.geometry('100x200')

variable = StringVar(app)
variable.set(OptionList[0])

opt = OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")


labelTest = Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")

def callback(*args):
    labelTest.configure(text="The selected item is {}".format(variable.get()))

variable.trace("w", callback)

app.mainloop()
2

There are 2 best solutions below

0
On BEST ANSWER

Just use ttk widgets for this modern looking style, try saying something like:

from tkinter import ttk
....
     #arguments  -  master  variable     default      *values
opt = ttk.Optionmenu(app, variable, OptionList[0], *OptionList)

The effect given by this is pretty similar or maybe identical to what your trying to achieve.

You might notice an additional third positional argument here, it is actually default=OptionList[0] argument specified here(specific to just ttk.Optionmenu), it is just the default value that the optionmenu will display, ignoring this might lead to some bugs in the looks of optionmenu, like this.

And also keep in mind, it does not have a font option too. To overcome this, check this out

Hope this was of some help to you, do let me know if any errors or doubts.

Cheers

0
On

You can get similar effect using tk.OptionMenu:

from tkinter import *

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
] 

app = Tk()

app.geometry('300x200')

variable = StringVar(app)
variable.set(OptionList[0])

opt = OptionMenu(app, variable, None) # need to supply at least one menu item
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")

# populate the menu items
menu = opt['menu']
menu.delete(0) # remove the None item
for item in OptionList:
    menu.add_radiobutton(label=item, variable=variable)

labelTest = Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")

def callback(*args):
    labelTest.configure(text="The selected item is {}".format(variable.get()))

variable.trace("w", callback)

app.mainloop()