Change elements position

Change elements position#

Sometimes it is useful to be able to reuse the same element without creating a new one. In such cases, you have the option to hide the element and then reposition it elsewhere.

To hide an element, you can utilize the appropriate “forget method” depending on the layout manager you used. For example, if you positioned the element using the pack method, you can use pack_forget to hide it. Similarly, if you utilized the place method, you can use place_forget, and if you used grid, you can use grid_forget and so on. Choose the appropriate forget method based on the layout manager you employed.

The following example shows how to change the pack side of the button by pressing the arrows or just hiding it with the space key.

import tkinter as tk

root = tk.Tk()
root.geometry("300x300")

button = tk.Button(root, text="My button")
button.pack(side=tk.TOP)

def replace_button(side):
    button.pack_forget()
    button.pack(side=side)
root.bind('<Up>', lambda event: replace_button(side=tk.TOP))
root.bind('<Down>', lambda event: replace_button(side=tk.BOTTOM))
root.bind('<Left>', lambda event: replace_button(side=tk.LEFT))
root.bind('<Right>', lambda event: replace_button(side=tk.RIGHT))

# If you only use the forget method on a button, 
# it will disappear. However, if you press any 
# arrow key, it will reappear in the corresponding 
# position. This way, you can reuse objects.
root.bind('<space>', lambda event: button.pack_forget())

root.mainloop()