2017-04-08 70 views
0

的獲得指數我使用OptionMenu從下拉列表中選擇一個選項的Tkinter STRINGVAR選擇的選項

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

的選項可能包含重複

正因爲如此,當我想知道哪些選項被選中,我需要知道它在選項列表中的索引,而不僅僅是它的文本。

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

但是,這是O(n),也失敗重複。

如何找出選擇對象的索引,以重複的方式工作(效率首選但不是必需的)?

回答

0

不幸的是,這似乎是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

0
int(np.argwhere(List==value)) 

是接近,但無法識別重複