首页 > 解决方案 > Python - 如果设置为重复,函数不会执行

问题描述

我刚开始学习Python,但我无法弄清楚这一点,基本上我想监控我的网络流量,下面运行这段代码只会显示目前捕获的结果,但它不会更新

from tkinter import*
import psutil,os
from psutil._common import bytes2human
from threading import Timer
import time

netmon = Tk()
netmon.title("NetMonitor")
netmon.geometry("200x80")

def getresults():
    total_before = psutil.net_io_counters()
    time.sleep(1)
    total_after = psutil.net_io_counters()
    download_rate = "Download : " + bytes2human(total_after.bytes_recv - total_before.bytes_recv) + " KB/S"
    upload_rate = "Upload : " + bytes2human(total_after.bytes_sent - total_before.bytes_sent) + " KB/S"
    text = Label(netmon, text = "\n" + download_rate + "\n\n" + upload_rate, anchor = NW)
    text.pack()
    #Timer(5, getresults).start

getresults()

netmon.mainloop()

我尝试过使用 while 循环:

.
.
.
while True:
   getresults()

netmon.mainloop()

我已经尝试过 Threading 中的计时器,但是在这两种情况下,“程序”甚至不会启动,直到我恢复到上面提到的第一个代码,谁能告诉我如何让它每秒更新一次?

标签: pythontkintertk

解决方案


更简单的方法是通过 APScheduler 的 BackgroundScheduler 实现解决方案:

from apscheduler.schedulers.background import BackgroundScheduler
backgroundScheduler = BackgroundScheduler(daemon=True)

backgroundScheduler.add_job(lambda : backgroundScheduler.print_jobs(),'interval',seconds=4)
backgroundScheduler.start()

...然后当完成

backgroundScheduler.shutdown()

推荐阅读