Tkinter窗口专注于Mac OS X [英] Tkinter window focus on Mac OS X

查看:191
本文介绍了Tkinter窗口专注于Mac OS X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an application in Python with the Tkinter GUI framework. It listens for keyboard and mouse events, so it must have focus. When it is launched from a terminal in Ubuntu, the following code works:

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)中的终端启动时,终端仿真器会保留焦点,直到用户单击窗口为止.有谁知道解决方法?

However, when launched from a terminal in Mac OS X 10.8.4 (stock Python 2.7.2), focus is retained by the terminal emulator until the user clicks on the window. Does anyone know of a workaround for this?

推荐答案

我尝试过此方法,对我来说效果很好:

I tried this and it worked well for me:

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(),然后将其移动到您所有应用程序窗口的最前面.

Of course, that'll bring your entire application to the front, not just a specific window, but after you do that, you can then use focus_force() on a specific frame or window and that'll get moved to become the frontmost of all your application windows.

对于那些感兴趣的人,我自己没有写system()电话.我在在SourceForge上的该线程中找到了它.

For those interested, I didn't write the system() call myself. I found it in this thread on SourceForge.

我将system()调用放在一个if块中以验证它是否已在OS X上运行,这一事实使该解决方案跨平台-我的理解是focus_force()完全可以在您希望的所有其他平台上工作,并且在system()调用之后执行该操作也不会在OS X中引起任何问题.

The fact that I put the system() call within an if block that verifies this is running on OS X makes the solution cross platform - my understanding is that focus_force() works on all other platforms exactly as you want, and just performing it after the system() invocation wouldn't cause any problems in OS X, either.

这篇关于Tkinter窗口专注于Mac OS X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆