Count Button Press - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Count Button Press (/thread-42389.html) |
Count Button Press - chizzy101010 - Jun-28-2024 Hi , hope all is good. I'm trying to put together a project to learn python and raspberry pi and have looked at counting how many times a button is pressed in an hour. Just now i'm just trying to out put to the screen , next to excel, then try to send via a pi to a network location. The code i've got now i though worked , but now realise that there's a bug and cant seem to reset the minute properly.The program counts the number of button presses in an hour. What i've noticed is that the last button for example if i press the button say 6 times in minute 23, then dont register another button press for say 3 mins, then the next button press is registered as minute 23 instead of minute 26. Could someone have a look please and see where the reset should be to close the count of that minute and be ready to count whenever another press occurs. Any help would be greatly appreciated for what is hopefully my new hobby. thanks import time # Initialize a dictionary to store button counts button_counts = {} # Initialize the current hour current_hour = None while True: # Get the current time now = time.localtime() hour = now.tm_hour mins = now.tm_min #added for mins print(mins) #added for mins # Check if a new min has started # if min != current_hour: added if mins != current_hour: # Print the counts for the previous hour if current_hour is not None: print(f"min {current_hour}:") #added to view minute for button, count in button_counts.items(): print(f"Button {button}: {count} presses") print("\n") # Reset counts for the new min button_counts = {} current_hour = mins # Simulate button press () button = input("Enter button number (1-5): ") if button.isdigit(): button = int(button) button_counts.setdefault(button, 0) button_counts[button] += 1 else: print("Invalid input. Please enter a number between 1 and 5.") RE: Count Button Press - deanhystad - Jun-28-2024 You need to keep a list of times when the button was pressed. Each time you compute the clicks per hour you remove any clicks that are more than an hour old. This is an example using tkinter to have a button to press. I changed to clicks per minute so I wouldn't have to wait an hour to see the old clicks being removed. import tkinter as tk from datetime import datetime, timedelta class CounterWindow(tk.Tk): def __init__(self): super().__init__() button = tk.Button(self, text="Push Me", command=self._button_clicked) label = tk.Label(self, text="Button clicks per minute:", anchor="e") self.tics_per_hour = tk.IntVar(self, 0) display = tk.Label(self, textvariable=self.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") self._clicks = [] self._periodic_update() def _button_clicked(self): self._clicks.append(datetime.now()) self._update_display() def _update_display(self): start = datetime.now() - timedelta(minutes=1) while self._clicks and start > self._clicks[0]: self._clicks.pop(0) self.tics_per_hour.set(len(self._clicks)) def _periodic_update(self): self._update_display() self.after(1000, self._periodic_update) CounterWindow().mainloop() RE: Count Button Press - chizzy101010 - Jun-28-2024 Thanks for the reply deanhystad it was more than i was expecting, i'll try and incorporate what you have with my code to try and understand it better. thanks again RE: Count Button Press - deanhystad - Jun-28-2024 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. |