Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Dropdown options menu using Enum

I'm trying to make a window that will hold all the current data for an object, and will let me change it. I'm stuck on how to make the options menu hold values of the enum and to save the selection as the correct enum key.

Here is my current code, which is being called on the button click:

current = tk.StringVar()
current .set(self.CustomEnum.value)
tk.OptionMenu(infoMenu, current, [e.value for e in CustomEnum]).pack()

This is the result of the list comprehension:

['Option 1', 'Option 2', 'Option 3']

I'm more focused on getting it to display correctly as right now the only option in the menu is

Option1 {Option 2} {Option 3}

Minimum reproducible example:

import tkinter as tk
from enum import Enum

window = tk.Tk()

class CustomEnum(Enum):
    Option1 = "Option1"
    Option2 = "Option2"

current = tk.StringVar()
current .set(CustomEnum.Option1.value)
tk.OptionMenu(window, current, [e.value for e in CustomEnum]).pack()

window.mainloop()
like image 474
FallingInForward Avatar asked Jun 30 '26 07:06

FallingInForward


1 Answers

As I already pointed out in a comment, you just needed to add an * character to the line that creates the OptionMenu widget to unpack the list of values in the list. This is required because each one of them needs to each be passed as separate argument.

Although not strictly necessary, I would also suggest changing the definition of the custom Enum to make it a little more succinct, as well as make a few other minor changes to the code.

Here's the result:

from enum import Enum
import tkinter as tk

window = tk.Tk()

CustomEnum = Enum(value='CustomEnum',
                  names='Option1 Option2 Option3')

current = tk.StringVar(value=CustomEnum.Option1.name)
tk.OptionMenu(window, current, *[option.name for option in CustomEnum]).pack()
#tk.OptionMenu(window, current, *list(CustomEnum.__members__)).pack()  # An alternative.

window.mainloop()
like image 175
martineau Avatar answered Jul 01 '26 22:07

martineau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!