How to show an image on Tkinter?

Asked

Viewed 1,552 times

0

I want to add an image to the widget, but nothing appears, I tried to follow the same face https://stackoverflow.com/questions/28139637/how-can-i-display-an-image-using-pillow , but it doesn’t work.

His code:

from PIL import Image, ImageTk 
import tkinter as tk 

root = tk.Tk()
tkimage = ImageTk.PhotoImage(Image.open("bola.jpg"))
tk.Label(root, image=tkimage).pack()
root.mainloop()

image in his code works:

inserir a descrição da imagem aqui

My code:

from tkinter import *
from PIL import Image, ImageTk

class TesteImage1:
   def __init__(self, master=None):
      self.widget1 = Frame(master)
      self.widget1.pack()

      self.imagem = Label(self.widget1)
      # imagem = ImageTk.PhotoImage(Image.open("bola.jpg"))
      self.imagem['image'] = ImageTk.PhotoImage(Image.open("bola.jpg"))
      # self.imagem['text'] = "Testando"
      self.imagem.pack()

      self.teste = Label(self.widget1, text="testando")
      self.teste.pack()

root = Tk()
TesteImage1(root)
root.mainloop()

inserir a descrição da imagem aqui

  • Elton’s changes work better, because I will make the image dynamic, that is, a function will change the image. def changeImage(self): width = 500 height = 500 sample = Image.open("ball.jpg") self.sample = Imagetk.Photoimage(sample width, height), Image.ANTIALIAS)) self.image['image'] = self.sample

2 answers

1


see two mistakes

The first one here

self.imagem['image'] = ImageTk.PhotoImage(Image.open("bola.jpg"))

what happens is that Imagetk.Photoimage is being picked up by the garbage collector, the solution is to pass the reference with variable

self.amostra = ImageTk.PhotoImage(Image.open("bola.jpg"))
self.imagem['image'] = self.amostra

The second mistake is the same

the collector is picking up the class call

TesteImage1(root)

put the output in a variable and it will work

teste = TesteImage1(root)

0

First of all check if the image you want to put is in the same code folder of your window. I solved your problem with script below:

from tkinter import *
from PIL import Image, ImageTk

class TesteImage1:

    def __init__(self, master=None):

        self.widget1 = Frame(master)
        self.widget1.pack()

        # imagem = ImageTk.PhotoImage(Image.open("bola.jpg"))
        image = Image.open("bola.jpg")
        photo = ImageTk.PhotoImage(image)
        self.imagem = Label(master, text = "adicionando", image = photo)
        self.imagem.image = photo
        self.imagem.pack()

        self.teste = Label(self.widget1, text="testando")
        self.teste.pack()


root = Tk()
TesteImage1(root)
root.mainloop()

I hope I’ve helped!!

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.