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.
Since you included the tag
tkinter
, there is a tkinter-specific solution that works quite well. You can use theafter
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:
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 useafter
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.