How to delete a Tkinter widget placement?

Viewed 189

I have buttons that won't go away. I wrote an absolute location of the buttons and it won't go away when I try to forget it. I managed to make it disappear with writing the absolute location of the button to the coordinate outside the window. How to make it go away with the delete function?

This is what I have

from tkinter import*

def delete():
    button1.pack_forget()
    button2.pack_forget()

gui =Tk()
gui.geometry("250x500")

button1 = Button(gui, text="1", command=delete, pady= 15, padx= 20)
button1.pack(pady= 5, padx= 20)
button1.place(x=85, y=60)
button2 = Button(gui, text="2", pady= 15, padx= 20)
button2.pack(pady= 5, padx= 20)
button2.place(x=63, y=120)

gui.mainloop()
1 Answers

Use place_forget() instead of pack_forget(). You may also remove the pack() calls. In your example, calling place is negating the pack call. That's why pack_forget() will not work. The button ceased to be packed the instant it was placed.

button1.pack(...)  # do it this way
button1.place(...) # nevermind, do it this way

example:

from tkinter import *

def delete():
    button1.place_forget()
    button2.place_forget()

gui =Tk()
gui.geometry("250x500")

button1 = Button(gui, text="1", command=delete, pady= 15, padx= 20)
button1.place(x=85, y=60)
button2 = Button(gui, text="2", pady= 15, padx= 20)
button2.place(x=63, y=120)

gui.mainloop()

Tkinter has 3 geometry methods ~ place, pack, and grid. Only one geometry method is required, per widget, but combining the grid or pack method with place is allowed. However, that combination is intended to allow you to alternatively pack or place widgets simultaneously within one container. In other words, some of the widgets are packed, and some of them are placed, within one container. None of the widgets are both packed and placed.

Determining which to use is simple. If you want to "dock" a widget to one or more of it's parent's edges use pack. If you need a table layout use grid. If you need arbitrary positioning use place.

Related