2013-07-21 45 views
10

我正在用Tkinter GUI框架在Python中编写应用程序。它监听键盘和鼠标事件,因此它必须有焦点。当它从在Ubuntu终端启动时,下面的代码工作:Tkinter窗口焦点在Mac OS X上

from Tkinter import * 

root = Tk() 
root.focus_force() 

def key(event): 
    print "pressed", event.char 

def callback(event): 
    print "clicked at", event.x, event.y 

frame = Frame(root, width=100, height=100) 
frame.bind("<Key>", key) 
frame.bind("<Button-1>", callback) 
frame.pack() 
frame.focus_force() 

root.mainloop() 

然而,从在Mac OS X 10.8.4(股票的Python 2.7.2)的终端启动时,聚焦是由终端保持直到用户点击窗口。有谁知道这个解决方法吗?

回答

9

我想这和它的工作很适合我:

from os import system 
from platform import system as platform 

# set up your Tk Frame and whatnot here... 

if platform() == 'Darwin': # How Mac OS X is identified by Python 
    system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''') 

当然,这会带给你的整个应用程序前,不仅仅是一个特定的窗口,但是当你这样做后,你就可以在特定的框架或窗口上使用focus_force(),这样就会变成所有应用程序窗口的最前端。

对于那些有兴趣的人,我没有写自己的system()调用。我在this thread on SourceForge找到它。

,我把system()调用的,如果块验证这是在OS X上运行中的事实使得该解决方案跨平台 - 我的理解是,focus_force()适用于所有其他平台完全按照你想要的,经过短短演艺吧在OS X中调用system()也不会导致任何问题。

+1

一个简单的天作之合 - 现在工作 - 现在破解:-)。谢谢! – yair

-1

做wait_visibility和event_generate帮助吗?

例如。像 -

from Tkinter import * 

root = Tk() 

def key(event): 
    print "pressed", event.char 

def callback(event): 
    print "clicked at", event.x, event.y 

frame = Frame(root, width=100, height=100) 
frame.bind("<Key>", key) 
frame.bind("<Button-1>", callback) 
frame.pack() 

frame.focus_set() 

root.wait_visibility() 
root.event_generate('<Button-1>', x=0, y=0) 

root.mainloop() 
+0

不幸的是不是 –

2

来到这里,想知道同样的问题,但我发现,从凯文·沃尔泽这一明智的冠冕堂皇答案,建议使用py2app

是的,这是OS X上运行标准行为终端 中的应用程序会一直关注终端,除非您通过单击窗口进行切换。命令选项卡的行为由窗口系统决定,而不是由新产生的进程决定。

解决方法是使用py2app将应用程序包装在标准的Mac应用程序 包中。普通的Mac用户不会从命令行启动基于Python的游戏 。

凯文

(从https://groups.google.com/forum/#!topic/comp.lang.python/ZPO8ZN5dx3M

+0

您也可以使用[pyinstaller](http://www.pyinstaller.org/)。我喜欢它,因为我可以制作Mac App捆绑包和Windows可执行文件。 – Fiver