如果在事件处理程序中添加,则不会显示 Tk 窗口中的图像


  1. 我正在尝试将照片绑定到列表框,但照片没有出现。

  2. 我试图在这里拍摄特定的照片路径。 使用上面的相同代码(在choosePhoto中),它起作用了。由于某种原因,当在函数内部的代码中并将函数绑定到listBox时,照片不会出现。

我的代码:

from tkinter import *
from PIL import ImageTk, Image
from os import *
def openPath(path,listBox):
    try:
       path2=str(path)
       list1= listdir(path2)
       listBox.delete(0,END)
       for i in range(len(list1)):
           listBox.insert(i,list1[i])
    except:
        print("file does not exist")
def choosePhoto(event):
    path=str(textFolder.get())+"\"+str(listBoxPath.get(ACTIVE))
    image1=ImageTk.PhotoImage(Image.open(path))
    lbl.configure(image=image1)
    print(path)

root = Tk()
root.geometry("450x600")
root.title("project image proccesor")
frame1=Frame(root,width=250,height=100)
frame1.pack(side=LEFT,fill=BOTH)
frame4=Frame(root,width=250,height=100)
frame4.pack(side=RIGHT,fill=BOTH)
lblFolder=Label(frame1,text="Enter folder path:")
lblFolder.grid(row=0,column=0)
textFolder=Entry(frame1,insertwidth=4)
textFolder.grid(rowspan=1,column=0)
listBoxPath=Listbox(frame1)
listBoxPath.grid(row=2)
bChoose=Button(frame1,text="Choose",command=lambda: openPath(textFolder.get(),listBoxPath)).grid(row=1,column=1)
lbl=Label(frame4, text="waiting for photo")
listBoxPath.bind('<<ListboxSelect>>', choosePhoto)
root.mainloop()

我可以在您的代码中看到 3 个问题。

第一。您需要将 image1 定义为全局图像,因为此图像当前是函数中的局部变量,一旦函数完成,图像将被删除,除非您在全局命名空间中定义它。

2nd. 用于显示图像的标签尚未放置在屏幕上。在这种情况下,您需要使用一些几何管理器(可能是grid())来显示图像。

第三。您当前在列表框的选择中使用ACTIVE。这将导致您在单击之前选择活动的内容,而不是刚刚单击的内容。

更改此设置:

list_box_path.get(ACTIVE)

对此:

list_box_path.get(list_box_path.curselection())

我已经清理了您的代码以更接近 PEP8 标准,并添加了一些小的更改并减少了不需要的代码部分。

import tkinter as tk
from PIL import ImageTk, Image
from os import listdir

def open_path(path):
    try:
        list1 = listdir(path)
        list_box_path.delete(0, "end")
        for i in range(len(list1)):
            list_box_path.insert(i, list1[i])
    except:
        print("file does not exist")

def choose_photo(event):
    global image1
    path = Image.open("{}\{}".format(text_folder.get(), list_box_path.get(list_box_path.curselection())))
    image1 = ImageTk.PhotoImage(path)
    lbl.configure(image=image1)
root = tk.Tk()
root.geometry("450x600")
root.title("project image processor")
frame1 = tk.Frame(root, width=250, height=100)
frame4 = tk.Frame(root, width=250, height=100)
lbl_folder = tk.Label(frame1, text="Enter folder path:")
text_folder = tk.Entry(frame1, insertwidth=4)
list_box_path = tk.Listbox(frame1)
b_choose = tk.Button(frame1, text="Choose", command=lambda: open_path(text_folder.get()))
lbl = tk.Label(frame4, text="waiting for photo")
frame1.pack(side="left", fill="both")
frame4.pack(side="right", fill="both")
lbl_folder.grid(row=0, column=0)
text_folder.grid(rowspan=1, column=0)
list_box_path.grid(row=2)
b_choose.grid(row=1, column=1)
lbl.grid(row=0, column=0)
list_box_path.bind('<<ListboxSelect>>', choose_photo)
root.mainloop()

最新更新