5

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.

DRdr
  • 1,171
  • 3
  • 12
  • 12
  • possible duplicate of [Getting a callback when a Tkinter Listbox selection is changed?](http://stackoverflow.com/questions/6554805/getting-a-callback-when-a-tkinter-listbox-selection-is-changed) – drevicko Nov 02 '13 at 00:08

1 Answers1

9

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()
Community
  • 1
  • 1
Cory Dolphin
  • 2,650
  • 1
  • 20
  • 30