python mainloop_Python Turtle mainloop()的用法

1586010002-jmsa.png

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()

But I get the error:

File "stopLights.py", line 51, in

wn.mainloop()

AttributeError: '_Screen' object has no attribute 'mainloop'

and have to use

turtle.mainloop()

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.

On line 4, they define wn = turtle.Screen(), which means that the later call to wn.mainloop() is equivalent to calling turtle.Screen().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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值