-2

I am trying to make a little piece of software to display how many times a button is pressed. I made the gui work, the button input works, but I can't figure out how to make the counter update each time I press the button, root.update() didn't work. Code:

import RPi.GPIO as GPIO
import time
import os
import Tkinter as tk
from Tkinter import *

root = tk.Tk()

root.overrideredirect(True)
root.overrideredirect(False)
root.attributes('-fullscreen',True)
root.configure(background='black')
root.configure(cursor="none")

buttonPin = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
Counter = 69

w = Label(root, text=Counter, fg="white", bg="black", font=("Helvetica",80))
w.pack()
w.place(relx=0.5, rely=0.5, anchor=CENTER)

last_state = True
input_state = True

root.mainloop()

while True:
  input_state = GPIO.input(buttonPin)

  if (not input_state):
      Counter += 1
      print(Counter)
      time.sleep(0.3)
Simon V.
  • 3
  • 2
  • Also see [this](https://stackoverflow.com/q/459083/7032856) and [this](https://stackoverflow.com/q/24849265/7032856). – Nae Dec 12 '17 at 13:20
  • By _button_ do you mean an actual mechanical button with Raspberry? – Nae Dec 12 '17 at 13:22
  • Note that `time.sleep` sleeps the GUI as well. – Nae Dec 12 '17 at 13:23
  • 2
    Your while loop is after `root.mainloop()` so it will be executed only after `root` is closed. So you should replace this while loop by calls to `after` like in the questions linked by Nae. – j_4321 Dec 12 '17 at 13:24
  • If your question is about Raspberry perhaps edit the question to include its tag. As its followers may provide a better, or specific solutions. – Nae Dec 12 '17 at 13:34

1 Answers1

1

Your while True loop won't be working as long as the GUI isn't closed. Try removing it and instead define a new function:

def ctr():
    global input_state, buttonPin, Counter
    input_state = GPIO.input(buttonPin)

    if (not input_state):
        Counter += 1
        print(Counter)
        root.after(30, ctr)

and call it once in the main body of script before root.mainloop():

ctr()
Nae
  • 14,209
  • 7
  • 52
  • 79