Home > Blockchain >  Making a counter increment with passing of system time
Making a counter increment with passing of system time

Time:11-22

Below is my attempt of having the counter variable increment as each second passes by. It's not working like I thought it would. I think the problem is in the while loop of trying to compare old time to new time to measure if a second has passed.

import time as time
import tkinter as tk

root = tk.Tk()
root.geometry('200x200')

months = {'1': 'Month of Flowers',
          '2': 'Month of Moon',
          '3': 'Month of Dragon'}

hours = {'1': '1st hour',
         '2': '2nd hour',
         '3': '3rd hour'}

system_time = tk.Label(root, text=f'{time.time()}')
system_counter = tk.Label(root, text='0')
game_time_month = tk.Label(root, text='Month')
game_time_hour = tk.Label(root, text='Hour')

system_time.pack()
system_counter.pack()
game_time_month.pack()
game_time_hour.pack()

def update_all_time():
    system_time['text'] = f'{time.time()}'
    game_time_month['text'] = 'Month'
    game_time_hour['text'] = 'Hour'
    root.update()

system_timer_old = time.time()
counter = 0
while True:
    system_timer_new = time.time()
    if system_timer_new == system_timer_old   1:
        counter = counter   1
        system_counter['text'] = 1
    update_all_time()

root.mainloop()

CodePudding user response:

A counter of how many seconds have passed is, essentially, a clock. Don't try to implement your own clock; just use one from the standard library.

The correct value of the counter is simply the number of seconds that have elapsed since the counting started, rounded down to an integer. So, the function below returns the current value of what the counter should be; you can call it from anywhere that you want to get the value of the counter.

import time

start_time = time.monotonic()

def get_counter():
    current_time = time.monotonic()
    return int(current_time - start_time)

CodePudding user response:

It only increases if system_timer_new is exactly 1 more than the old system_timer. Consider using a window or a limit? I.e. it will never trigger if your time difference is not exactly 1. Consider using a window or a limit to trigger the increase of your counter. You could also use datetime function of timedelta as well.

if system_time_new >= system_time_old:
    delta = system_time_new - system_time_old

CodePudding user response:

Tkinter has a method specifically for scheduling functions to be called in the future. If you want to update a counter every second, it looks something like this:

def update_counter():
    global counter
    counter  = 1
    system_counter['text'] = counter
    system_counter.after(1000, update_counter)

With that, the function will update the counter, update the label with the new value, and then schedule itself to run again in 1 second (1000 milliseconds). You only need to run this function once, and it will continue to execute once a second.

  • Related