【问题标题】:OS X: Move window from PythonOS X:从 Python 移动窗口
【发布时间】:2013-05-16 22:28:08
【问题描述】:

我正在尝试通过 OS X 上的 Python 以编程方式在 Windows 中移动。

我在 Stackoverflow 上找到了 AppleScript here 的 sn-p,它可以做到这一点,但我想用 Python 或其他“真正的”脚本语言来做。

这是我的 Python 脚本,它不起作用。我在它们下面写了打印命令的输出。

#!/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])

最后一个命令 (setPosition_) 崩溃并出现以下异常。

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_'

如何使 setBounds 命令起作用?

【问题讨论】:

  • 这是有效的 AppleScript:tell application "System Events" ; set position of first window of application process "Finder" to {20, 20} ; end tell
  • 你只想用 Python 代码来做吗?为什么不直接使用 osascript 和 do 和 os.system 调用?
  • 因为我不想使用一个特定的窗口,而是显示一个列表,用户可以从中选择一个窗口。如果我能够直接在 Python 中完成,那可能会更容易。

标签: python macos pyobjc scripting-bridge


【解决方案1】:

您不必通过系统事件来执行此操作(我怀疑这会起作用)。而是直接在 Finder 应用程序上执行:

from ScriptingBridge import *

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

您也不需要 Foundation 导入。

【讨论】:

  • 我不能这样做,因为我不想依赖目标应用程序的脚本支持。它应该适用于所有应用程序。
【解决方案2】:

如果您想通过 Python 与 OS X 的辅助功能 API 进行交互,请尝试 atomac。 System Events 只是围绕各种系统 API 的 AppleScriptable 包装器,但 PyObjC 和其他 Python 库已经为您提供了对系统 API 的广泛访问,而无需处理任何 AS/SB 废话。

--

p.s 您可能需要在“系统偏好设置”的“辅助功能”窗格中启用“辅助设备”选项,否则大多数辅助功能将不可用。

【讨论】:

猜你喜欢
  • 2010-10-11
  • 1970-01-01
  • 2011-03-02
  • 2012-09-07
  • 1970-01-01
  • 2010-09-27
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多