Python - 从函数外部更新窗口类中的标签文本

我正在尝试编写一个运行我的 HVAC 和许多其他系统的应用程序,在树莓派上运行。我会第一个承认python和我不是好朋友。但是,我正在使用的传感器的驱动程序库似乎与 Java 或其他任何我准备编写代码的东西都不兼容。为我工作。


本质上,我试图获取 getcurrentTH() 函数来更新 GUI 中的 currenttempLabel。我不断收到错误。


名称错误:名称 currenttempLabel 未定义


我猜这与我如何尝试从外部函数调用类内部的标签有关。任何指针将不胜感激。


代码如下。


import mysql.connector

import time

import Adafruit_DHT as dht

from tkinter import *

import random

import _thread

import threading


started = 0

currentTemp = 0

currentHumidity = 0


def getcurrentTH():

    while started > 0:

        global currentTemp

        global currentHumidity

        h,t = dht.read_retry(dht.DHT22, 4)

        currentTemp = ((t *1.8) + 32)

        currentHumidity = h

        currenttempLabel['text'] = currentTemp

        time.sleep(5)


def start():

    global started

    started = 1

    print("started")

    print(started)

    t3 = threading.Thread(target=getcurrentTH)

    t3.start()



def stop():

    global started

    started = 0


def quitapp():

    exit()


class Window(Frame):


    def __init__(self, master = None):

        Frame.__init__(self, master)


        self.master = master


        self.init_window()


    def init_window(self):

        global currentTemp

        global currentHumidty


        self.pack(fill=BOTH, expand=1)


        startButton = Button(self, height = 3, width = 5, bg = "light green", text= "Start", command=start)


        startButton.place(x=625, y=50)


        stopButton = Button(self, height =3, width =5, bg = "red",  text = "Stop", command=stop)


        stopButton.place(x=625, y=150)


        statusLabel = Label(self,  text = "Current Status: N/A")


        statusLabel.place(x=600, y=125)


        quitButton = Button(self, height =3, width = 5, text = "Quit", command=quitapp)


        quitButton.place(x=625, y=500)


        currenttempLabel = Label(self, font = ("Courier",26), text = "No Current Reading" )

        currenttempLabel.place(x=50, y=50)


root = Tk()

root.geometry("800x600")

app = Window(root)

root.mainloop()


料青山看我应如是
浏览 121回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python