我正在尝试将树莓派的一个小程序从硬按钮移植到gui(非常新的),我找不到一个易于理解的函数和变量分层的指南。在非gui程序中工作的变量似乎没有传播到程序的其余部分(如果这有意义的话)。我的if语句似乎也停止工作了。我对解决这个问题不太感兴趣,我更感兴趣的是,如果有人能给我指出一个可以理解的方法,让我正确地理解这个问题。下面的代码,我希望'计数'变量更新Countlabel,因为它上升和下降(这是问题1)。我也希望在张力和驱动函数工作的if语句,但我认为我有他们在错误的水平(问题2.)
import tkinter as tk
import tkinter.font
from gpiozero import LED, Button
from signal import pause
import math
import busio
import board
import adafruit_mcp4725
i2c = busio.I2C(board.SCL, board.SDA)
dac = adafruit_mcp4725.MCP4725(i2c, address = 0x63)
win=tk.Tk()
win.title("tkinter test")
myFont=tkinter.font.Font(family = 'Helvetica', size = 12, weight = 'bold')
hall=Button(21)
light1=LED(26) ##indicate you are in counting mode
light2=LED(13) ##indicate you are in tension mode
light3=LED(19)
counts = 0
def spins():
global counts
counts += 1
print("out", counts)
def reels():
global counts
counts -= 1
print("in", counts)
def home():
hall.when_pressed = spins
light1.on()
light2.off()
light3.off()
dac.normalized_value = 0.0
def tension():
hall.when_pressed = reels
light1.off()
light2.on()
light3.off()
if counts > 5:
dac.normalized_value = 0.25
else:
dac.normalized_value = 0.0
print("in", counts)
def drive():
hall.when_pressed = reels
light1.off()
light2.off()
light3.on()
if counts > 5:
dac.normalized_value = 1.0
else:
dac.normalized_value = 0.0
print("in", counts)
def exitProgram():
win.quit()
homeButton=tk.Button(win, text='Home', font=myFont, command=home, bg='cyan', height=1, width=24)
homeButton.grid(row=0, column=0, sticky=tk.NSEW)
tensionButton=tk.Button(win, text='Tension', font=myFont, command=tension, bg='cyan', height=1, width=24)
tensionButton.grid(row=1, column=0, sticky=tk.NSEW)
driveButton=tk.Button(win, text='Drive', font=myFont, command=drive, bg='cyan', height=1, width=24)
driveButton.grid(row=2, column=0, sticky=tk.NSEW)
exitButton=tk.Button(win, text='Exit', font=myFont, command=exitProgram, bg='cyan', height=1, width=6)
exitButton.grid(row=4, sticky=tk.E)
Countlabel=tk.Label(win, text=counts)
Countlabel.grid(row=5, sticky=tk.NSEW)enter code here
我的if语句在错误的级别。当我把它们移到进行计数的函数时,它们都工作了。