How to exit from Python using a Tkinter Button?
When creating a GUI application using Python’s tkinter module, it’s essential to know how to exit the application gracefully when required. And, one of the most common ways to exit a tkinter application is by simple clicking a button.
In this article, we’ll explore how to exit from Python using a Tkinter button.
Prerequisites
Before getting started, make sure that you have Python and tkinter installed on your system.
The Code
To start with, we need to create a tkinter button to trigger the exit event.
from tkinter import *
root = Tk()
btn_exit = Button(root, text="Exit", command=root.quit) #add command to exit
btn_exit.pack()
root.mainloop()
In the above code, we import the tkinter module and create a tkinter window using root=Tk().
Next, we create a button widget using Button()
that displays the text “Exit” and calls root.quit()
when clicked. The root.quit()
method is used to exit the tkinter application gracefully.
Finally, we pack the button using btn_exit.pack()
, it is the geometry manager that organizes the widgets in blocks before placing them in the parent widget.
To run this code, save it in a file with .py
extension and execute it. You’ll notice a simple tkinter window with a button labeled “Exit.” Pressing this button will exit the application gracefully.
Sample Code
from tkinter import *
root = Tk()
btn_exit = Button(root, text="Exit", command=root.quit) #add command to exit
btn_exit.pack()
root.mainloop()
Conclusion
By using the root.quit()
command, we can easily exit from Python using a tkinter button. It’s a simple technique yet very useful in many GUI applications. With this knowledge, you can move forward with more confidence while creating GUI applications in Python.