python - 我将图片转换为 GIF 但 turtle 的 bgpic() 仍然无法正常工作

标签 python image tkinter background-image turtle-graphics

这是我的代码:

from tkinter import *
import turtle as t
import random
bob=Tk()
t.setup(width = 200,height = 200)
t.bgpic(picname="snakesandladders.gif")
def left(event):
    t.begin_fill()
    print("left")
    t.left(90)

def right(event):
    print("right")
    t.right(90)
def forward(event):
    print("forward")
    t.forward(100)


block = Frame(bob, width=300, height=250)
bob.bind("<a>", left)
bob.bind("<d>", right)
bob.bind("<w>", forward)
block.pack()
bob.mainloop()

我的错误是:

Traceback (most recent call last):
  File "/Users/lolszva/Documents/test game.py", line 6, in <module>
    t.bgpic(picname="snakesandladders.gif")
  File "<string>", line 8, in bgpic
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 1481, in bgpic
    self._bgpics[picname] = self._image(picname)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 479, in _image
    return TK.PhotoImage(file=filename)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3545, 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 3501, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "snakesandladders.gif": no such file or directory

我是初学者,所以我真的不知道我是否没有导入库。在另一个类似的问题中,bgpic() 不起作用,它说将图片转换为 gif,但对我来说它仍然不起作用。我使用的是 Mac OSX Python 版本 3.8.0。

最佳答案

虽然您的问题是缺少 GIF 文件,但即使该文件存在并且位于正确的目录中,您的程序仍然会失败。

第二个问题是您在 tkinter 上调用独立的 turtle 。您可以独立运行turtle,它设置底层tkinter根和窗口,也可以在tkinter中嵌入运行turtle,您可以在其中设置turtle的根和 Canvas 漫游。但是在您创建的 tkinter 根上调用独立的 turtle 将会失败并出现错误:

...
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage2" doesn't exist

以下是如何在独立 turtle 中实现您的程序:

from turtle import Screen, Turtle

def left():
    turtle.left(90)

def right():
    turtle.right(90)

def forward():
    turtle.forward(100)

screen = Screen()
screen.setup(width=200, height=200)
screen.bgpic(picname="snakesandladders.gif")

screen.onkey(left, "a")
screen.onkey(right, 'd')
screen.onkey(forward, 'w')

turtle = Turtle()

screen.listen()
screen.mainloop()

将 GIF 背景图像放在与源代码相同的目录中。

如果您想在 turtle Canvas 旁边添加 tkinter 小部件,则只需要嵌入 turtle 。请参阅 RawTurtleTurtleScreen 的文档。

forward() 距离相比,您的窗口尺寸较小 - 您可能需要调整其中之一。

关于python - 我将图片转换为 GIF 但 turtle 的 bgpic() 仍然无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460292/

相关文章:

image - 在 QTP 等自动化工具上测试应用程序时如何通过验证码

python - Tkinter 标签不更新

python - 从 Django 中的列表创建标签云?

Python,SQLAlchemy,如何只用一个提交指令以有效的方式插入查询

python - 无法在 Ubuntu 18.04 上创建 python 虚拟环境

python - 不使用 if 但使用 else 的列表推导式

javascript - HTML Canvas Img 缩放以某种方式不起作用

android - 如何将图像存储在 mySQL 数据库中?

python - 使用 OpenCV 读取图像并使用 Tkinter 显示它

python - 在文本框中的文本周围制作矩形边框 python tkinter