0

I am starting to program, in which I have to make a python graphical interface, in which by means of a button the jpg file is chosen and it is displayed in the interface, but I have had a problem, since the image is not displayed and in the terminal it does not detect any error and practically I go crazy here I leave the code

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

This is what I get, the gray box that is in the upper right I suppose it is the image, but it does not show it. please help

1 Answers1

1

Welcome to SO.

The image is created in a function, and when the function ends the reference to the image is garbage collected. Therefore the Label can not find any image.

You can save a reference to the image in the label object:

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

or you can make the reference an attribute of the instance:

self.imagen = ImageTk.PhotoImage(load)
label = Label(self.frame_show, image = self.imagen)
figbeam
  • 7,001
  • 2
  • 12
  • 18