下面是我的代码:
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版本3.8.0。
发布于 2019-10-21 07:36:35
尽管您的问题是缺少GIF文件,但即使该文件存在并且位于正确的目录中,您的程序仍将失败。
第二个问题是在tkinter上调用turtle standalone。您可以在设置底层tkinter根和窗口的位置独立运行turtle,也可以运行嵌入在tkinter中的turtle,您可以在其中设置根和画布让turtle漫游。但是在您创建的tkinter root上调用turtle standalone将失败,并出现错误:
...
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画布旁边添加tkinter小部件,则只需使用嵌入的turtle。请参阅RawTurtle和TurtleScreen的文档。
与forward()距离相比,您的窗口大小较小--您可能需要调整其中之一。
https://stackoverflow.com/questions/58460292
复制相似问题