【问题标题】:Updating a TKinter Label during other loops在其他循环期间更新 TKinter 标签
【发布时间】:2021-07-16 18:17:24
【问题描述】:

目前我正在处理我的一个涉及传感器的项目,并通过 TKinter 在显示器上显示该感官数据。一切都是用 Python 3.7.3 编写的。

我当前处理的问题是在主循环运行时更新窗口中的标签。 我的意思是,如果我执行脚本,首先定义窗口选项,然后使用 while true 循环定义更新函数。然后它应该启动窗口。现在由于 while true 循环,它没有到达 window.mainloop() 点(显然,while 循环没有中断......)。我的兴趣达到了顶峰,我试图将 window.mainloop() 函数放在更新的 while 循环中(请不要怪我,我知道我的脚本是一团意大利面条。)我发现我可以运行整个线程中的东西,所以我决定线程化整个窗口进程,并为传感器数据添加队列。现在while循环仍然在路上并且没有正常工作,经过一番谷歌搜索后,我发现了一个可能对我有帮助的代码sn-p。在尝试在我的脚本中实现它之后,我得到了一个异常“函数 init 需要 3 个参数,但给出了 4 个参数。”(下面的代码)我有点想不通了。

请记住,我不是真正的开发人员,我只需要一个可以处理传感器数据、在窗口中显示并将当前数据导出到数据库的脚本。所以请放轻松。

当前脚本:

import time
import board
import adafruit_dht
import threading
import queue
from tkinter import *

dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)

tempQ = queue.Queue(maxsize=0)
humQ = queue.Queue(maxsize=0)
    
    
class windowMain:


    def __init__(self):
        

        self.tempC_label = Label(fenster, text="Placeholder TempC")

        self.humidity_label = Label(fenster, text="Placeholder Humidity")

        self.tempC_label.pack()
        self.humidity_label.pack()
        
        self.tempC_label.after(2000, self.labelUpdate)
        self.humidity_label.after(2000, self.labelUpdate)
    
        
    def labelUpdate(self, tempQ, humQ):
        self.tempC_label.configure(text= tempQ.get() + "°C")
        #this is just to confirm if the function called or not, to see if the label updated or not.
        #if the label didnt update, and the function called, there is something wrong with the       function
        #if the label didnt update, and the function didnt call, there is a problem somwhere else
        print("Current Temp: " +tempQ.get() + "°C")
        self.label.after(2000, self.labelUpdate)

if __name__ == "__main__":
    windowName = Tk()
    windowName.title = ("Climatemonitor")
    windowMain(windowName)
    windowName.mainloop()
    

try:
    windowThread = threading.Thread(target=windowMain, args=(tempQ, humQ, ))
    windowThread.start()
except:
    print("Unable to start thread")



while True:
    
    try:
        temperature_c= dhtDevice.temperature
        tempText= temperature_c
        tempText= str(tempText)
        tempQ.put(tempText)
        humidity = dhtDevice.humidity
        humidityP = str(humidity)
        
        #this one is just to check if the sensor reads data
        print(
              "Temp: {:.1f} C     Humidity: {}% ".format(
            temperature_c, humidity
            )
              )
        
        time.sleep(2.0)
    except RuntimeError as error:
        print(error.args[0])
        time.sleep(2.0)
        continue
    except Exception as error:
        
        dhtDevice.exit()
        raise error
    
    time.sleep(2.0)

最终目标是显示我的传感器数据,刷新 2 秒(传感器的 HZ 速率),同时传感器每 2 秒继续读取一次。 我还想补充一点,这是我第一次使用 Python,因为我还不是真正的开发人员。 提前感谢大家的每一个批评和帮助

【问题讨论】:

  • 最简单的方法是使用一个按钮来执行一个函数,然后在该函数中包含你的while循环。

标签: python loops tkinter window


【解决方案1】:

最简单的方法是使用一个按钮来执行一个函数,然后在该函数中包含你的while循环,

使用按钮可以让您在运行程序的同时开始运行,而不是在运行程序后立即启动它

示例代码应该是这样的,

import tkinter as t

def execute():
    print('hello')
    
window = t.Tk()
window.title("system")
window.geometry("550x250")
b1 = t.Button(window, text="Start", width=15, command=execute)
b1.grid(row=1, sticky="W", padx=4)
window.mainloop()

由于没有用户交互,因此可以使用button.invoke方法调用按钮,如下所示,

import tkinter as t

def execute():
    print('hello')
    
window = t.Tk()
window.title("system")
window.geometry("550x250")
b1 = t.Button(window, text="Start", width=0, command=execute)
#b1.grid(row=1, sticky="W", padx=4)
b1.invoke()
window.mainloop()

此处删除 .grid() 会导致按钮消失,但可能会在稍后更新标签值时影响您的 GUI,也可以看看这个 ->

Is there a way to press a button without touching it on tkinter / python?

Python tkinter button.invoke method trouble

【讨论】:

  • 问题是,最终产品不应该有用户交互。我同意,使用一个按钮会更容易,但它都运行在一个 Raspberry Pi 上,它会在博物馆的某个半尘土飞扬的角落自行运行,所以这不会真正起作用,因为它违背了项目的目的。
  • tkinter 中有一个按钮的“调用”方法,您可以调用它来自动单击或自动调用该方法。我已经更新了它的答案。
  • 我尝试实现该解决方案,遗憾的是我遇到了问题,即我无法指向函数之间的 tkinter 标签。当我尝试在函数 execute() 中指向它(在您的示例中)时,它给了我一个例外,即我使用的第一个函数(如上所示,我的脚本中的 init )没有带有我的标签名称的属性...
猜你喜欢
  • 1970-01-01
  • 2021-08-11
  • 2016-08-11
  • 2016-05-19
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
相关资源
最近更新 更多