从tkinter curselection中提取字符串变量

问题描述 投票:0回答:1

快速提问:

我在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()

我创建了一个'test'函数,用于选择光标上的ACTIVE项,并通过双击将其绑定到我的列表框。当我运行它并双击列表中的任何名称时,它会打印出来。但是,我似乎无法从中创建一个字符串变量。当我尝试这样的事情时:

test_var = (listbox.bind("<Double-Button-1>", test))
print(test_var)

我得到某种索引:

257891528test

但我需要变量的实际字符串(例如:华盛顿)

谢谢!

string tkinter listbox selection
1个回答
0
投票

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.