2011-12-27 60 views
4

我想單擊列表框來執行功能。這是我的想法:Tkinter Listbox

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

但這個功能打印之前執行選擇......你會看到什麼是problrm當你運行該代碼。

+0

的可能重複[當Tkinter的列表框選擇改變獲取回調?] (http://stackoverflow.com/questions/6554805/getting-a-callback-when-a-tkinter-listbox-selection-is-changed) – drevicko 2013-11-02 00:08:39

回答

8

您可以綁定到在這篇文章中描述的<<ListboxSelect>>事件:Getting a callback when a Tkinter Listbox selection is changed? 使用TKinter是該信息不似乎包含發送到處理程序的事件中有些奇怪。還要注意,沒有必要創建一個lambda,簡單地調用你的函數immediately,函數對象可以傳遞的,如下所示:

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

非常好,tnx :) – DRdr 2011-12-27 18:35:40