【问题标题】:Tkinter StringVar get index of selected optionTkinter StringVar 获取所选选项的索引
【发布时间】:2023-03-15 16:58:01
【问题描述】:

我正在使用 OptionMenu 从下拉列表中选择一个选项

self.var = tk.StringVar()
tk.OptionMenu(self, self.var, *self.options)

选项可能包含重复项

因此,当我想知道选择了哪个选项时,我需要知道它在选项列表中的索引,而不仅仅是它的文本。

self.options.index(self.var.get())

但是这是 O(n) 并且也会因重复而失败。

如何以适用于重复项的方式找出选择对象的索引(效率优先但不是必需的)?

【问题讨论】:

    标签: python tkinter python-3.6 optionmenu


    【解决方案1】:

    不幸的是,这似乎是impossible

    但是,我得到了一个(丑陋的)解决方法。它基于ttk.Combox(其中入口部分被禁用)。此方法在最后为每个选项附加一个计数器。由于小部件显示的最终宽度,该计数器未显示。 它相当有效地获取索引,但由于额外的空格,内存存储可能不是最佳的......

    import tkinter as tk
    from tkinter import ttk
    
    def set_index(text):
        output=()
        counter=0
        for s in text:
            output += (s.ljust(width+extra_whitespace)+str(counter),)
            counter += 1
        return output
    
    def get_index(*x):
        s= OptionVar.get()
        a = int(s[s.rfind(" "):])
        print(a)
        return a
    
    root = tk.Tk()
    
    text = ("a","a","a","a","d","g","fgggggggh","j","a","l","p","a","d","D")
    
    # not entirely sure if width is based on character_width
    # you should adjust these nubmer to your own needs....
    width = max(map(len,text)) + 3
    extra_whitespace = 20
    
    text_with_index = set_index(text)
    
    
    OptionVar = tk.StringVar()
    OptionVar.set(text_with_index[0])
    OptionVar.trace("w", get_index)
    
    O = ttk.Combobox(root, textvariable=OptionVar, values=text_with_index)
    O.pack()
    O.configure(width=width)
    O.configure(state="readonly")
    
    get_index()
    
    
    root.mainloop()
    

    (建议;你也可以调整字体...这样可以更容易调整widthextra_whitespace

    【讨论】:

      【解决方案2】:
      int(np.argwhere(List==value))
      

      已接近但无法识别重复项

      【讨论】:

        猜你喜欢
        • 2012-11-13
        • 1970-01-01
        • 2021-10-01
        • 2017-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-22
        相关资源
        最近更新 更多