我在python中有一个交通信号灯模拟器,它正常运行但是在第一次运行后它刚刚结束,我需要它在一个循环上,例如红 - 黄 - 绿,然后再红 - 黄 - 绿和那么......我在这里失踪了什么?我是python的新手,如果这是一个noob问题,请不要报告 以下是我的代码:
import time
from time import sleep
from tkinter import *
tk=Tk()
win=Canvas(tk, width=55, height=200)
win.pack()
#functions
def red(a):
for i in range(a):
red=win.create_oval(5,5,50,50, fill="red")
tk.update()
time.sleep(0.05)
def redb(a):
for i in range(a):
red=win.create_oval(5,5,50,50, fill="black")
tk.update()
time.sleep(0.05)
def amber(a):
for i in range(a):
amber=win.create_oval(5,55,50,100, fill="orange")
tk.update()
time.sleep(0.05)
def amberb(a):
for i in range(a):
amber=win.create_oval(5,55,50,100, fill="black")
tk.update()
time.sleep(0.05)
def green(a):
for i in range(a):
green=win.create_oval(5,105,50,150, fill="green")
tk.update()
time.sleep(0.05)
def greenb(a):
for i in range(a):
green=win.create_oval(5,105,50,150, fill="black")
tk.update()
time.sleep(0.05)
def lights():
red=win.create_oval(5,5,50,50, fill="black")
amber=win.create_oval(5,55,50,100, fill ="black")
green=win.create_oval(5,105,50,150, fill="black")
#end of functions
#calling the functions
lights()
red(30)
redb(1)
amber(10)
amberb(1)
green(30)
greenb(1)
tk.mainloop()
答案 0 :(得分:0)
你需要在光变化代码上循环:
lights()
while True: # use a better termination condition here
red(30)
redb(1)
amber(10)
amberb(1)
green(30)
greenb(1)
请注意:
for i in range(a):
amber=win.create_oval(5,55,50,100, fill="black")
tk.update()
time.sleep(0.05)
它与:
相同amber=win.create_oval(5,55,50,100, fill="black")
tk.update()
time.sleep(0.05 * a)
因为for循环只是重新绘制椭圆并睡眠0.05秒a
次。