Python Tkinter – How to position a topLevel() widget relative to the root window?


In Tkinter, the toplevel widget is used to create a popup modal window. The popup window created by the toplevel window works similar to the default window of the tkinter application. It can have widgets such as text widget, button widget, canvas widget, frame, etc.

The size and position of the toplevel window can be decided by making it flexible throughout the screen. In the toplevel window, all the widgets are always placed on top of the other windows.

You can use root.winfo_x() and root.winfo_y() to get the position of the root window. Then, you can use the geometry method to position a toplevel widget relative to the root window. Making the toplevel widget relative to the root window prevents the overlapping of the two windows and separates them. Let's take an example to demonstrate how it works.

Example

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x300")
win.title("Root Window")

# Create a toplevel window
top = Toplevel(win)
top.geometry("400x200")

# Create a Label in the toplevel widget
Label(top, text= "This is a Toplevel window", font="Calibri, 12").pack()
x = win.winfo_x()
y = win.winfo_y()
top.geometry("+%d+%d" %(x+200,y+200))

# Keep the toplevel window in front of the root window
top.wm_transient(win)

top.mainloop()

Output

Running the above code will display a toplevel window apart from the main window.

Updated on: 16-Dec-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements