WhyWhat
WhyWhat

Reputation: 250

How can the order of widgets in tkinter be changed?

How can the on_change_order method in the following script be implemented?

import tkinter as tk


root = tk.Tk()

# Inserts labels 1 and 2 in sequence, using .pack() method
label1 = tk.Label(root, text="Label 1", bg="red", fg="white")
label1.pack(padx=5, pady=15, side=tk.LEFT)
label2 = tk.Label(root, text="Label 2", bg="green", fg="white")
label2.pack(padx=5, pady=20, side=tk.LEFT)

def on_change_order():
    """Swaps the .pack() order of the labels 1 and 2 appearing before the button."""
    pass  # How can this be done?

button = tk.Button(root, text='Change order', command=on_change_order)
button.pack()

root.mainloop()

When the app opens, Label 1 appears first and Label 2 appears second. However, when I click the "Change order" button, I would like the labels to switch positions. That is, I would like to have the callback on_change_order change something and then have Label 2 appear first and Label 1 appear second.

In other words, how to you change the order of the elements of the "packing list" mentioned in https://www.tcl.tk/man/tcl8.6/TkCmd/pack.html#M27 ?

Upvotes: 1

Views: 1137

Answers (2)

acw1668
acw1668

Reputation: 46669

For your case, you can repack the required label before button:

def on_change_order():
    """Swaps the .pack() order of the labels 1 and 2 appearing before the button."""
    if root.pack_slaves()[0] == label1:
        label1.pack(before=button)
    else:
        label2.pack(before=button)

However it is more easier to relocate widgets using grid manager.

Upvotes: 1

stedev
stedev

Reputation: 29

def on_change_order():
    label1.pack_forget()
    label2.pack_forget()
    label2.pack(padx=5, pady=10, side=tk.LEFT)
    label1.pack(padx=5, pady=10, side=tk.LEFT)
    button.pack(after=label1)  

I think you are looking for this. Note that "Change order" button is not fixed. If you want it to save it's position on the right you should set it after label1

Upvotes: 0

Related Questions