Index of same values in Tkinter Optionmenu widget

こ雲淡風輕ζ 提交于 2019-12-13 01:53:49

问题


I am trying to access the index of same values in optionmenu widget. In the following code, character "b" from the list returns index 1 no matter which of the two "b" characters I select. I need to differentiate both "b" characters based on their index position in the list i.e. selecting 1st "b" from the optionmenu widget should return index 1 while 2nd "b" should return index 2. Please tell me how to do it. Thanks in advance.

from Tkinter import *

class GUI(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.master.title("New window")
        self.master.geometry("300x200")
        self.grid()

        self.list1 = ["a", "b", "b"]

        self.var = StringVar()
        self.var.set("")
        self.entry = Entry(self, textvariable=self.var)
        self.entry.grid(row=0, column=0)
        self.optionMenu = OptionMenu(self, self.var, *self.list1)
        self.optionMenu.grid(row=0, column=1)

        self.button = Button(self, text="Print", command=self.print_fun)
        self.button.grid(row=0, column=2)

    def print_fun(self):
        print self.optionMenu["menu"].index(self.var.get())

obj = GUI()

obj.mainloop()

回答1:


This isn't how the option menu is designed to work. You'll have to create a custom option menu. An option menu isn't anything special, it's just a button and a menu, and a couple of functions to give it the behavior that it has.

From a usability perspective this is a very bad design, since the user has no way of knowing the difference between the first "b" choice and the second "b" choice. I hope one choice doesn't map to "deactivate the bomb" and the other is "explode the bomb".



来源:https://stackoverflow.com/questions/27826296/index-of-same-values-in-tkinter-optionmenu-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!