简体   繁体   中英

Trying to move the traffic light in a loop when clicking the mouse with Zelle graphics module

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

My code runs but the only problem is I can't get the function to loop, it stops after it jumps to red but it needs jump to green and then yellow and then red in a loop. I have tried using the function win.mianloop() but that also does not work. I wanted to use a while loop but I don't know how to go and do that, any suggestions?

Just put a loop in your function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM