[英]PhotoImage no such file or directory error
所以基本上,我正在尝试学习 tkinter,但 PhotoImage 小工具不起作用。
我的代码:
import tkinter as tk
root = tk.Tk()
logo = tk.PhotoImage(file ="monky.gif")
def test():
print("Hello World")
text = tk.Label(root, text = "Hello World")
text.pack()
我也试过这个:
logo = tk.PhotoImage(file ="/Users/MinecraftMaster/Desktop/Python/Tests/monky.gif")
错误信息:
Traceback (most recent call last):
File "/Users/MinecraftMaster/Desktop/Python/Tests/Tkinter Test.py", line 4, in <module>
logo = tk.PhotoImage(file ="monky.gif")
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 3539, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 3495, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "monky.gif": no such file or directory
这是我的目录的图片:
编辑:一位朋友帮我解决了这个问题。 对于遇到此问题的任何其他人,只需将目录放入变量中,然后调用它。 感谢所有试图提供帮助的人
您需要确保monky.gif
文件与您的 python 脚本文件位于同一目录中,例如monky.py
。
要显示图像,您需要tk.Label
方法中的image=logo
和tk.Label
compound='top'
选项告诉tk.Label
将图像和文本一起显示,使图像位于顶部。
希望以上有帮助。
更新:如何检查monky.gif
文件与您的 python 脚本文件在同一目录中。
打开一个终端,例如按Ctr
+ Alt
+ T
。 如果你的图像和python文件在你的Home_folder/Desktop/test_folders中,那么在终端中输入cd
命令进入你的文件夹(即目录)。 然后使用ls
命令列出该文件夹中的文件。 这些命令是为了帮助您查看您的 python 文件(例如monky.py
)和monky.gif
文件是否在同一目录中。 如果这些文件不在同一个文件夹中,则不会出现图像。
$ cd Desktop/test_folder/
$ ls
monky.gif monky.py
您还没有放置一个包含照片的小部件,就像标签一样,然后它应该会出现。
import tkinter as tk
root = tk.Tk()
photo = tk.PhotoImage(file = "monkey.gif")
label = tk.Label(image = photo).pack()
def test():
print("Hello World")
text = tk.Label(root, text = "Hello World")
text.pack()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.