我正在结合使用 Python 3.4/5 和 Tkinter 制作一个小项目。我制作了一个列表框,显示目录中的所有项目。我似乎找不到一种方法来选择一个项目,然后将名称保存在一个变量中供以后使用。
listnotes = Listbox(notebox, selectmode=SINGLE)
listnotes.pack(side=LEFT, fill=Y, padx=10, pady=10)
listnotes.insert(END, "notes")
for i in glob.glob("\TESTFOLDER\*.txt"):
i = i[12:]
listnotes.insert(END, i)
我了解到使用 listnotes.get(ACTIVE) 可能有效。另外,我使用 python 的时间并不长,所以任何见解都将不胜感激。
请您参考如下方法:
你必须使用 Bindings为此,
例如:
listnotes.bind("<Return>", dosomething) #to bind to your enterkey
然后是与 Listbox 关联的 curselection 方法
def dosomething(event):
"""
on enter, capture the value from the Listbox
and assign the value captured to value via the get method form the selected value
"""
try:
selection = listnotes.curselection()
value = listnotes.get(selection[0])
except Exception as select:
print("Nothing selected")
pass
