<p>Windows的解决方案有点棘手——你不能仅仅从另一个窗口窃取焦点,你应该以某种方式将你的应用程序移到前台。
但首先,我建议你消耗一个<a href="https://stackoverflow.com/a/12203109/6634373">littlebit of windows theory</a>,所以我们可以确认,这是我们想要达到的。</p>
<p>正如我在<a href="https://stackoverflow.com/questions/22751100/tkinter-main-window-focus/47119600#comment81258243_47119600">comment</a>中提到的,这是一个使用<a href="https://msdn.microsoft.com/en-gb/library/windows/desktop/ms633539(v=vs.85).aspx" rel="noreferrer">SetForegroundWindow</a>函数的好机会(还可以检查限制!)。但考虑到这些东西是一个廉价的黑客,因为用户“拥有”前台,Windows会不惜一切代价阻止你:</p>
<blockquote>
<p>An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.</p>
</blockquote>
<p>另外,请检查<a href="https://msdn.microsoft.com/en-gb/library/windows/desktop/ms633532(v=vs.85).aspx" rel="noreferrer">this</a>页上的备注:</p>
<blockquote>
<p>The system automatically enables calls to SetForegroundWindow if the user presses the ALT key or takes some action that causes the system itself to change the foreground window (for example, clicking a background window).</p>
</blockquote>
<p>下面是一个最简单的解决方案,因为我们能够模拟<code>Alt</code>按:</p>
<pre><code>import tkinter as tk
import ctypes
# store some stuff for win api interaction
set_to_foreground = ctypes.windll.user32.SetForegroundWindow
keybd_event = ctypes.windll.user32.keybd_event
alt_key = 0x12
extended_key = 0x0001
key_up = 0x0002
def steal_focus():
keybd_event(alt_key, 0, extended_key | 0, 0)
set_to_foreground(window.winfo_id())
keybd_event(alt_key, 0, extended_key | key_up, 0)
entry.focus_set()
window = tk.Tk()
entry = tk.Entry(window)
entry.pack()
# after 2 seconds focus will be stolen
window.after(2000, steal_focus)
window.mainloop()
</code></pre>
<p>一些链接和示例:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/26323767/intercepting-a-windows-attempt-to-steal-global-focus-on-windows">Similar problem</a></li>
<li><a href="https://www.codeproject.com/Tips/76427/How-to-bring-window-to-top-with-SetForegroundWindo.aspx" rel="noreferrer">Example #1</a></li>
<li><a href="https://gist.github.com/EBNull/1419093" rel="noreferrer">Example #2</a></li>
</ul>