【问题标题】:Image not seen in Tkinter (python) [duplicate]在 Tkinter(python)中看不到图像 [重复]
【发布时间】:2020-12-24 04:40:43
【问题描述】:

我开始编程,我必须在其中制作一个python图形界面,通过一个按钮选择jpg文件并显示在界面中,但是我遇到了一个问题,因为图像没有显示并且在终端中它没有检测到任何错误,实际上我在这里发疯了,我留下了代码

from PIL import Image, ImageTk
from tkinter import Tk, Frame, Button, Label, Text, filedialog, PhotoImage

class Application_BotonPath(Frame):
    def __init__(self, master = None):
        super().__init__(master, width = "1300", height = "950", bg = "old lace")
        self.master = master
        self.pack()
        self.Panel()
        self.widget()
        
    def Panel(self):
        self.frame_side = Frame(self, width = '300', height = '850', bg = 'sky blue').place(x = 20, y = 50)
        self.frame_show = Frame(self, width = '900', height = '850').place(x = 360, y = 50)
        
    def widget(self):
        boton = Button(self.frame_side, text = "Abrir Imagen", command = self.cargar_imagen).place(x = 85, y = 60, width = 150, height = 30)
        salida = Text(self.frame_side, state = "disable").place(x = 43, y = 110, width = 250, height = 700)
        
    def cargar_imagen(self):
        self.ruta_imagen = filedialog.askopenfilename(title = "Abrir", filetypes = [('Archivo png', '*.png'), ('Archivo jpeg', '*.jpg')])      
        load = Image.open(self.ruta_imagen)
        imagen = ImageTk.PhotoImage(load)
        label = Label(self.frame_show, image = imagen)
        label.place(x=0, y=0)
        
root = Tk()
root.wm_title("Detector de Caracteres")
app = Application_BotonPath(root)
app.mainloop()

image

这就是我得到的,右上角的灰色框我想是图像,但它没有显示它。请帮忙

【问题讨论】:

    标签: python image user-interface tkinter functional-programming


    【解决方案1】:

    欢迎来到 SO。

    图像是在函数中创建的,当函数结束时,对图像的引用会被垃圾回收。因此 Label 找不到任何图像。

    您可以在标签对象中保存对图像的引用:

    label = Label(self.frame_show, image = imagen)
    label.image = imagen    # Save reference to image
    

    或者您可以将引用作为实例的属性:

    self.imagen = ImageTk.PhotoImage(load)
    label = Label(self.frame_show, image = self.imagen)
    

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多