使用乌龟绘图时,如何解决设置背景后发生的错误?
我从“从头开始学习编码”一书开始学习编程。我必须创建一个模块以使用Python的龟图形进行龟竞赛。我一步一步地进行了操作,但是当我尝试运行代码时,在代码末尾出现了“语法错误”,并且在“ setup()”行出现了。
我将答案与作者的回答进行了比较,每个字符都相同。然后,我复制并尝试运行作者的代码。当我尝试运行代码时,仅出现空白页。在代码中,我必须设置一个与模块位于同一目录中的背景。
import turtle
import random
turtles = list()
def setup():
global turtles
startline = -620
screen = turtle.Screen()
screen.setup(1290,720)
screen.bgpic('pavement.gif')
turtle_ycor = [-40, -20, 0, 20, 40]
turtle_color = ['blue', 'red', 'purple', 'brown', 'green']
for i in range(0, len(turtle_ycor)):
new_turtle = turtle.Turtle()
new_turtle.shape('turtle')
new_turtle.penup()
new_turtle.setpos(startline, turtle_ycor[i])
new_turtle.color(turtle_color[i])
new_turtle.pendown()
turtles.append(new_turtle)
def race():
global turtles
winner = False
finishline = 590
while not winner:
for current_turtle in turtles:
move = random.randint(0,2)
current_turtle.forward(move)
xcor = current_turtle.xcor()
if (xcor >= finishline):
winner = True
winner_color = current_turtle.color()
print('The winner is', winner_color[0])
setup()
race()
turtle.mainloop()
我删除了screen.bgpic('pavement.gif')
行,并且作者的模块运行良好,但是我的模块具有相同的“语法错误”。 (每个字符都相同,后来我尝试复制粘贴代码的每个部分,并且错误也相同)。
我该如何设置背景图片?
错误消息:
Traceback (most recent call last):
File "/home/viccha/.cache/.fr-mVA9RC/headfirstlearntocode-master/ch7/race_step3.py", line 41, in <module>
setup()
File "/home/viccha/.cache/.fr-mVA9RC/headfirstlearntocode-master/ch7/race_step3.py", line 11, in setup
screen.bgpic('pavement.gif')
File "/usr/lib/python3.6/turtle.py", line 1481, in bgpic
self._bgpics[picname] = self._image(picname)
File "/usr/lib/python3.6/turtle.py", line 479, in _image
return TK.PhotoImage(file=filename)
File "/usr/lib/python3.6/tkinter/__init__.py", line 3545, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python3.6/tkinter/__init__.py", line 3501, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "pavement.gif": no such file or directory
答案 0 :(得分:0)
对我来说很好(除了race()部分,因为我没有此功能
您忘记导入turtle模块
import turtle
def setup():
global turtles
startline = -620
screen = turtle.Screen()
screen.setup(1290,720)
screen.bgpic('pavement.gif')
#the end of the code:
setup()
race()
turtle.mainloop()
答案 1 :(得分:0)
显示的错误消息是由以下行引起的:
screen.bgpic('pavement.gif')
您注意到,可以通过注释掉该行来避免错误:
# screen.bgpic('pavement.gif')
那么您的海龟应该就可以了。如果/如果有pavement.gif
文件可用作窗口的背景图像,则可以添加该行。与这本书相关的网站可能会提供它。但是对于这样简单的程序,任何合适大小的GIF图片都应该可以正常工作-在Google图片上查看。