Skip to content

Instantly share code, notes, and snippets.

@zed

zed/progress.py Secret

Created February 27, 2015 20:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/5440b9372a15d86b5c47 to your computer and use it in GitHub Desktop.
Save zed/5440b9372a15d86b5c47 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""Demonstrate how to use `root.after()` to implement a timer."""
import time
from tkinter import Label, StringVar, Tk, font
ncycles = 1000
ndigits = len(str(ncycles)) - 1
timeout = 10 # milliseconds
root = Tk()
font.nametofont('TkDefaultFont').configure(size=100) # big
text = StringVar()
text.set('0'*ndigits)
Label(root, textvariable=text).pack()
# center the window
root.update_idletasks() # necessary to update w, h
w, h = root.winfo_width(), root.winfo_height()
x = root.winfo_screenwidth() // 2 - w // 2
y = root.winfo_screenheight() // 2 - h // 2
root.geometry('{}x{}+{}+{}'.format(w, h, x, y))
def timer():
return round(time.perf_counter() * 1000)
def update_timer(i=0):
if i >= ncycles:
root.destroy() # exit
else:
root.after(timeout - timer() % timeout, update_timer, i+1)
text.set('{:0{width}d}'.format(i, width=ndigits))
root.after(timeout - timer() % timeout, update_timer) # start timer
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment