简体   繁体   中英

ImageTk.Photoimage not working as expected

I want to make the user open a file using askopenfile() and assign the image to a variable code:

from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
root = Tk()
root.title("Forms")


def new_window():
    root.filename = filedialog.askopenfilename(title="Select a file", filetypes=[("Png Files", "*.png")])
    print(root.filename)
    img = ImageTk.PhotoImage(open(root.filename))


btn = Button(text="Click here to open file .", command=new_window).pack()
root.mainloop()

But i get an error. The output is:

C:\\Users\\Imtiaz\\PycharmProjects\\pythonProject\\venv\\Scripts\\python.exe C:/Users/Imtiaz/PycharmProjects/pythonProject/mbox.py C:/Users/Imtiaz/Pictures/Roblox/RobloxScreenShot20201102_204504924.png Exception in Tkinter callback

Traceback (most recent call last):
  File "C:\Users\Imtiaz\pyver\py390\lib\tkinter\__init__.py", line 1885, in __call__
    return self.func(*args)
  File "C:\Users\Imtiaz\PycharmProjects\pythonProject\mbox.py", line 11, in new_window
    img = ImageTk.PhotoImage(open(root.filename))
  File "C:\Users\Imtiaz\PycharmProjects\pythonProject\venv\lib\site-packages\PIL\ImageTk.py", line 108, in __init__
    mode = Image.getmodebase(mode)
  File "C:\Users\Imtiaz\PycharmProjects\pythonProject\venv\lib\site-packages\PIL\Image.py", line 300, in getmodebase
    return ImageMode.getmode(mode).basemode
  File "C:\Users\Imtiaz\PycharmProjects\pythonProject\venv\lib\site-packages\PIL\ImageMode.py", line 64, in getmode
    return _modes[mode]
KeyError: <_io.TextIOWrapper name='C:/Users/Imtiaz/Pictures/Roblox/RobloxScreenShot20201102_204504924.png' mode='r' encoding='cp1252'>

Answer: Thanks to acw1668 I got what the problem was. error was in:

img = ImageTk.PhotoImage(open(root.filename))

it is supposed to be: Either ImageTk.PhotoImage(file=root.filename) or ImageTk.PhotoImage(Image.open(root.filename))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM