1

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.

Jonnyolsen1
  • 31
  • 1
  • 5
  • [Yes](https://docs.python.org/3.6/library/time.html). You can first get the initial time with `time.time()` or `time.clock()` and use that to calculate the current simulation time by calling either of the two before the window closes – pbreach Dec 16 '16 at 14:54
  • 1
    @pbreach Why not add this as an anser? It's far too good to be just a comment. – MeanGreen Dec 16 '16 at 15:01
  • Because this is a [duplicate](http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python), of a [duplicate](http://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python), of a [duplicate](http://stackoverflow.com/questions/3620943/measuring-elapsed-time-with-the-time-module)... You get the idea. – pbreach Dec 16 '16 at 16:09
  • Thanks for the input guys! I tried using both of them but the other answer below suits me better. – Jonnyolsen1 Dec 16 '16 at 17:08

1 Answers1

1

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685