7

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
Bogdan Balan
  • 6,493
  • 8
  • 25
  • 23
  • The _Related_ sidebar included http://stackoverflow.com/questions/4728880/instantiating-a-tkinter-window-without-grabbing-focus which looks potentially useful. – sarnold May 23 '11 at 00:32
  • I would suggest not using Tkinter unless you have to ... IMHO, its a pain. – Dhaivat Pandya May 23 '11 at 00:49
  • 6
    Don't let the naysayers fool you. Tkinter is quite useful and easy to use. – Bryan Oakley May 23 '11 at 10:52
  • I suppose wxPython is generally better (or so I heard). But what I need is a window with a canvas and lines, circles, rectangles methods, which Tk supports. So Tk being included in Python without additional installations is better (specially since I might share the program with friends). It's just toy programming that I am using it for. Thanks for the comments. – Bogdan Balan May 25 '11 at 09:22
  • Anyone has better solutions? It's quite a basic requirement for a GUI app to be seen on start. Are we missing some important point? – Shang Feb 21 '14 at 11:20
  • Another closely related question: http://stackoverflow.com/questions/1892339/make-tkinter-jump-to-the-front – Pierz Mar 18 '15 at 16:27

3 Answers3

2

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
0

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()
Caleb Hattingh
  • 9,005
  • 2
  • 31
  • 44
0

Have you tried this at the end of your script ?

root.iconify()
root.update()
root.deiconify()

root.mainloop()
nbro
  • 15,395
  • 32
  • 113
  • 196
noob oddy
  • 1,314
  • 8
  • 11