Jun-28-2024, 05:16 PM
The tricky part is periodically calling a function, but I believe there are timers in raspberry pi that you can configure to call a function (Timer.PERIODIC). The timer can call the _update_display function directly. The _periodic_update() function in my example was required because tkinter doesn't have anything as nice as Timer.
You should be able to hook the button directly to the _button_clicked function (button.when_pressed = _button_clicked).
I wrote my code as a class, but it can be functions.
You should be able to hook the button directly to the _button_clicked function (button.when_pressed = _button_clicked).
I wrote my code as a class, but it can be functions.
import tkinter as tk from datetime import datetime, timedelta def update_display(): start = datetime.now() - timedelta(minutes=1) while clicks and start > clicks[0]: clicks.pop(0) tics_per_hour.set(len(clicks)) def button_clicked(): clicks.append(datetime.now()) update_display() def periodic_update(): update_display() root.after(1000, periodic_update) root = tk.Tk() button = tk.Button(root, text="Push Me", command=button_clicked) label = tk.Label(root, text="Button clicks per minute:", anchor="e") tics_per_hour = tk.IntVar(root, 0) display = tk.Label(root, textvariable=tics_per_hour, width=6, anchor="w") label.grid(row=0, column=0, padx=(10, 5), pady=10, sticky="e") display.grid(row=0, column=1, padx=(0, 10), pady=10, sticky="w") button.grid(row=1, column=0, columnspan=2, padx=10, pady=(0, 10), sticky="news") clicks = [] periodic_update() root.mainloop()Nowhere in your code can you have this:
while True:Loops should be rare in raspberry pi code.