【发布时间】:2021-02-23 22:03:36
【问题描述】:
我正在尝试将树莓派的一个小程序从硬按钮移植到 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
【问题讨论】:
-
第一个问题使用
Countlabel.config(text=<new text>) -
完美运行,不敢相信我没有在文档中发现这一点。感谢您的帮助!
标签: python if-statement tkinter raspberry-pi