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