安装依赖包:
pip install pillow psutil rumps
netSpeedApp.py
from PIL import Image, ImageDraw, ImageFont
import psutil
import rumps
class NetSpeedApp(rumps.App):
def __init__(self):
super(NetSpeedApp, self).__init__("NetSpeed")
self.title=''
self.last_download = psutil.net_io_counters().bytes_recv
self.last_upload = psutil.net_io_counters().bytes_sent
self.icon = self.generate_icon() # 设置图标
self.template = True # 为True时系统自动生成黑色图标 重点!!!
rumps.Timer(self.update_speed, 1).start() # 启动定时器,每秒更新一次
def update_speed(self, sender):
# 计算下载和上传速度
download_speed = psutil.net_io_counters().bytes_recv - self.last_download
upload_speed = psutil.net_io_counters().bytes_sent - self.last_upload
# 更新上一次的下载和上传值
self.last_download = psutil.net_io_counters().bytes_recv
self.last_upload = psutil.net_io_counters().bytes_sent
# 生成包含两行文本信息的图片
self.generate_icon(download_speed, upload_speed)
# 更新图标
self.icon = self.icon
def generate_icon(self, download_speed=0, upload_speed=0):
filename = 'img.png'
# 创建一个空白图像
image = Image.new("RGBA", (120, 40), (0, 0, 0, 0))
# 获取字体 size 20
font = ImageFont.load_default(20)
# 获取绘图上下文
draw = ImageDraw.Draw(image)
# 绘制下载和上传速度文本
draw.text((0, 0), "U: {}".format(self.format_speed(upload_speed)), font=font, fill="white")
draw.text((0, 20), "D: {}".format(self.format_speed(download_speed)), font=font, fill="white")
image.save(filename, format="PNG")
return filename
def format_speed(self, speed):
# 格式化速度,以 B、KB 或 MB 为单位
if speed < 1024:
return "{} B/s".format(speed)
elif 1024 <= speed < 1048576:
return "{:.1f} KB/s".format(speed / 1024)
else:
return "{:.1f} MB/s".format(speed / 1048576)
if __name__ == "__main__":
NetSpeedApp().run()
# 修改源码 file:rumps.py > func:_nsimage_from_file > line:128:image.setSize_((60, 20) if dimensions is None else dimensions) # (20, 20)=>(60, 20)
效果预览: