Python tkinter image file

Asked 2 years ago, Updated 2 years ago, 116 views

from tkinter import *

window = Tk()
window.title ("Choose what you need right now")

def myFunc():
    if var.get() == 1:
        labelImage.configure(image=photo1)
    elif var.get() == 2:
        labelImage.configure(image=photo2)
    else:
        labelImage.configure(image=photo3)

labelText=Label (window, text="Vote for required items",
                  fg="red", font=("Gungseo font", 20))

var = IntVar()
rb1 = Radiobuton (window, text="tissue", variable=var,
                  value=1)
rb2 = Radiobutton (window, text="clock", variable=var,
                  value=2)
rb3 = Radiobutton (window, text="nutrients", variable=var,
                  value=3)
buttonOk = Button(window, text="View pictures",
                  command=myFunc)

photo1 = PhotoImage(file="image/tissue.png")
photo2 = PhotoImage(file="image/clock.png")
photo3 = PhotoImage(file="image/tonic.png")

labelImage = Label(window, width=200, height=200, bg="orange",
                   image=None)

labelText.pack(padx=5, pady=5)
rb1.pack(padx=5, pady=5)
rb2.pack(padx=5, pady=5)
rb3.pack(padx=5, pady=5)
buttonOk.pack(padx=5, pady=5)
labelImage.pack(padx=5, pady=5)

window.mainloop()

<Error Message> _tkinter.TclError: couldn't recognize data in image file "image/tissue.png"

Python version 3.9, the program uses an idle. I typed everything according to the file path, and even if I change the extension to jpg, jpeg, gif, etc., photo1 = PhotoImage(file="image/tissue.png") The same error occurs from this part.

python tkinter image data

2022-09-20 10:22

1 Answers

I tested the code you uploaded with an arbitrary png file, and the same error did not occur. There was no problem reading the png file.

The code itself does not appear to be abnormal.

(1) There is something wrong with the image file, or (2) the tkinter version of the Python you are using fails to process a specific type of png file. I think that's the question. If it was a path problem, there would have been an error saying that the file could not be found.

If you search, you'll see examples of reading image files using the pillow library, not the photoImage of tkinter. I'm sure you'll try to fix the code to use the pillow.

The png file you are using may be strange, so please test whether other png files can be read.


2022-09-20 10:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.