Python Forum

Full Version: Adding a Frame
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
It is the simple program, where I tried to make the Frame widget clear for me, but something went wrong. When I start the program:
from tkinter import *

root = Tk()
root.geometry("500x500")


def new():
    global ss
    ss = Frame(root, height=200, width=200, bg="red")
    ss.pack()


clean = Button(root, text="Delete", command=lambda: ss.destroy())
clean.pack()

add = Button(root, text="Add", command=new())
add.pack()

ss = Frame(root, height=200, width=200, bg="red")
ss.pack()

root.mainloop()
it makes the window with 2 red squares and 2 buttons. But the location of all this things is rather strange. Button, then square, then another button and the last square. I think it is about using pack().
I wish the whole program to start with a one red square and two buttons. Pressing "Delete" button will cause the deleting of the Frame widget(it works, I think, because I used lambda), pressing "Add" button has to cause the creating of the same Frame that we just deleted. But it does not. Pressing this button has no effect on program.
I will appreciate any help, thanks.
P.S. I just new in Python, so have such stupid questions.
Instead of destroying and creating the same frame over and over, you can use grid _forget or pack_forget() and then grid/pack() it again when you want it to appear.
from tkinter import *

root = Tk()
root.geometry("500x500")

def new():
    ss.grid(row=0, column=0)

ss = Frame(root, height=200, width=200, bg="red")
ss.grid(row=0, column=0)

clean = Button(root, text="Delete", command=ss.grid_forget)
clean.grid(row=1, column=0)

add = Button(root, text="Add", command=new)
add.grid(row=2, column=0)


root.mainloop() 
(Mar-02-2018, 03:45 AM)woooee Wrote: [ -> ]Instead of destroying and creating the same frame over and over, you can use grid _forget or pack_forget() and then grid/pack() it again when you want it to appear.
from tkinter import *

root = Tk()
root.geometry("500x500")

def new():
    ss.grid(row=0, column=0)

ss = Frame(root, height=200, width=200, bg="red")
ss.grid(row=0, column=0)

clean = Button(root, text="Delete", command=ss.grid_forget)
clean.grid(row=1, column=0)

add = Button(root, text="Add", command=new)
add.grid(row=2, column=0)


root.mainloop() 
Okay, probably, i will use it, but what should i do while using .place()? And what is the problem with my code?