Reputation: 6701
I have a Tkinter program and running it like: python myWindow.py
starts it all right, but the window is behind the terminal that I use to start it.
Is there a way to make it grab the focus and be the foreground application? Does it depend on the platform?
Upvotes: 8
Views: 4056
Reputation: 9225
Somewhat of a combination of various other methods found online, this works on OS X 10.11, and Python 3.5.1 running in a venv, and should work on other platforms too. On OS X, it also targets the app by process id rather than app name.
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 it right before the mainloop()
call, like so:
raise_app(root)
root.mainloop()
Upvotes: 0
Reputation: 1339
Have you tried this at the end of your script ?
root.iconify()
root.update()
root.deiconify()
root.mainloop()
Upvotes: 0
Reputation: 385870
This might be a feature of your particular window manager. One thing to try is for your app to call focus_force
at startup, after all the widgets have been created.
Upvotes: 2