Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Tkinter: Using after() to display time [GB]

Using

root.after(milliseconds, callback)

you can run function with delay.

You can use it to display current time

import tkinter as tk
import time

# --- function ---

def update_timer():
    timer['text'] = time.strftime('%H:%M:%S')
    root.after(1000, update_timer) # run again after 1000ms = 1s

# --- main ---

root = tk.Tk()

timer = tk.Label(root, width=10)
timer.pack()

update_timer() # run first time

root.mainloop()

You can also use it for countdown time

import tkinter as tk
import time

# --- function ---

def update_timer():
    global timer_time

    #timer['text'] = time.strftime('%H:%M:%S')
    timer['text'] = str(timer_time)
    timer_time -= 1

    if timer_time >= 0:
        root.after(500, update_timer) # 1000ms = 1s
    else:
        timer['text'] = 'Boom!'

# --- main ---

timer_time = 10

root = tk.Tk()

timer = tk.Label(root, width=10)
timer.pack()

update_timer()

root.mainloop()

callback means function's name without () and without arguments. To run with arguments you can use

root.after(milliseconds, callback, arg1, arg2, ...)
import tkinter as tk
import time

# --- function ---

def update_timer(widget, number):
    widget['text'] = str(number)
    number -= 1

    if number >= 0:
        root.after(1000, update_timer, widget, number) # 1000ms = 1s
    else:
        widget['text'] = 'Boom!'

# --- main ---

root = tk.Tk()

timer1 = tk.Label(root, width=10)
timer1.pack()

timer2 = tk.Label(root, width=10)
timer2.pack()

update_timer(timer1, 5)
update_timer(timer2, 10)

root.mainloop()
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury