I want to display an image when an item in a list is clicked, but when I click the item, only one image is being displaying for all the items but the specific item’s image is not getting loaded.
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()
You are binding your button event to the ListBox not the item in the ListBox, so when you click you get the last one binded. You need to check which item is selected in your handler and open the correct image.
Something like: