使用GPIO按钮启动时RPI程序不起作用

时间:2019-06-05 22:43:53

标签: python tkinter raspberry-pi raspberry-pi3 gpio

因此,我正在制作简单的运动信号灯以显示结果和时间。我将TkInter用于GUI和GPIO(物理按钮)以添加分数,暂停/重置分数等。 当我使用GPIO按钮启动计时器/程序时,其他GPIO按钮不再起作用,我也不知道为什么。我无法添加分数或暂停计时器... 如果我使用GUI按钮启动程序,则它可以正常工作,并且可以添加乐谱,并使用其他GUI按钮暂停计时器。这是代码,我认为传递“ root”存在一些问题。 另外,当按下GPIO按钮时,它传递参数,因此我必须将“ smth”用于函数,而当您按下GUI按钮时,则没有任何东西可以传递给函数。 所以总而言之,当我按GUI按钮调用start()时,一切正常,当我从GPIO按钮添加分数开始,而其他GPIO按钮不起作用

import RPi.GPIO as GPIO
import Tkinter as tk
import time


GPIO.setmode(GPIO.BCM)

GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) 
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP) 
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP) 


def fun_score1(smth):
    global score1
    score1 += 1
    label_team1['text'] = 'Team 1: ' + str(score1)

def fun_score2(smth):
    global score2
    score2 += 1
    label_team2['text'] = 'Team 2: ' + str(score2)

def start():
    global count_flag, count
    count_flag = True

    while True: 
        if count_flag == False:
            break
        # put the count value into the label
        label_time['text'] = str(count)
        # wait for 0.1 seconds
        time.sleep(0.1)
        # needed with time.sleep()
        root.update()
        # increase count
        count += 0.1

def stop(smth=1):
    global count_flag, count, score1, score2
    count_flag = False
    count = 0.0
    score1 = 0
    score2 = 0
    label_time['text'] = str(count)
    label_team1['text'] = 'Team 1: ' + str(score1)
    label_team2['text'] = 'Team 2: ' + str(score2)

def pause(smth=1):
    global count_flag
    count_flag = False

count = 0.0
score1 = 0
score2 = 0

root = tk.Tk()
# this will be a global flag
count_flag = True

# create needed widgets
label_time = tk.Label(root, text='0.0')
label_team1 = tk.Label(root, text='Team 1: ' + str(score1))
label_team2 = tk.Label(root, text='Team 2: ' + str(score2))

#btn_pause = tk.Button(root, text='Pause', command=pause)
btn_start = tk.Button(root, text='Start', command=start)
#btn_stop = tk.Button(root, text='Reset', command=stop)

btn_start.grid(row=1, column=0, padx=5, pady=5)
#btn_stop.grid(row=1, column=2, padx=5)
#btn_pause.grid(row=1, column=1, padx=5)

label_time.grid(row=0, column=0, columnspan=2)
label_team1.grid(row=2, column=0, padx=5, pady=5)
label_team2.grid(row=2, column=3, padx=5, pady=5)

GPIO.add_event_detect(22, GPIO.RISING, callback=start, bouncetime=300)
GPIO.add_event_detect(24, GPIO.RISING, callback=stop, bouncetime=300)
GPIO.add_event_detect(23, GPIO.RISING, callback=pause, bouncetime=300)
GPIO.add_event_detect(4, GPIO.RISING, callback=fun_score1, bouncetime=300)
GPIO.add_event_detect(17, GPIO.RISING, callback=fun_score2, bouncetime=300)


# start the event loop
root.mainloop()

Program GUI

0 个答案:

没有答案