python - 如何在 Python 3.x 上将图像添加到 Tkinter GUI
问题描述
背景信息,以便您了解我问这个问题的原因:
我使用的 Python 版本是 3.7
我是一名学生
在我的课堂上,我们 2 个月前开始学习 Python
这门课的开始是我第一次接触Python
您可能会认为我对这种语言的了解几乎为零。
反正,
我尝试在一个使用 Tkinter GUI 的项目中将多个图像编码到一个帧中。但是,错误消息:
'_tkinter.TclError:无法打开“snake1.jpg”:没有这样的文件或目录'
每当我尝试运行程序时都会出现,尽管我已经确保我计划使用的所有图像都放在与我的项目相同的目录中,并且还确保在我尝试调用文件时没有拼写错误和错误.
我认为我输入的内容有问题,但根据我使用的参考资料,它似乎没有错误。
在该目录中,文件位于以下文件夹中:
C:\Users\[我的账户名]\PycharmProjects\Practice Coding\GUI Practice
GUI练习包含:Practice_GUI_Game.py、snake1.jpg、snake2.jpg、snake3.jpg、snake4.jpg。
请查看代码并告诉我我做错了什么。所有答案都将被记录和赞赏。谢谢你。
from tkinter import *
game = Tk()
game.wm_title("Snake Collection")
game.config(bg="#EB5E55")
left1 = Frame(game, width=500, height=1000)
left1.grid(row=0, column=0, padx=15, pady=15)
def bonuslvl():
bonusimg1 = PhotoImage(file='snake1.jpg')
Label(left1, image=bonusimg1).grid(row=0, column=0, padx=5, pady=5)
bonusimg2 = PhotoImage(file='snake2.jpg')
Label(left1, image=bonusimg2).grid(row=0, column=1, padx=5, pady=5)
bonusimg3 = PhotoImage(file='snake3.jpg')
Label(left1, image=bonusimg3).grid(row=1, column=0, padx=5, pady=5)
bonusimg4 = PhotoImage(file='snake4.jpg')
Label(left1, image=bonusimg4).grid(row=1, column=1, padx=5, pady=5)
bonuslvl()
game.mainloop()
将每个 jpeg 图像的名称更改为其他名称,然后将它们恢复为原始名称后,我遇到了一个新错误:
File "C:\Users\[my account name]\PycharmProjects\Practice Coding\GUI Practice\Practice_GUI_Game.py", line 10, in bonuslvl
bonusimg1 = PhotoImage(file='snake1.jpg')
File "C:\Users\[my account name]\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3542, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\[my account name]\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3498, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "snake1.jpg"
Process finished with exit code 1
解决方案
所以,tkinter 似乎不再支持.jpg
了。
我使用 PIL 解决了您的问题。
要安装 PIL 运行pip install Pillow
.
我设法使它在我的本地机器上工作:
from tkinter import *
from PIL import ImageTk, Image
game = Tk()
game.wm_title("Snake Collection")
game.config(bg="#EB5E55")
left1 = Frame(game, width=500, height=1000)
left1.grid(row=0, column=0, padx=15, pady=15)
def bonuslvl():
bonusimg1 = ImageTk.PhotoImage(file='snake1.jpg')
Label(left1, image=bonusimg1).grid(row=0, column=0, padx=5, pady=5)
bonuslvl()
game.mainloop()
推荐阅读
- python - 使用“-1”作为索引号时,元素插入到最后第二个位置。它是怎么发生的?
- python - python从
- java - 为什么我的广播接收器没有响应任何电话状态?
- mysql - 错误:错误:在 DENO 中读取数据包超时
- ios - 在 SwiftUI 中从数据模型中搜索数组
- mule - 使用 Mule 4 Object Store V2 超过 10 TPS 后,我需要等待多长时间?
- azure - HDInsight azure adls gen2 'InternalServerError' ARM 模板部署
- r - 用符号制作的多行词
- excel - 循环粘贴,然后在 VBA 中分组
- javascript - 如何将我的下拉选择值保存在数据库中......使用 javascript?