如何使用Tkinter显示计数器,显示按下按钮的次数

时间:2017-12-12 13:16:15

标签: python tkinter raspberry-pi

我正在尝试制作一个软件来显示按下按钮的次数。我做了gui工作,按钮输入工作,但我无法弄清楚每次按下按钮时如何更新计数器,root.update()不起作用。 代码:

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)

1 个答案:

答案 0 :(得分:1)

只要GUI未关闭,您的while True循环就无法正常工作。尝试删除它,而是定义一个新功能:

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

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

root.mainloop()之前在脚本主体中调用一次:

ctr()