简体   繁体   中英

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.

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 (eg 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.

So you could do something like this, but it seems buggy for me. What I have done is to bind the FocusOut event to the toplevel that was created, so every time it looses the focus it triggers the event stackingorder to put the windos in the right order. You may need to expire this code for several events of your choice, but to get you the idea.. Here is the code:

import tkinter as tk

def add_toplevel(idx, toplevel):
    if idx == 'end':
        idx = len(toplevels)
    toplevels.insert(idx,toplevel)

def create_new_window():
    root2 = tk.Toplevel()
    root2.geometry('500x500')
    add_toplevel('end',root2)
    root2.bind('<FocusOut>', stackingorder)

def stackingorder(event):
    for toplevel in toplevels:
        toplevel.lift()
        toplevel.update_idletasks()

toplevels = [] #stacking order by index

root = tk.Tk()

create_new_window()


root.mainloop()

You are maybe also intrested in this: https://stackoverflow.com/a/10391659/13629335

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM