简体   繁体   English

_tkinter.TclError: 无法打开 [暂停]

[英]_tkinter.TclError: couldn't open [on hold]

I've been trying to figure out how to create an image on tkinter for a while now below is my code:我一直试图弄清楚如何在 tkinter 上创建图像一段时间,现在下面是我的代码:

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

canvas = Canvas(root, width = 500, height = 500)
canvas.pack
my_image = PhotoImage(file='C:\\Users\\david\\Desktop\\e.png')
canvas.create_image(0,0, anchor = NW, image=my_image)
root.mainloop()

and as a result, I receive this error:结果,我收到此错误:

Traceback (most recent call last):
  File "/Users/david/Desktop/tinker.py", line 8, in <module>
    my_image = PhotoImage(file='C:\\Users\\david\\Desktop\\e.png')
  File     "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line     3542, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line     3498, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "C:\Users\david\Desktop\e.png": no such file or     directory

I have made sure that \Users\david\Desktop\e.png is in my desktop along with the tkinker script.我已确保 \Users\david\Desktop\e.png 与 tkinker 脚本一起在我的桌面中。
I have also tried putting them in the same folder but still I get the same error message.我也尝试将它们放在同一个文件夹中,但仍然收到相同的错误消息。

Thanks for any help!谢谢你的帮助!

Sorry literally, 4 seconds ago I used,对不起,4秒前我用过,

import tkinter as tk
from PIL import ImageTk,Image
root  =tk.Tk()
root.title("e.png")
photo = ImageTk.PhotoImage(Image.open('e.png'))
label = tk.Label(root, image=photo)
label.pack()

And it finally worked... Im sorry this is dumb I answered my own question I apologise.. I just accidentally coded this and woosh it worked..它终于奏效了...对不起,这很愚蠢

The problem is that the tkinter.PhotoImage doesn't support opening .png images, only .gif .问题是tkinter.PhotoImage不支持打开.png图像,只支持.gif Your solution is one of the best.您的解决方案是最好的解决方案之一。 PIL can use a .png file as a PhotoImage . PIL 可以使用.png文件作为PhotoImage Use photo = ImageTk.PhotoImage(Image.open('e.png')) , as you did.像你一样使用photo = ImageTk.PhotoImage(Image.open('e.png'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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