In this article, we will be discussing how to close only the TopLevel window in Python Tkinter.
Syntax:
def exit_btn():
top.destroy()
top.update()
btn = Button(top,text=’#Text of the exit button’,command=exit_btn)
Stepwise Implementation
Step 1: First of all, import the library tkinter.
from tkinter import *
Step 2: Now, create a GUI app using tkinter
app=Tk()
Step 3: Next, give a title to the app.
app.title(“#Title you want to assign to app”)
app.geometry(“#Dimensions of the app”)
Step 4: Further, make a function to create a TopLevel window which will be opened when pressed a button on the GUI app.
def top_level():
Step 4.1: In the function, create a TopLevel Window first.
top = Toplevel()
Step 4.2: Moreover, create a title and set the geometry for the TopLevel window.
top.title(“#Title you want to assign to TopLevel window”)
top.geometry(‘#Dimensions of the TopLevel window’)
Step 4.3: Later on, display a message in the TopLevel window.
msg = Message(top, text=”#Text you want to assign to TopLevel window”,width=#Width of the text)
msg.pack()
Step 4.4: Furthermore, make a function for creating an exit button which when clicked will close the TopLevel window.
def exit_btn(): top.destroy() top.update()
Step 4.5: In addition to it, create an exit button for closing the TopLevel window.
btn = Button(top,text=’#Text of the exit button’,command=exit_btn)
btn.pack()
Step 5: Now, declare a button on GUI app, which when clicked will deviate you to the TopLevel window.
Button(app, text=”#Text of the button deviating to TopLevel window”, command=top_level).pack()
Step 6: Finally, make an infinite loop for displaying the app on the screen.
app.mainloop()
Example:
Python3
# Python program to close only the # TopLevel window in Python Tkinter # Import the library tkinter from tkinter import * # Create a GUI app app = Tk() # Set the title and geometry of app app.title( "Main App" ) app.geometry( '300x100' ) # Make a function to create a Top Level window def top_level(): # Create a Top Level Window top = Toplevel() # Create a title and geometry for Top # Level Window top.title( "TopLevel Window" ) top.geometry( '200x200' ) # Display a message on Top Level Window msg = Message(top, text = "Text on TopLevel window" , width = 150 ) msg.pack() # Make a function for exit button def exit_btn(): top.destroy() top.update() # Create a button to exit Top Level Window btn = Button(top, text = 'EXIT' , command = exit_btn) btn.pack() # Create a button to go to Top Level Window # in GUI app Button(app, text = "Create a TopLevel window" , command = top_level).pack() # Make infinite loop for displaying app on screen app.mainloop() |
Output: