To close Tkinter Button, we can use several ways such as the use of destroy() or quit method.
We will learn this with examples based on some scenarios.
Let's get started with examples.
In this example, we created a button and a quit() method called when this button is clicked. It will destroy the root object of the Tkinter application. See the Python code.
"""
How to close Tkinter Button
"""
# import tkinter
import tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('200x100')
mybutton = tk.Button(self.root,
text = 'Click to Quit',
command=self.quit)
mybutton.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
We can directly pass the destroy() method to the command argument in the Tkinter Button construction to close the Button. See the code example below.
"""
How to close Tkinter Button
"""
# import tkinter
import tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('200x100')
mybutton = tk.Button(self.root,
text = 'Click to Quit',
command=self.root.destroy)
mybutton.pack()
self.root.mainloop()
app = App()
If you are not using class in your code then can simply call the destroy() method with Tkinter object. We don't need to use self here as we did in the above examples due to class. See the Python code.
"""
How to close Tkinter Button
"""
# import tkinter
import tkinter as tk
root = tk.Tk()
root.geometry("200x100")
def close_window():
root.destroy()
mybutton = tk.Button(text = "Click to Quit", command = close_window)
mybutton.pack()
root.mainloop()
This is another solution to close Tkinter Button. We can use quit with Tkinter object to close the instance. This is as simple as the destroy() method. See the Python code below.
"""
How to close Tkinter Button
"""
# import tkinter
import tkinter as tk
root = tk.Tk()
root.geometry("200x100")
mybutton = tk.Button(text = "Click to Quit", command = root.quit)
mybutton.pack()
root.mainloop()