Tkinter main window focus
I have the following code
window = Tk()
window.lift()
window.attributes("-topmost", True)
This code works in that it displays my Tkinter window above all other windows, but it still only solves half of the problem. While the window is in fact displayed above all other windows, the window does not have focus. Is there a way not only to make the window the frontmost window in Tkinter, but also put focus on it?
If focus_force()
is not working you can try doing:
window.after(1, lambda: window.focus_force())
It's essentially the same thing, just written differently. I just tested it on python 2.7.
root.focus_force()
wouldn't work but the above method did.
Solution for Windows is a littlebit tricky - you can't just steal the focus from another window, you should move your application to foreground somehow. But first, I suggest you to consume a littlebit of windows theory, so we're able to confirm, that this is what we want to achieve.
As I mentioned in comment - it's a good opportunity to use the SetForegroundWindow function (check restrictions too!). But consider such stuff as a cheap hack, since user "owns" foreground, and Windows would try to stop you at all cost:
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.
Also, check a remark on this page:
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).
Here's goes a simplest solution, since we're able to emulate Alt
press:
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()
Some links and examples:
- Similar problem
- Example #1
- Example #2