我可以/应该使用 asyncio 而不是使用 Pystray 进行线程处理吗?

问题描述

我正在编写一个 Python 程序,该程序会定期抓取网站获取单个数字,然后通过 Pystray 将其显示在系统托盘中。我可以使用 threading 让它做我想做的事,但使用 asyncio 会更好 - 如果是,如何做?

来自 Pystray 手册:

pystray.Icon.run()调用是阻塞的,必须从应用程序的主线程执行。这样做的原因是 OSX 的系统托盘图标实现将失败,除非从主线程调用,并且它还需要运行应用程序 runloop。 pystray.Icon.run() 将启动 runloop。

这是否意味着 asyncio 不兼容并且对于这个应用程序必须有一个单独的线程?

这是一个使用 threading 的工作演示:

from pystray import Icon as icon,Menu as menu,MenuItem as item
from PIL import Image,ImageDraw,ImageFont
import threading
import time
import random

def make_number_icon(number):
    # draws the number as two digits in red on a transparent background
    img = Image.new('RGBA',(64,64),color=(0,0))
    fnt = ImageFont.truetype(r'C:\Windows\Fonts\GOTHICB.TTF',58)
    d = ImageDraw.Draw(img)
    d.text((0,-8),f"{number:02}",font=fnt,fill='red')
    return img

def update_icon(icon,_=None):
    # web-scraping replaced with an RNG for demo
    count = random.randrange(100)
    icon.icon = make_number_icon(count)

icon = icon("Pystray test",icon=make_number_icon(0),menu=menu(item("Update Now",update_icon),item("Quit",icon.stop)))

def update_periodically_forever():
    global icon
    while True:
        update_icon(icon)
        time.sleep(2) # shortened from 60 for demo

# I understand daemon=True cleans up this thread when we reach EOF
update_thread = threading.Thread(target=update_periodically_forever,daemon=True)
update_thread.start()

# this is a blocking call; we stay here until icon.stop() is called
icon.run()

它的样子:

enter image description here

update_icon 应该大约每 60 秒调用一次。这是上次调用函数后 60 秒还是上次调用返回函数后 60 秒都没有关系。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)