我刚开始学习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()我已经尝试了线程计时器,但是在这两种情况下,“程序”甚至不会启动,直到我恢复到上面提到的第一个代码,谁能告诉我如何让它每秒更新一次?
发布于 2020-06-20 01:37:03
您走上了正确的道路,需要使用while循环。我将它放入它自己的线程中(并将文本作为构造函数参数传递给thread类)。
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()发布于 2020-06-20 02:07:21
一种更简单的方法是通过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()https://stackoverflow.com/questions/62475413
复制相似问题