Set focus on the Tkinter window (platform dependent?)

I have a Tkinter program and run it as: python myWindow.py starts everything correctly, but the window is behind the terminal, which I use to start it.

Is there a way to get it to capture focus and be a foreground application? Does it depend on the platform?

+6
source share
3 answers

This may be a feature of your particular window manager. Try the application to call focus_force at startup, after creating all the widgets.

+2
source

Have you tried this at the end of your script?

 root.iconify() root.update() root.deiconify() root.mainloop() 
0
source

In a sense, a combination of various other methods found on the Internet, this works on OS X 10.11 and Python 3.5.1, running in Vienna, and should work on other platforms as well. In OS X, it also targets the application by process ID, not the name of the application.

 from tkinter import Tk import os import subprocess import platform def raise_app(root: Tk): root.attributes("-topmost", True) if platform.system() == 'Darwin': tmpl = 'tell application "System Events" to set frontmost of every process whose unix id is {} to true' script = tmpl.format(os.getpid()) output = subprocess.check_call(['/usr/bin/osascript', '-e', script]) root.after(0, lambda: root.attributes("-topmost", False)) 

You call this right before calling mainloop() , for example:

 raise_app(root) root.mainloop() 
0
source

Source: https://habr.com/ru/post/888784/


All Articles