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
from tkinter import *
app = Tk()
app.title( "Main App" )
app.geometry( '300x100' )
def top_level():
top = Toplevel()
top.title( "TopLevel Window" )
top.geometry( '200x200' )
msg = Message(top, text = "Text on TopLevel window" , width = 150 )
msg.pack()
def exit_btn():
top.destroy()
top.update()
btn = Button(top, text = 'EXIT' , command = exit_btn)
btn.pack()
Button(app, text = "Create a TopLevel window" , command = top_level).pack()
app.mainloop()
|
Output: