Reputation: 1367
why is this listbox not returning my selection? I added the returnSelected() function with a button thinking that it needed to be triggered. My goal is to create as simple a possible function that a user can select a reduced list, and I am clearly not understanding the tkinter flow.
import tkinter
def listboxinput3():
# <ListboxSelect> callback function and current selection
def cb(event):
label['text'] = str(event) + '\n' + str(lb.curselection())
def returnSelected():
myselection = [my_list[k] for k in lb.curselection()]
print(myselection )
root = tkinter.Tk()
root.title('Parameter Selection')
root.geometry('200x600')
my_list = dir(tkinter)
var = tkinter.StringVar(value=my_list)
label = tkinter.Label(root)
label.grid()
btnGet = tkinter.Button(root,text="Get Selection",command=returnSelected)
btnGet.grid()
lb = tkinter.Listbox(root, listvariable=var, selectmode='extended')
lb.grid()
lb.bind('<<ListboxSelect>>', cb)
#tkinter.Button(root, text="Show Selected", command=returnSelected).pack()
selected_text_list = [lb.get(i) for i in lb.curselection()]
root.mainloop()
return selected_text_list
selected_text_list = listboxinput3()
Thanks
Upvotes: 0
Views: 129
Reputation: 142641
It seems you don't know how GUI works. You create selected_text_list
before mainloop()
which starts program, displays window, gets your click, runs cb
and returnSelected
, etc. - so you create this list before you even see window and select item.
You have to create it inside function cb
or returnSelected
which is executed after you select item. And it will need global selected_text_list
to assing it to external variable because button
can't get it and assing it to external variable.
import tkinter
def listboxinput3():
# <ListboxSelect> callback function and current selection
def cb(event):
label['text'] = str(event) + '\n' + str(lb.curselection())
def returnSelected():
global selected_text_list
selected_text_list = [my_list[k] for k in lb.curselection()]
root = tkinter.Tk()
root.title('Parameter Selection')
root.geometry('200x600')
my_list = dir(tkinter)
var = tkinter.StringVar(value=my_list)
label = tkinter.Label(root)
label.grid()
btnGet = tkinter.Button(root, text="Get Selection", command=returnSelected)
btnGet.grid()
lb = tkinter.Listbox(root, listvariable=var, selectmode='extended')
lb.grid()
lb.bind('<<ListboxSelect>>', cb)
#tkinter.Button(root, text="Show Selected", command=returnSelected).pack()
# selected_text_list = [lb.get(i) for i in lb.curselection()] # useless - it is executed before you even see window
# display window, run function assigned to button when you click, etc.
root.mainloop()
return selected_text_list
selected_text_list = listboxinput3()
print(selected_text_list)
Upvotes: 1