【问题标题】:How would I constantly update a variable within a script/program?我将如何不断更新脚本/程序中的变量?
【发布时间】:2019-06-25 02:26:44
【问题描述】:

我正在尝试制作某种恒温器。为此,我使用了带有 DHT22 温度传感器的 Pi3 和 Python3。

我需要的是轮询温度并自行更新相应的变量。

尝试使用任何类型的 While True: 语句执行此操作会导致我正在测试的 gui 无法打开。

我迷路了(是的,这段代码是从其他人那里盗用的。哈哈)

#! python3
import time
import RPi.GPIO as GPIO
import string
import tkinter
import tkinter.ttk
import Adafruit_DHT
from tkinter import messagebox
from tkinter import *

root = Tk()
root.title('PiTEST')
root.configure(background='black')

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

sensor = Adafruit_DHT.DHT22
pin = 4

def PRINTTEST():
    print(temperature, humidity)

TESTTEXT = Label(root,text="TESTING",fg="white",bg="black",font='Consolas 20 bold')
TESTTEXT.grid(row=1,column=1,sticky="W,S,E")

B1 = tkinter.Button(root,bd=5,text="TEST",bg="gray",fg="white",command=PRINTTEST,height=4,width=20)
B1.grid(row=2,column=1,sticky="N,S,E,W",padx=8,pady=8)

while True:
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    temperature = temperature * 9/5.0 + 32

root.mainloop()

GPIO.cleanup()

【问题讨论】:

  • 你不能使用 While 循环,因为这不会让你的 root.mainloop() 启动。查看函数 root.after(),它可以持续更新变量

标签: python-3.x loops variables temperature


【解决方案1】:

这是一个没有你的 GPIO 的代码示例:

#! python3
import time
import string
import tkinter
import random
from tkinter import messagebox
from tkinter import *

root = Tk()
root.title('PiTEST')
root.configure(background='black')

def PRINTTEST():
    temperature = random.randint(0,100)
    humidity = random.randint(0,100)
    print(temperature, humidity)
    root.after(1000, PRINTTEST)

TESTTEXT = Label(root,text="TESTING",fg="white",bg="black",font='Consolas 20 bold')
TESTTEXT.grid(row=1,column=1,sticky="W,S,E")

B1 = tkinter.Button(root,bd=5,text="TEST",bg="gray",fg="white",command=PRINTTEST,height=4,width=20)
B1.grid(row=2,column=1,sticky="N,S,E,W",padx=8,pady=8)


root.mainloop()

这将在您的终端中每秒打印 2 个随机整数。

【讨论】:

  • 这只是挂起终端。我最终在它自己的线程中运行了我需要的东西。不过,我很欣赏这种洞察力。以前从未见过 root.after 的东西。
  • 这段代码应该可以工作,至少对我来说它运行正常。确保按下 GUI 中的按钮 ;)
  • 确实有效。至于每次按下按钮时打印随机整数。但是当我不按下按钮时,它是否在后台不断更新温度和湿度变量?
  • 你应该只需要按一次它就会继续打印新的随机数字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多