Tkinter列表框

时间:2011-12-27 18:01:47

标签: python listbox tkinter

我想在列表框上单击一下来执行功能。这是我的想法:

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()

但是这个函数在执行选择之前打印...你会看到运行这段代码时的问题是什么。

1 个答案:

答案 0 :(得分:8)

您可以按照此帖中所述绑定<<ListboxSelect>>事件:Getting a callback when a Tkinter Listbox selection is changed? TKinter有点奇怪,因为信息似乎不包含在发送给处理程序的事件中。另请注意,不需要创建只调用函数immediately的lambda,函数对象可以如图所示传入:

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()