Search code examples
pythontkintertopleveltopmost

How to put a toplevel window in front of the main window in tkinter?


Is there any way to put a toplevel window in front of the main window?

Here's the code:

from tkinter import *

root = Tk()
root.geometry('1280x720')

def create_new_window():
    root2 = Toplevel()
    root2.geometry('500x500')

create_new_window()

mainloop()

Here, I want the root2 window to always stay in front of the root window.

I tried using root2.attributes('-topmost' , 1), but the problem is that this line puts the window on top of all the other programs as well.

What I want is that the toplevel window should only be in front of the main window, and it should never go back when I click on the main window.

Is there any way to achieve this in tkinter?

It would be great if anyone could help me out.


Solution

  • What you want, i think, is a transient window, you nedd to do:

    root2.wm_transient(root)
    

    From the manual:

    wm transient window ?master? If master is specified, then the window manager is informed that window is a transient window (e.g. pull-down menu) working on behalf of master (where master is the path name for a top-level window). If master is specified as an empty string then window is marked as not being a transient window any more. Otherwise the command returns the path name of window's current master, or an empty string if window isn't currently a transient window. A transient window will mirror state changes in the master and inherit the state of the master when initially mapped. It is an error to attempt to make a window a transient of itself.