Python 递归限制以及如何持续监控某事

Python recursive limit and how to keep monitoring something

我正在开发一个 python 监控计算机温度的 tkinter 程序,我希望它在固定时间后更新温度值。 以下功能是我过去常做的:

    def update():
        get_temp()#the function that get the computer temperature value, like cpu temperature.
        ...
    def upd():
        update()
        time.sleep(0.3)
        upd()#recursive call function.

    upd()

但是这种方式会达到递归的极限,所以程序会在一段时间后停止。 我想让它不断更新值,怎么办? 不知道改成after()会不会好些。 但是如果我使用 after(),tkinter window 会冻结一段时间,所以我不想使用它。 谢谢。

在此use-case中递归不足,请改用循环。

Tkinter 特别有一个 方法 允许你在不中断 GUI 事件循环.

快速示例:

from tkinter import *

root = Tk()
INTERVAL = 1000 # in milliseconds

def get_temp()
   # ...
   root.after(INTERVAL, get_temp) 

get_temp()
root.mainloop()

它需要循环。 应该是:

def update():
    get_temp()#the function that get the computer temperature value, like cpu temperature.
    ...

def upd():
    while True:#needs a while true here and don't call upd() in this function.
        update()
        time.sleep(0.3)

upd()#this upd() is outside the function upd(),it used to start the function.

感谢所有帮助过我的人