TOPLEVEL IN TKINTER
In this tutorial, we are going to learn about the toplevel widget in tkinter. We will learn about its features and methods along with an example showing clear distinction between a root window and a toplevel window.
What is Toplevel in Tkinter?
Toplevel widgets in tkinter are just like Frame, but they are always contained in a new window. Those windows have title names, border and all the other features of a regular window. You can always toplevel widget for displaying pop ups, dialogue boxes or other extra windows. Syntax of toplevel widget is:
toplevel_tk = Toplevel ( window, features )
Toplevel features and properties are:
1 | bg | Declares the background color of the widget |
2 | bd | Displays the border width |
3 | cursor | You can use the cursor as different shapes on the screen as circle, dot etc. |
4 | class | The text selection in the window manager will be exported when you select text within a text widget. If you avoid this option, set exportselection=0. |
5 | font | Determines the type of font that is used for the toplevel items. |
6 | fg | Determines the foreground color of font that is used for the toplevel items. |
7 | height | Determines the height of the toplevel widget. The default value is 10. |
8 | relief | Sets the border type. The default is FLAT. |
9 | width | Determines the width of window. |
Methods for a toplevel widget are:
1 | deiconify() | Used for displaying the window. |
2 | frame() | Used for showing a system dependent window identifier. |
3 | group(window) | Used for adding a window to a specified group. |
4 | iconify() | Used for converting the toplevel window to an icon. |
5 | protocol(name, function) | Used for mentioning a function name that will be called for a specific protocol. |
6 | state() | Used for getting the current state of a window. |
7 | transient([master]) | Used for converting the window into a transient window. |
8 | withdraw() | Used for withdrawing from the window but not for deleting it. |
9 | maxsize(width, height) | Used for declaring the maximum size of the window. |
10 | minsize(width, height) | It is used to declare the minimum size for the window. |
11 | positionfrom(who) | Used for specifying the position controller. |
12 | resizable(width, height) | Used for controlling if the window can be resizable or not. |
13 | sizefrom(who) | Used for defining the size of the controller. |
14 | title(string) | Used for defining the title for the window. For example: ‘Hello Tkinter’. |
Creating Toplevel Widget
You can create simple a toplevel widget as follows:
from tkinter import * screen = Tk() screen.geometry('300x300') label1 = Label(screen, text="""This is Original Window""") label1.pack() #you can make as many Toplevels as you like new_window = Toplevel(screen) new_window.geometry('300x300') label2 = Label(new_window, text="""This is Toplevel Window""") label2.pack() screen.mainloop()
Output will be:
References have been used from here