如何用Python在macOS实现跟随鼠标的绿色空心置顶正方形?
解决方案
针对你的需求,在macOS环境下可以基于你已用的Quartz/rumps框架,结合Cocoa窗口API实现一个置顶、透明、仅显示绿色边框正方形的跟随鼠标应用,无需依赖Tkinter。以下是完整实现:
实现代码
import Quartz import rumps from AppKit import NSWindow, NSBorderlessWindowMask, NSColor, NSBezierPath, NSView, NSBackingStoreBuffered class MouseSquareApp(rumps.App): def __init__(self): super(MouseSquareApp, self).__init__("Mouse Square", quit_button=None) # 配置正方形参数 self.square_size = 50 # 正方形边长 self.border_width = 2 # 边框宽度 # 初始化置顶透明窗口 self.setup_floating_window() # 启动定时器,高频更新位置确保流畅跟随 self.timer = rumps.Timer(self.update_square_pos, 0.01) self.timer.start() def setup_floating_window(self): # 创建无边框窗口 self.window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_( ((0, 0), (self.square_size, self.square_size)), NSBorderlessWindowMask, NSBackingStoreBuffered, False ) # 设置窗口层级:高于屏幕保护层级,确保始终置顶 self.window.setLevel_(Quartz.NSScreenSaverWindowLevel + 1) # 窗口透明配置 self.window.setOpaque_(False) self.window.setBackgroundColor_(NSColor.clearColor()) # 忽略鼠标事件,避免干扰正常操作 self.window.setIgnoresMouseEvents_(True) # 自定义视图绘制绿色边框 self.square_view = SquareView.alloc().initWithFrame_(((0, 0), (self.square_size, self.square_size))) self.square_view.border_width = self.border_width self.window.setContentView_(self.square_view) # 显示窗口 self.window.makeKeyAndOrderFront_(None) def update_square_pos(self, _): # 获取当前鼠标位置(macOS坐标原点在屏幕左下角) mouse_loc = Quartz.NSEvent.mouseLocation() screen_height = Quartz.NSScreen.mainScreen().frame().size.height # 转换坐标:让窗口左上角位于鼠标左下方,可根据需求调整偏移 window_x = mouse_loc.x - self.square_size window_y = screen_height - mouse_loc.y - self.square_size # 更新窗口位置 self.window.setFrameOrigin_((window_x, window_y)) class SquareView(NSView): def drawRect_(self, rect): # 绘制绿色边框,内部完全透明 NSColor.greenColor().setStroke() border_path = NSBezierPath.bezierPathWithRect_(rect) border_path.setLineWidth_(self.border_width) border_path.stroke() if __name__ == "__main__": app = MouseSquareApp() app.run()
关键说明
- 窗口层级设置:通过
NSScreenSaverWindowLevel + 1确保窗口优先级高于普通应用、甚至部分置顶窗口,实现类似z-index最大值的效果。 - 透明与无干扰:设置窗口为非不透明、背景透明,同时开启
IgnoresMouseEvents,让鼠标可以正常操作其他应用,不会被这个正方形窗口拦截。 - 流畅跟随:使用0.01秒间隔的定时器高频更新位置,避免跟随延迟。
- 自定义绘制:通过
SquareView重写drawRect_方法,仅绘制绿色边框,内部保持完全透明。
依赖安装
执行以下命令安装所需依赖:
pip install pyobjc rumps
内容的提问来源于stack exchange,提问作者Nehir Gökçe
相关产品推荐
相关产品推荐

