首页 > 解决方案 > 使用 Zelle 图形模块单击鼠标时尝试循环移动交通灯

问题描述

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循环,但我不知道该怎么做,有什么建议吗?

标签: pythongraphicszelle-graphics

解决方案


只需在您的函数中放置一个循环:

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

推荐阅读