Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Listbox

I want to execute function with one click on listbox. This is my idea:

from Tkinter import *
import Tkinter

def immediately():
    print Lb1.curselection()

top = Tk()

Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")

Lb1.pack()


Lb1.bind('<Button-1>', lambda event :immediately() )
top.mainloop()

But this function print before execute selecting...You will see what is the problrm when you run this code.

like image 397
DRdr Avatar asked Dec 27 '11 18:12

DRdr


People also ask

How do I add to a Listbox in Python?

A listbox shows a list of options. You can then click on any of those options. By default it won't do anything, but you can link that to a callback function or link a button click. To add new items, you can use the insert() method.

What is the use of Listbox widget give an example to add elements to Listbox using tkinter?

The Listbox widget is used to display the list items to the user. We can place only text items in the Listbox and all text items contain the same font and color. The user can choose one or more items from the list depending upon the configuration.

What is the use of Listbox widget?

The Listbox widget is used to display a list of items from which a user can select a number of items.


1 Answers

You can bind to the <<ListboxSelect>> event as described in this post: Getting a callback when a Tkinter Listbox selection is changed? TKinter is somewhat strange in that the information does not seemed to be contained within the event that is sent to the handler. Also note, there is no need to create a lambda that simply invokes your function immediately, the function object can be passed in as shown:

from Tkinter import *
import Tkinter

def immediately(e):
    print Lb1.curselection()


top = Tk()

Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")

Lb1.pack()


Lb1.bind('<<ListboxSelect>>', immediately)
top.mainloop()
like image 179
Cory Dolphin Avatar answered Oct 04 '22 14:10

Cory Dolphin