我正在使用OptionMenu从下拉列表中选择一个选项
self.var = tk.StringVar()
tk.OptionMenu(self, self.var, *self.options)
选项可以包含重复项
因此,当我想知道哪个选项被选中时,我需要知道它在选项列表中的索引,而不仅仅是它的文本。
self.options.index(self.var.get())
然而,这是O(n),并且在重复时也会失败。
我怎样才能找到select对象的索引,以一种处理重复的方式(效率优先,但不是必需的)?
发布于 2017-04-08 12:34:13
不幸的是,这似乎是impossible。
然而,我得到了一个(丑陋的)变通方法。它基于ttk.Combox
(其中entry-part被禁用)。此方法在最后将计数器附加到每个选项。由于widget-display的最终宽度,该计数器不会显示。它相当有效地获取索引,但由于额外的空格,内存的存储可能不是最佳的……
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()
(建议;您也可以调整字体...这可以更容易地调整width
和extra_whitespace
)
发布于 2017-11-07 22:55:03
int(np.argwhere(List==value))
已关闭,但无法识别重复项
https://stackoverflow.com/questions/43292974
复制相似问题