OS X: Move window from Python

时间秒杀一切 提交于 2020-06-13 04:32:14

问题


I'm trying to move around windows programatically from Python on OS X.

I found a snippet of AppleScript here on Stackoverflow which does this, but I'd like to do it in Python or another "real" scripting language.

This is my Python script, which does not work. I wrote the output of print commands below each of them.

#!/usr/bin/python

from Foundation import *
from ScriptingBridge import *

app = SBApplication.applicationWithBundleIdentifier_("com.apple.SystemEvents")

finderProc = app.processes().objectWithName_("Finder")

print finderProc
# <SystemEventsProcess @0x74b641f0: SystemEventsProcess "Finder" of application "System Events" (29683)>

finderWin = finderProc.windows()[0]

print finderWin
# <SystemEventsWindow @0x74b670e0: SystemEventsWindow 0 of SystemEventsProcess "Finder" of application "System Events" (29683)>

print finderWin.name()
# Macintosh HD

finderWin.setBounds_([[20,20],[100,100]])
# no visible result

finderWin.setPosition_([20,20])

The last command (setPosition_) crashes with the following exception.

Traceback (most recent call last):
  File "/Users/mw/Projekte/Python/winlist.py", line 17, in <module>
    finderWin.setPosition_([20,20])
AttributeError: 'SystemEventsWindow' object has no attribute 'setPosition_'

How can I make the setBounds command work?


回答1:


If you want to interact with OS X's Accessibility APIs from Python then try atomac. System Events is just an AppleScriptable wrapper around various system APIs, but PyObjC and other Python libraries already give you extensive access to the system APIs without having to deal with any AS/SB nonsense.

--

p.s You may need to enable the 'assistive devices' option in System Preferences' Accessibility pane, otherwise most accessibility features won't be available.




回答2:


You don't have to do it via System Events (I doubt that will work). Instead, do it directly on the Finder app:

from ScriptingBridge import *

app = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
finderWin = app.windows()[0]
finderWin.setBounds_([[100,100],[100,100]])
finderWin.setPosition_([20,20])

You don't need the Foundation import either.



来源:https://stackoverflow.com/questions/16598551/os-x-move-window-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!