如何找到Python tkinter的OptionMenu索引的索引?

2024-09-30 08:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个解决方案来找到chousen选项菜单选项的索引(编号)。 Python 3.8 值可以相同


Tags: 选项菜单解决方案编号chousen
2条回答

如果你不在乎使用字典,你可以这样做

import tkinter as tk


class Window:
    def __init__(self):
        self.root = tk.Tk()

        self.variable = tk.StringVar()
        self.variable.set('Option 1')
        self.options = {'Option 1', 'Option 2', 'Option 3'}
        self.option_menu = tk.OptionMenu(self.root, self.variable, *self.options)
        self.button = tk.Button(self.root, text="Button", command=self.on_click)
        self.option_menu.pack()
        self.button.pack()
        self.root.mainloop()

    def on_click(self):
        choice = self.variable.get()
        index = {'Option 1' : 0, 'Option 2': 1, 'Option 3': 2}[choice]
        print(index)

Window()

我只是抛出了tk.OptionMenu,改用了ttk.Combobox

相关问题 更多 >

    热门问题