首页 > 解决方案 > 如何在 Python 3.x 上将图像添加到 Tkinter GUI

问题描述

背景信息,以便您了解我问这个问题的原因:

反正,

我尝试在一个使用 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

标签: pythonpython-3.xtkinter

解决方案


所以,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()

推荐阅读