Python - 如果设置为重复,函数不会执行

Python - Function doesn't excute if set to repeat

我刚开始学习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 中的计时器,但在这两种情况下 "program" 甚至都不会启动,直到我恢复到上面提到的第一个代码,谁能告诉我如何让它每秒更新一次?

您走在正确的轨道上,需要使用 while 循环。我把它放到它自己的线程中(并将文本作为构造函数参数传递给线程class)。

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

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

text = Label(netmon, text = "\n" + 'Download : TBD' + "\n\n" + 'Upload : TBD', anchor = NW)
text.pack()

class GetUpdates(threading.Thread):
    def __init__(self, text):
        threading.Thread.__init__(self)
        self._stop_event = threading.Event()
        self._text = text

    def stop(self):
        self._stop_event.set()

    def run(self):
        while not self._stop_event.is_set():
            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"
            self._text['text'] = "\n" + download_rate + "\n\n" + upload_rate


getupdates = GetUpdates(text)
getupdates.start()


netmon.mainloop()

更简单的方法是通过 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()