Python 动态更改连接到列表框中项目的图像
我想在列表框中动态显示所选项目的图像。 文件夹中图像存储的名称与listbox中my tuple中索引为[0]的项完全相同Python 动态更改连接到列表框中项目的图像,python,tkinter,Python,Tkinter,我想在列表框中动态显示所选项目的图像。 文件夹中图像存储的名称与listbox中my tuple中索引为[0]的项完全相同 list1= Listbox(ViewFrame, height=15, width=75) files = glob.glob('img\\*.jpg') ImageFrame = LabelFrame(page1, text="Podgląd i parametry") ImageFrame.grid(row=6, column
list1= Listbox(ViewFrame, height=15, width=75)
files = glob.glob('img\\*.jpg')
ImageFrame = LabelFrame(page1, text="Podgląd i parametry")
ImageFrame.grid(row=6, column=6, pady=10, padx=5)
path = files[list1.curselection()[0]]
img = ImageTk.PhotoImage(Image.open(path))
label = Label(ImageFrame)
label.image = img
label.configure(image=img)
错误:
path=files[list1.curselection()[0]]
索引器错误:元组索引超出范围
在我看来,在我打开应用程序之前,没有选择任何内容,但我不知道如何修复它。检查是否在加载图像之前选择了某些内容 创建列表框时添加
list1.bind("<<ListboxSelect>>", on_item_selected)
开放的
if list1.curselection():
path = files[list1.curselection()[0]]
img = ImageTk.PhotoImage(Image.open(path))
label = Label(ImageFrame)
label.image = img
label.configure(image=img)
这是可运行的代码,但它只是@1966bc答案的一个更完整的版本,我创建了这个答案,因为你的问题不是:
导入全局
从tkinter进口*
从PIL导入图像,ImageTk
所选项目上的def(事件):
path=files[list1.curselection()[0]]
img=ImageTk.PhotoImage(Image.open(path))
label.image=img
label.configure(image=img)
root=Tk()
page1=帧(根)
第1页网格(行=0,列=0)
图幅=图幅(第1页)
ViewFrame.grid(行=0,列=0)
files=glob.glob('*.jpg')[:10]#将开发限制在前10个。
listvar=StringVar(值=文件)
list1=Listbox(图幅,高度=15,宽度=75,listvariable=listvar)
列表1.grid()
ImageFrame=LabelFrame(第1页,text=“Podgląd i参数”)
网格(行=6,列=6,pady=10,padx=5)
标签=标签(图像框)#创建占位符。
label.grid()
列表1.bind(“,在所选项目上)
root.mainloop()
I change my code-no errors by nothing显示的是正常的,现在您必须添加一个函数,在选择列表框的一行时加载图像。是的,我现在明白了,因为我不知道如何加载图像。。
if list1.curselection():
path = files[list1.curselection()[0]]
img = ImageTk.PhotoImage(Image.open(path))
label = Label(ImageFrame)
label.image = img
label.configure(image=img)
import glob
from tkinter import *
from PIL import Image, ImageTk
def on_item_selected(event):
path = files[list1.curselection()[0]]
img = ImageTk.PhotoImage(Image.open(path))
label.image = img
label.configure(image=img)
root = Tk()
page1 = Frame(root)
page1.grid(row=0, column=0)
ViewFrame = Frame(page1)
ViewFrame.grid(row=0, column=0)
files = glob.glob('*.jpg')[:10] # Limit to first 10 for development.
listvar = StringVar(value=files)
list1= Listbox(ViewFrame, height=15, width=75, listvariable=listvar)
list1.grid()
ImageFrame = LabelFrame(page1, text="Podgląd i parametry")
ImageFrame.grid(row=6, column=6, pady=10, padx=5)
label = Label(ImageFrame) # Create placeholder.
label.grid()
list1.bind("<<ListboxSelect>>", on_item_selected)
root.mainloop()