tkinter: immediately selecting newly opened window

Tags: ,

The code is simple. In tkinter I create a button which opens a new window. The difference in the pictures below might be hard to see but if you look closely you can see that in the first picture the root window is selected even though it’s behind the new opened window.

In my actual program I use keybindings to operate the second window so it would be nice to instantly select this window so you don’t have to click on it to use keys to operate it. How can I select the Toplevel window as soon as it opens?

enter image description here

from tkinter import *

def open_new_window():
    top = Toplevel(root)

root = Tk()
Button(root, text="open new window", command=open_new_window).pack()


Possible duplicate of this question

Like acw1668 said, simply add top.focus() at the end of your function open_new_window

Your new open_new_window function will look like this:

def open_new_window():
    top = Toplevel(root)

Source: stackoverflow