Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Count Button Press
#4
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.
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.
chizzy101010 likes this post
Reply


Messages In This Thread
Count Button Press - by chizzy101010 - Jun-28-2024, 03:19 PM
RE: Count Button Press - by deanhystad - Jun-28-2024, 04:05 PM
RE: Count Button Press - by chizzy101010 - Jun-28-2024, 04:50 PM
RE: Count Button Press - by deanhystad - Jun-28-2024, 05:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Row Count and coloumn count Yegor123 4 1,519 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  How to break out of a for loop on button press? philipbergwerf 6 2,035 Oct-06-2022, 03:12 PM
Last Post: philipbergwerf
  tkinter auto press button kucingkembar 2 3,460 Dec-24-2021, 01:23 PM
Last Post: kucingkembar
  Count to movement according to the time pressed button noartist 1 2,625 Feb-27-2019, 01:33 PM
Last Post: noartist
  Conditional Button Press Raudert 8 21,998 Mar-17-2017, 07:32 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020