不幸的是,這似乎是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()
(建議,您可以調整字體,以及...這可以使它更容易調整width
和extra_whitespace
)