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
321 views
in Technique[技术] by (71.8m points)

python - tkinter listbox get(ACTIVE) method

I was trying to make the currently selected Listbox item to be printed out. For example, when I select item "one", it should print out "one" and when I select item "two", it should print out "two" etc. The following is what I have tried.

from Tkinter import*
root=Tk()
sizex = 600
sizey = 400
posx  = 40
posy  = 20
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
itemsforlistbox=['one','two','three','four','five','six','seven']

def CurSelet(evt):
    value=str((mylistbox.get(ACTIVE)))
    print value

mylistbox=Listbox(root,width=60,height=10,font=('times',13))
mylistbox.bind('<<ListboxSelect>>',CurSelet)
mylistbox.place(x=32,y=90)

for items in itemsforlistbox:
    mylistbox.insert(END,items)
root.mainloop()

My problem is whenever I selected an item in the listbox, it is actually printing out the previously selected item.For example, the moment I select the item "two" in the list, it is printing out "one". To make things more clear,please see the following

  1. I selected the item "one", it printed out "one"
  2. I selected the item "two", it print out "one" again
  3. I selected the item "three", it print out "two" and so on...

Am I missing something? or did I misunderstand the way the get(ACTIVE) works?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

An item becomes active after you click on it—which means after your ListboxSelect method returns. So, you're printing out whatever was active before this click (meaning, generally, what you clicked last time).

Also, given that you refer to "selected" numerous times, I think what you want is the selected value(s), not the active one, so you should be asking for that.

For a listbox with selectmode=SINGLE or BROWSE (the default, what you have) listbox, you can fix both of these trivially. Just change this:

mylistbox.get(ACTIVE)

to:

mylistbox.get(mylistbox.curselection())

If you need to handle MULTIPLE or EXTENDED, then of course there are anywhere from 0 to 7 selections instead of exactly 1, so you need to do something like:

values = [mylistbox.get(idx) for idx in mylistbox.curselection()]
print ', '.join(values)

While we're at it, I'm not sure why you were doing str((mylistbox.get(ACTIVE))), or even str(mylistbox.get(ACTIVE)). The result of mylistbox.get with a single index is going to be a string, the same one you inserted.


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

...