Python Turtle mainloop()的用法 [英] Python Turtle mainloop() usage
问题描述
我从在线教程中获得以下代码通过使点击鼠标时改变状态的信号灯学习基于事件的编程.这是我的全部代码:
I have the following code from an online tutorial to learn event-based programming by making a stop light that changes state when the mouse is clicked. Here is the entirety of my code:
import turtle
turtle.setup(400,500)
wn = turtle.Screen()
wn.title("Tess becomes a traffic light!")
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
def draw_housing():
tess.pensize(3)
tess.color("black","darkgrey")
tess.begin_fill()
tess.forward(80)
tess.left(90)
tess.forward(200)
tess.circle(40, 180)
tess.forward(200)
tess.left(90)
tess.end_fill()
draw_housing()
tess.penup()
tess.forward(40)
tess.left(90)
tess.forward(40)
tess.shape("circle")
tess.shapesize(3)
tess.fillcolor("green")
state_num = 0
def nextFSMstate():
global state_num
if state_num == 0:
tess.forward(70)
tess.fillcolor("orange")
state_num = 1
elif state_num == 1:
tess.forward(70)
tess.fillcolor("red")
state_num = 2
else:
tess.back(140)
tess.fillcolor("green")
state_num = 0
wn.onkey(nextFSMstate, "space")
wn.listen()
turtle.mainloop()
# example says wn.mainloop() but I get error. This works though
在本教程中,他们使用:
In the tutorial, they use:
wn.mainloop()
但是我得到了错误:
File "stopLights.py", line 51, in <module>
wn.mainloop()
AttributeError: '_Screen' object has no attribute 'mainloop'
并且必须使用
turtle.mainloop()
为什么有区别?我在Ubuntu中使用Python 2.7;该示例在PyScripter中.预先感谢.
Why the difference? I am using Python 2.7 in Ubuntu; the example is in PyScripter. Thanks in advance.
推荐答案
在本教程中似乎是一个错误.
It appears to be an error in the tutorial.
在第4行上,它们定义了wn = turtle.Screen()
,这意味着以后对wn.mainloop()
的调用等同于调用turtle.Screen().mainloop()
.
On line 4, they define wn = turtle.Screen()
, which means that the later call to wn.mainloop()
is equivalent to calling turtle.Screen().mainloop()
.
这没有任何意义;如错误消息所示,没有turtle.Screen()
的.mainloop()
方法.有 ,但是基础turtle
对象的.mainloop()
方法,这就是调用该方法的原因.
This doesn't make any sense; as the error message states there is no .mainloop()
method of turtle.Screen()
. There is, however a .mainloop()
method of the base turtle
object, which is why calling that works.
这篇关于Python Turtle mainloop()的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!