我正在使用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()
但是,当从Mac OS X 10.8.4(库存Python 2.7.2)中的终端启动时,终端仿真器会保留焦点,直到用户点击窗口。有没有人知道这方面的解决方法?
答案 0 :(得分:11)
我尝试了这个并且对我来说效果很好:
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()
调用放在一个if块中,以验证它是否在OS X上运行,这使得该解决方案跨平台 - 我的理解是focus_force()
可以在所有其他平台上与您完全一样希望,并且在system()
调用之后执行它也不会在OS X中引起任何问题。
答案 1 :(得分:2)
来到这里想知道同样的问题,但我发现Kevin Walzer的这个明智的回答建议使用py2app
:
是的,这是OS X的标准行为。在终端中运行应用程序 除非您通过单击窗口切换,否则将焦点保持在终端中。该 Command-Tab行为由窗口系统决定,而不是由a 新产生的过程。
解决这个问题的方法是将您的应用程序包装在标准的Mac应用程序中 使用py2app捆绑。普通的Mac用户不会发布 来自命令行的基于Python的游戏。
凯文
(来自https://groups.google.com/forum/#!topic/comp.lang.python/ZPO8ZN5dx3M)
答案 2 :(得分:-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()