Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Created October 7, 2018 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PM2Ring/3b11ea2b6750903e92acdd104c63c769 to your computer and use it in GitHub Desktop.
Save PM2Ring/3b11ea2b6750903e92acdd104c63c769 to your computer and use it in GitHub Desktop.
Use Tkinter's .after method to run several named counters in parallel.
#!/usr/bin/env python3
""" Use .after to run several named counters in parallel.
Each counter prints its name and value to the terminal,
once per second.
When the 'New counter' button is clicked, a new
counter is created, using the name in `name_entry`, and
a 'Stop' button with the same name is added to the GUI.
Written by PM 2Ring 2018.10.07
"""
import tkinter as tk
root = tk.Tk()
# The name for the next counter
name_entry = tk.Entry(root)
name_entry.insert(tk.END, 'A')
name_entry.pack()
# A dict to store the counter names & their Stop buttons
counters = {}
def start_counter():
""" Create a new named counter and its Stop button """
name = name_entry.get()
if name in counters:
# This name is already in use
return
# Create a stop button for this counter
button = tk.Button(root, text='Stop ' + name,
command=lambda name=name: stop(name))
button.pack()
counters[name] = button
# Start the counter
counter(name, 0)
def stop(name):
""" Destroy the stop button & remove the name """
counters[name].destroy()
del counters[name]
def counter(name, num):
""" Print the counter name & value, and schedule the next call
if the name is still in the counters dict
"""
if name in counters:
print(name, num)
root.after(1000, lambda: counter(name, num + 1))
tk.Button(root, text='New counter', command=start_counter).pack()
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment