user-interfacetkinteroptionmenutkinter.optionmenu

Adding a check next to the selected item in tkinter OptionMenu


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

Solution

  • 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