Home > OS >  Why Tkinter place_forget() is not working?
Why Tkinter place_forget() is not working?

Time:10-02

For some reason when I try to use place_forget() or grid_forget() they won't work My code

import tkinter as tk

root=tk.Tk()
root.title("Chat test")

startframe = tk.Frame(root)
buttonstart = tk.Button(startframe)
newframe = tk.Frame(root)
newbutton = tk.Button(newframe)

def drawStart():
    startframe = tk.Frame(root, bg="blue", width=1100, height=600)
    startframe.grid()
    buttonstart = tk.Button(startframe, command=start, text="button")
    buttonstart.place(relx=0.5, rely=0.5, anchor="s")

def start():
    buttonstart.place_forget()
    startframe.grid_forget()
    newframe = tk.Frame(root, bg="blue", width=1100, height=600)
    newframe.grid()
    newbutton = tk.Button(startframe, command=start, text="button")
    newbutton.place(relx=0.5, rely=0.5, anchor="s")

if __name__ == "__main__":
    drawStart()
    root.mainloop()

Instead they remain and new frame is created below the current one. I'm using the latest version of Python.

Result

CodePudding user response:

Your problem is that the "buttonstart" and "startframe" in drawStart are local to that function. They are not related to the globals. After creating those globals. you don't really need to create them again in your function. I suggest you remove those first four definitions, and add a global declaration for the values you are creating.

This does what you expect.

import tkinter as tk

root=tk.Tk()
root.title("Chat test")

def drawStart():
    global startframe
    global buttonstart
    startframe = tk.Frame(root, bg="blue", width=1100, height=600)
    startframe.grid()
    buttonstart = tk.Button(startframe, command=start, text="button")
    buttonstart.place(relx=0.5, rely=0.5, anchor="s")

def start():
    global newframe
    global newbutton
    buttonstart.place_forget()
    startframe.grid_forget()
    newframe = tk.Frame(root, bg="blue", width=1100, height=600)
    newframe.grid()
    newbutton = tk.Button(startframe, command=start, text="button")
    newbutton.place(relx=0.5, rely=0.5, anchor="s")

if __name__ == "__main__":
    drawStart()
    root.mainloop()
  • Related