【发布时间】:2025-11-23 18:45:02
【问题描述】:
快速提问:
我在 Python 3.6 上运行 TKinter 提示,我想从我的列表框中的 curselection 函数创建一个变量。我想保留该变量的字符串,以便以后可以使用它来命名其他变量。
这是我的代码:
#Extracting municipalities from shapefile
MunList = []
MunMap = arcpy.env.workspace +'\munic_s.shp'
cursor = arcpy.SearchCursor(MunMap)
for row in cursor:
MunVar = row.getValue("munic_s_24")
MunList.append(MunVar)
del cursor
MunList = sorted(MunList)
print(MunList)
def test(event=None):
#print(listbox.get(ACTIVE))
print(listbox.get(listbox.curselection()))
root = Tk()
root.title("Scrolldown Menu")
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(root, selectmode=SINGLE)
for lines in MunList:
listbox.insert(END, lines)
listbox.pack(side=LEFT,fill=BOTH)
listbox.config(yscrollcommand=scrollbar.set)
listbox.config(borderwidth=3, exportselection=0, height=20, width=50)
print(listbox.bbox(0))
(listbox.bind("<Double-Button-1>", test))
scrollbar.config(command=listbox.yview)
mainloop()
我创建了一个“测试”函数,它在我的光标上选择 ACTIVE 项目并通过双击将其绑定到我的列表框。当我运行它并双击列表中的任何名称时,它会打印出来。但是,我似乎无法从中创建一个字符串变量。当我尝试这样的事情时:
test_var = (listbox.bind("<Double-Button-1>", test))
print(test_var)
我得到了某种索引:
257891528test
但我需要变量的实际字符串(例如:Washington)
谢谢!
【问题讨论】:
-
可以在
test()函数中设置test_var:test_var = listbox.get(ACTIVE)。 -
它打印值,但只打印我列表的第一个条目,无论我是否双击另一个名称。例如,如果我的列表中有 100 个名称,我可以单击任何我想要的名称,但 test_var 的打印始终是我列表中的第一个名称。
-
我的示例代码中没有您的问题。您可以使用所做的更改更新问题中的代码吗?
标签: string tkinter listbox selection