2011-12-05 57 views
0

我想單擊列表中的項目時顯示圖像,但是當單擊該項目時,只有一個圖像正在顯示所有項目,但特定項目的圖像沒有被加載。綁定列表的內容點擊時顯示圖像

from Tkinter import * 
import os 
from PIL import Image 

root = Tk() 
scrollbar = Scrollbar(root) 
scrollbar.pack(side = RIGHT, fill=Y) 
mylist = Listbox(root, font = "verdana 15", yscrollcommand = scrollbar.set, height= 5, width = 10) 

def biscuit(self): 
    bi = Image.open('D://images/biscuit.jpeg') 
    bi.show() 

a = mylist.insert(END,str('Biscuit')) 
mylist.bind('<Button>', biscuit) 

def chocolate(self): 
    ch = Image.open('D://images/chocolate.jpeg') 
    ch.show() 

b = mylist.insert(END,str('Chocolate')) 
mylist.bind('<Button>', chocolate) 

def sandwich(self): 
    san = Image.open('D://images/sandwich.jpeg') 
    san.show() 

c = mylist.insert(END,str('Sandwich')) 
mylist.bind('<Button>', sandwich) 

def cake(self): 
    ca = Image.open('D://images/cake.jpeg') 
    ca.show() 

d = mylist.insert(END,str('Cake')) 
mylist.bind('<Button>', cake) 

mylist.pack() 
scrollbar.config(command = mylist.yview) 
mainloop() 

回答

0

您在您的按鈕事件綁定到ListBox不是在ListBox中的項目,所以當你點擊你的最後一個綁定。您需要檢查您的處理程序中選擇了哪個項目並打開正確的圖像。

喜歡的東西:

from Tkinter import * 
import os 
from PIL import Image 

root = Tk() 
scrollbar = Scrollbar(root) 
scrollbar.pack(side = RIGHT, fill=Y) 
mylist = Listbox(root, font = "verdana 15", yscrollcommand = scrollbar.set, height= 5, width = 10) 

pathToImages = ['D://images/biscuit.jpeg', 
'D://images/chocolate.jpeg','D://images/sandwich.jpeg', 
'D://images/cake.jpeg'] 

def buttonHandler(self): 
    bi = Image.open(pathToImages[int(mylist.curselection()[0])]) 
    bi.show() 

a = mylist.insert(END,str('Biscuit')) 
b = mylist.insert(END,str('Chocolate')) 
c = mylist.insert(END,str('Sandwich')) 
d = mylist.insert(END,str('Cake')) 

mylist.bind('<<ListboxSelect>>', buttonHandler) 

mylist.pack() 
scrollbar.config(command = mylist.yview) 
mainloop() 
+0

Thankz的答案馬克.. u能PLZ闡述如何讓我與sutable關鍵詞的要求是使用.. –

+0

@BharathGupta,請參閱代碼示例。 – Mark

+0

Thankz很多馬克.. –

相關問題