Python provides a variety of GUI (Graphic User Interface) such as PyQt, Tkinter, Kivy and soon. Among them, tkinter is the most commonly used GUI module in Python since it is simple and easy to learn and implement as well. The word Tkinter comes from the tk interface. The tkinter module is available in Python standard library.
Note: For more information, refer to Python GUI – tkinter
Installation
For Ubuntu, you have to install tkinter module by writing following command:
sudo apt-get install python-tk
When a Tkinter program runs, it runs a mainloop (an infinite loop) which is responsible for running a GUI program. At a time only one instance of mainloop can be active, so in order to open a new window we have to use a widget, Toplevel.
A Toplevel widget works pretty much like a Frame, but it opens in a separate top-level window, such windows have all the properties that a main window (root/master window) should have.
To open a new window with a button, we will use events.
Example 1:
Python3
from tkinter import *
from tkinter.ttk import *
master = Tk()
master.geometry( "200x200" )
def openNewWindow():
newWindow = Toplevel(master)
newWindow.title( "New Window" )
newWindow.geometry( "200x200" )
Label(newWindow,
text = "This is a new window" ).pack()
label = Label(master,
text = "This is the main window" )
label.pack(pady = 10 )
btn = Button(master,
text = "Click to open a new window" ,
command = openNewWindow)
btn.pack(pady = 10 )
mainloop()
|
Output:
Example 2: This will be a class based approach, in this we will create a class which will derive Toplevel widget class and will behave like a toplevel. This method will be useful when you want to add some other properties to an existing Toplevel widget class.
Every object of this class will be a Toplevel widget. We will also use bind() method to register click event.
Python3
from tkinter import *
from tkinter.ttk import *
class NewWindow(Toplevel):
def __init__( self , master = None ):
super ().__init__(master = master)
self .title( "New Window" )
self .geometry( "200x200" )
label = Label( self , text = "This is a new Window" )
label.pack()
master = Tk()
master.geometry( "200x200" )
label = Label(master, text = "This is the main window" )
label.pack(side = TOP, pady = 10 )
btn = Button(master,
text = "Click to open a new window" )
btn.bind( "<Button>" ,
lambda e: NewWindow(master))
btn.pack(pady = 10 )
mainloop()
|
Output:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
13 Jul, 2021
Like Article
Save Article