How do I add an image to a python script using Tkinter

Asked

Viewed 104 times

0

I’m trying to add an image to a program with the following code:

from tkinter import * 

root = Tk()

imagem = PhotoImage(file="imagem")

lb = Label(root, imagem=imagem)

lb.place(x = 0, y = 20)

root.mainloop()

The image is saved in the same folder as the program code, but it still doesn’t work.

1 answer

0


Gabriel,

On the line you instance to PhotoImage, the image name needs to contain the extension for the program to find it, if your image is a jpg for example, you put the name with . jpg at the end:

imagem = PhotoImage(file="imagem.jpg")

Also, when you inform the image on Label, you passed imagem=imagem, but is incorrect, the correct parameter of the Label is called image, without the M at the end:

lb = Label(root, image=imagem)

Correcting these points, your program would look like this:

from tkinter import * 

root = Tk()

imagem = PhotoImage(file="imagem.jpg")

lb = Label(root, image=imagem)

lb.place(x = 0, y = 20)

root.mainloop()
  • It worked! Thank you very much!

Browser other questions tagged

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