Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

python 3.x - Tkinter Listbox will not return selected element

The code is as follows:

import tkinter as tk
plc=tk.Tk()
choices=["A","B","C]
choicesvar=tk.StringVar(value=choices)
l=tk.Listbox(master=plc,listvariable=choicesvar)
l.pack()
selected=l.get(l.curselection())
plc.mainloop()

The idea is to get what element is currently selected. But all I'm getting is TclError: bad listbox index "": must be active, anchor, end, @x,y, or a number.

question from:https://stackoverflow.com/questions/65848027/tkinter-listbox-will-not-return-selected-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.curselections returns an empty tuple if nothing is selected. You are trying to get the user-selected input even before the user selects anything.

one way to overcome this is to set the default selection to the first row using .selection_set(0)

...
l=tk.Listbox(master=plc,listvariable=choicesvar)
l.pack()
l.selection_set(0)
print(l.get(l.curselection()))
...

But since you want to get user selected row, bind the <ButtonRelease> to an event handler then get the selected rows. something as shown below.

import tkinter as tk

def handler(event):
    print([l.get(index) for index in l.curselection()])
    

plc=tk.Tk()
choices=["A","B","C"]
choicesvar=tk.StringVar(value=choices)

l=tk.Listbox(master=plc,listvariable=choicesvar, selectmode=tk.MULTIPLE)
l.pack()
l.bind('<ButtonRelease>', handler)

plc.mainloop()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...