我希望在单击列表中的项目时显示图像,但是当我单击该项目时,只有一个图像正在显示所有项目,但特定项目的图像未加载。
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 :(得分: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()