代码之家  ›  专栏  ›  技术社区  ›  GaryC

Tkinter与图像

  •  1
  • GaryC  · 技术社区  · 1 年前

    使用以下代码,我无法在tkinter单元格中显示图像:

    from tkinter import *
    from tkinter import filedialog
    from PIL import Image, ImageTk
    
    root = Tk()
    root.geometry=("1000x1000")
    
    def orig():
        orig_image = filedialog.askopenfilename(filetypes=[("Image file", "*.jpg"), ("All files", "*.")])
        my_img = ImageTk.PhotoImage(Image.open(orig_image))
        lbl = Label(image=my_img)
        lbl.grid(row=0, column=0)
    
    
    orig()
    
    root.mainloop()
    

    但是,通过将其从方法中删除,它可以很好地工作:

    from tkinter import *
    from tkinter import filedialog
    from PIL import Image, ImageTk
    
    root = Tk()
    root.geometry=("1000x1000")
    
    orig_image = filedialog.askopenfilename(filetypes=[("Image file", "*.jpg"), ("All files", "*.")])
    my_img = ImageTk.PhotoImage(Image.open(orig_image))
    lbl = Label(image=my_img)
    lbl.grid(row=0, column=0)
    
    root.mainloop()
    

    我错过了什么?

    这是一个更大项目的一部分,我想显示一个“原始”OCR扫描图像,然后用其他方法在原始图像旁边(在另一列中)显示一个”校正图像“,以显示该校正是否是一种改进。

    2 回复  |  直到 1 年前
        1
  •  1
  •   toyota Supra    1 年前

    你的代码有一些问题

    *不幸的是,几何方法分配不正确。它应该被调用而不是分配。

    *对于第一个代码块,你定义了一个函数orig(),但让它保持未求值状态。

    *PhotoImage对象需要作为属性保留,以防止它丢失到垃圾回收中。

    试试这个方法:

    from tkinter import *
    from tkinter import filedialog
    from PIL import Image, ImageTk
    
    root = Tk()
    root.geometry("1000x1000")  # Corrected: called as a method
    
    def orig():
        global my_img  # Important: keep a reference to prevent garbage collection
        orig_image = filedialog.askopenfilename(filetypes=[("Image file", "*.jpg"), ("All files", "*.*")])
        img = Image.open(orig_image)
        my_img = ImageTk.PhotoImage(img)
        lbl = Label(root, image=my_img)
        lbl.grid(row=0, column=0)
    
    orig()  # Call the function to open file dialog and display image
    root.mainloop()
    
        2
  •  0
  •   toyota Supra    1 年前

    我无法在tkinter单元中显示图像。

    你需要参考图像。

    将其添加到第12行, lbl.image= my_img

    编辑:

    截图:

    enter image description here

    推荐文章