问题描述
from graphics import *
def trafficlight():
win = GraphWin()
Box = Rectangle(Point(75,25),Point(125,175))
Box.draw(win)
yellow = Circle(Point(100,100),25)
yellow.setFill('yellow')
red = Circle(Point(100,50),25)
red.setFill('red')
green = Circle(Point(100,150),25)
green.setFill('green')
yellow.draw(win)
red.draw(win)
green.draw(win)
win.getMouse()
red.setFill('grey')
yellow.setFill('grey')
green.setFill('green')
win.getMouse()
red.setFill('grey')
yellow.setFill('yellow')
green.setFill('grey')
win.getMouse()
red.setFill('red')
yellow.setFill('grey')
green.setFill('grey')
win.getMouse()
trafficlight()
我的代码运行,但唯一的问题是我无法让函数循环,它在跳到红色后停止,但它需要在循环中跳到绿色,然后是黄色,然后是红色。我曾尝试使用函数 win.mianloop()
但这也不起作用。我想使用 while 循环,但我不知道如何去做,有什么建议吗?
解决方法
只需在您的函数中放置一个循环:
from graphics import *
def trafficlight():
win = GraphWin()
box = Rectangle(Point(75,25),Point(125,175))
box.draw(win)
yellow = Circle(Point(100,100),25)
yellow.setFill('yellow')
red = Circle(Point(100,50),25)
red.setFill('red')
green = Circle(Point(100,150),25)
green.setFill('green')
yellow.draw(win)
red.draw(win)
green.draw(win)
win.getMouse()
while True: # Loop forever.
red.setFill('grey')
yellow.setFill('grey')
green.setFill('green')
win.getMouse()
red.setFill('grey')
yellow.setFill('yellow')
green.setFill('grey')
win.getMouse()
red.setFill('red')
yellow.setFill('grey')
green.setFill('grey')
win.getMouse()
trafficlight()