Welcome folks today in this blog post we will be closing window using root.destroy() method using button inside functions and classes
in tkinter
gui desktop app in python. All the full source code of the application is given below.
Get Started
In order to get started you need to install the below library using the pip
command as shown below
pip install tkinter
After installing this library you need to make an app.py
file and copy paste the following code
app.py
First of all we will be using the root.destroy
command to the button
1 2 3 4 5 6 7 8 9 10 11 12 |
# using destroy Non-Class method from tkinter import * # Creating the tkinter window root = Tk() root.geometry("200x100") # Button for closing exit_button = Button(root, text="Exit", command=root.destroy) exit_button.pack(pady=20) root.mainloop() |
Now we will be using functions
to close the window
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Python program to create a close button # using destroy Non-Class method from tkinter import * # Creating the tkinter window root = Tk() root.geometry("200x100") # Function for closing window def Close(): root.destroy() # Button for closing exit_button = Button(root, text="Exit", command=Close) exit_button.pack(pady=20) root.mainloop() |
Now we will be using the classes
to close the tkinter
window
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Python program to create a close button # using destroy Class method from tkinter import * # Class for tkinter window class Window(): def __init__(self): # Creating the tkinter Window self.root = Tk() self.root.geometry("200x100") # Button for closing exit_button = Button(self.root, text="Exit", command=self.root.destroy) exit_button.pack(pady=20) self.root.mainloop() # Running test window test = Window() |
If you execute the above python script
by typing the below command
python app.py