Tkinter窗口专注于Mac OS X.

Sea*_* W. 12 python macos tkinter

我正在使用Tkinter GUI框架在Python中编写应用程序.它会侦听键盘和鼠标事件,因此必须具有焦点.当它从Ubuntu中的终端启动时,以下代码有效:

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()
Run Code Online (Sandbox Code Playgroud)

但是,当从Mac OS X 10.8.4(库存Python 2.7.2)中的终端启动时,终端仿真器会保留焦点,直到用户单击窗口.有谁知道这个的解决方法?

Art*_*are 12

我尝试了这个,它对我有用:

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' ''')
Run Code Online (Sandbox Code Playgroud)

当然,这会将您的整个应用程序放在前面,而不仅仅是一个特定的窗口,但是在您这样做之后,您可以focus_force()在特定的框架或窗口上使用,并且它将被移动到您所有应用程序的最前端视窗.

对于那些感兴趣的人,我没有system()自己写电话.我在SourceForge上找到了这个帖子.

事实上,我将system()调用放在一个if块中,以验证它是否在OS X上运行,这使得解决方案跨平台 - 我的理解是,它focus_force()可以完全按照您的需要在所有其他平台上运行,并且只是在system()调用后执行它不会导致OS X中的任何问题.

  • 一个简单的gosh-make-it-work-now hack :-).谢谢! (2认同)