【问题标题】:Extracting string variable from tkinter curselection从 tkinter curselection 中提取字符串变量
【发布时间】: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_vartest_var = listbox.get(ACTIVE)
  • 它打印值,但只打印我列表的第一个条目,无论我是否双击另一个名称。例如,如果我的列表中有 100 个名称,我可以单击任何我想要的名称,但 test_var 的打印始终是我列表中的第一个名称。
  • 我的示例代码中没有您的问题。您可以使用所做的更改更新问题中的代码吗?

标签: string tkinter listbox selection


【解决方案1】:

如果有人有同样的问题,我找到了答案:

root = Tk()
root.title("TEST_TK_Scroll menu")
# Add a grid
mainframe = Frame(root)
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
mainframe.pack(pady=100, padx=100)
def close_window ():
    root.destroy()
button = Button (text= 'Confirm selection', command=close_window)
button.pack()
sel=[]
def selection(event):
    selected = (listbox.get(listbox.curselection()))
    print(selected)
    sel.append(selected)
scrollbar = Scrollbar(mainframe)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(mainframe, 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)
#cur1 = listbox.get(selected)
#index1 = listbox.get(0, "end").index(cur1)
(listbox.bind("<Double-Button-1>", selection))
print(listbox.bbox(0))
root.mainloop()
print('answer :')
print(sel)
def attempt2(string):
    for v in ("[", "]", "'"):
        string = string.replace(v, "")
    return string
select=sel[0]
attempt2(select)
print(select)

【讨论】: