Timer in a traffic light simulation

1.8k views Asked by At

I'm currently working on a Python 3.x project and I'm supposed to make a simple crossroad simulation with traffic lights etc. My only problem right now is that I am not aware of any way to measure time so as to use it to change the traffic lights accordingly. Is there any way to create a virtual timer which will begin as soon as the simulation starts and goes on infinitely until the window is closed? I'm considering using the time or timeit modules, but I'm a bit lost here.

Thanks in advance.

1

There are 1 answers

1
Bryan Oakley On BEST ANSWER

Since you included the tag tkinter, there is a tkinter-specific solution that works quite well. You can use the after method available on every widget to schedule an event to happen in the future.

In the simplest case, you can have a function that will run some other function on a given interval. For example:

import tkinter as tk

def run_periodically(func, ms):
    func()
    root.after(ms, run_periodically, func, ms)

def tick():
    global count
    count += 1
    tick_label.configure(text="count: %d" % count)


count = 0
root = tk.Tk()
tick_label = tk.Label(root, text="")
tick_label.pack(padx=20, pady=20)

run_periodically(tick, 1000)

root.mainloop()

Of course, instead of having something called on a schedule, you can also just schedule the jobs as needed. For example, when the light turns red you can use after to both turn it off and turn the green on. You can then use after to turn the green off and the yellow on, and so on. Since this sounds like a homework assignment I won't provide an example.