如何让pystray托盘图标左键点击也显示右键菜单?
解决pystray左键点击显示菜单的问题
pystray默认仅支持右键点击弹出菜单,要实现左键点击显示菜单,需要手动绑定on_click回调函数,在左键触发时调用菜单显示方法。
核心实现步骤
- 定义左键点击回调函数,判断点击的是左键(鼠标按钮编号为1)
- 在回调中调用托盘图标实例的
show_menu()方法,手动弹出菜单 - 创建
Icon实例时指定on_click参数绑定回调
修改后的完整代码
from pystray import Icon as icon, Menu as menu, MenuItem as item from PIL import Image, ImageDraw def create_image(width, height, color1, color2): image = Image.new('RGB', (width, height), color1) dc = ImageDraw.Draw(image) dc.rectangle( (width // 2, 0, width, height // 2), fill=color2) dc.rectangle( (0, height // 2, width // 2, height), fill=color2) return image def on_left_click(icon_inst, button, x, y): # 1对应鼠标左键,3对应右键 if button == 1: icon_inst.show_menu() ico = icon( 'test', create_image(64, 64, 'black', 'white'), menu=menu( item( 'With submenu', menu( item('Close App', lambda: ico.stop()), item('Submenu item 2', None) ) ) ), on_click=on_left_click ) ico.run()
补充说明
on_click回调的参数依次为:托盘图标实例、点击的按钮编号、点击位置的x/y坐标- 跨平台鼠标按钮编号统一:1=左键,2=中键,3=右键
show_menu()是pystray Icon类的公开方法,用于主动触发菜单显示
内容的提问来源于stack exchange,提问作者Phillip
相关产品推荐
相关产品推荐

