Home > Software engineering >  Clearing the Tkinter window (NOT closing it) after a button click
Clearing the Tkinter window (NOT closing it) after a button click

Time:01-11

I'm currently playing around with tkinter for a school project. I have a basic welcome screen set up, but after i hit the "start" button I want the screen to clear so I can make another "page."

My current code is this:

# IMPORTS #
import tkinter as tk
# ------- #

# Define Window #
window = tk.Tk()
window.title("Bioinformatics Showcase")
window.geometry("600x400")
# ------------- #

# Clear screen function #
def clearScreen(object):
    screenItem = object.grid_slaves()
    for i in screenItem:
        i.destroy()
# --------------------- #

# Event functions #
def startEvent(event):
    clearScreen(window)
# ------- #

# Create Welcome Page #
welcomeLabel = tk.Label(text="Welcome, User! :3")
welcomeLabel.place(relx = .5, rely = .1, anchor = "center")
    # Make start button
startButton = tk.Button(window, text = "Click here to start")
startButton.place(relx = .5, rely = .5, anchor = "center")
    # Bind button to start event
startButton.bind("<Button-1>", startEvent) # <Button-1> is the mouse left click
# ------------------- #

# Main loop keeps window open until user closes it #
window.mainloop()

For some reason, when I press the "Click here to start" button, nothing happens. By clearing the screen, I mean I want welcomeLabel and startButton to disappear from the GUI screen; I want it to look like if my code was only the following:

window = tk.Tk()
window.title("Bioinformatics Showcase")
window.geometry("600x400")

window.mainloop()

CodePudding user response:

Creating a frame, placing all element in that frame, and destroying that frame will help you to solve your problem

Here's the basic example:

frame=tk.Frame(window)
frame.pack()

button = tk.Button(frame, text = "Destroy All")
button.pack()

button.bind("<Button-1>", lambda x: frame.destroy())

This will destroy all elements which are in frame.

CodePudding user response:

You have used .place() to put widgets into window, so you need to use .place_slaves() instead of .grid_slaves() to get the list of widgets:

def clearScreen(obj):
    screenItem = obj.place_slaves()
    for i in screenItem:
        i.destroy()

Or you can use .winfo_children():

def clearScreen(obj):
    screenItem = obj.winfo_children()
    for i in screenItem:
        i.destroy()

Note that it is not recommended to use object as variable name because it is a reserved word in Python.

  • Related