本文介绍了Tkinter Optionmenu小部件中相同值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问optionmenu小部件中相同值的索引。在下面的代码中,无论我选择哪两个b字符,列表中的字符b都返回索引1。我需要根据列表中的索引位置来区分两个b字符,即从optionmenu小部件中选择第一个b应该返回索引1而第二个b应该返回索引2.请告诉我该怎么做。提前致谢。

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


推荐答案

这不是怎么回事选项菜单旨在工作。您必须创建自定义选项菜单。选项菜单并不特别,它只是一个按钮和一个菜单,还有一些功能可以让它具有它所具有的行为。

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.

从可用性的角度来看,这是一个非常糟糕的设计,因为用户无法知道第一个b选择和第二个b选择之间的区别。我希望一个选择不会映射到停用炸弹而另一个选择是爆炸炸弹。

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".

这篇关于Tkinter Optionmenu小部件中相同值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:18