尝试使用 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 循环,但我不知道如何去做,有什么建议吗?

解决方法

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...