Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在脚本/程序中不断更新变量?_Python 3.x_Loops_Variables_Temperature - Fatal编程技术网

Python 3.x 如何在脚本/程序中不断更新变量?

Python 3.x 如何在脚本/程序中不断更新变量?,python-3.x,loops,variables,temperature,Python 3.x,Loops,Variables,Temperature,我正在尝试做一种恒温器。为此,我使用了带有DHT22温度传感器的Pi3和Python3 我需要的是轮询温度,并自行更新相应的变量 尝试使用任何类型的While-True:语句都会导致我正在测试的gui,而不是打开 我迷路了(是的,这段代码是从别人那里拼凑起来的。哈哈) 下面是一个没有GPIO的代码示例: #! python3 import time import string import tkinter import random from tkinter import messagebox

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

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

尝试使用任何类型的While-True:语句都会导致我正在测试的gui,而不是打开

我迷路了(是的,这段代码是从别人那里拼凑起来的。哈哈)


下面是一个没有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个随机整数

您不能使用While循环,因为这无法从启动时启用root.mainloop()。请查看函数root.after(),该函数支持对仅挂起终端的变量进行连续更新。我最终在它自己的线程中运行了我需要的东西。不过我很欣赏这种洞察力。以前从未见过root.after这个东西。这段代码应该可以工作,至少对我来说,它应该像它一样运行。确保按下GUI中的按钮;)它确实有效。每次按下按钮都会打印随机整数。但是,当我不按下按钮时,它会在后台不断更新温度和湿度变量吗?你只需要按下一次,它就会不断打印新的随机数字
#! 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()