Home > other >  Tkinter widget using pack(pady) is not moving
Tkinter widget using pack(pady) is not moving

Time:11-12

I am trying to make an app, but experiencing problems. Have a Frame:

status_frame = Frame(self.root, height=60, style='status.TFrame') # white one at the top 
status_frame.pack_propagate(0)
status_frame.pack(fill=X)

Have a Label:

status_label = Label(status_frame, text='Label', style='status_bold.TLabel')

And placing it with pack() method:

status_label.pack(side=LEFT, padx=5)

padx=5 works fine:

padx=5

But if i add pady=25 it doesn't move, it cuts strangely:

pady=25

Why is that and how can i move Label up? I need to place it with pack(). Full code:

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.geometry('400x250')
root.resizable(0, 0)

style = Style()
style.configure('status.TFrame', background='white')
style.configure('status_bold.TLabel', background='white', font=('Arial 9 bold'))
style.configure('status.TLabel', background='while')

status_frame = Frame(root, height=60, style='status.TFrame')
status_frame.pack_propagate(0)
main_frame = Frame(root, height=150)
main_frame.pack_propagate(0)
button_frame = Frame(root, height=40)
button_frame.pack_propagate(0)

status_label = Label(status_frame, text='Label', style='status_bold.TLabel')
left_button = Button(button_frame, text='Left')
right_button = Button(button_frame, text='Right')


status_frame.pack(fill=X)
Separator(root, orient=HORIZONTAL).pack(fill=X)
main_frame.pack(fill=X)
Separator(root, orient=HORIZONTAL).pack(fill=X)
button_frame.pack(fill=X)
status_label.pack(side=LEFT, padx=5, pady=25)
right_button.pack(side=RIGHT, padx=5)
left_button.pack(side=RIGHT)

root.mainloop()

CodePudding user response:

Because you've turned geometry propagation off for status_frame and forced the space to be exactly 60 pixels tall, there's not enough room for the label and 25 pixels of padding on the top and bottom. With that padding, it leaves only 10 pixels for the label. Tkinter has no choice but to remove pixels from the label.

If you are trying to use pady to move the text of the label down, you can add padding just to the top like so:

status_label.pack(side=LEFT, padx=5, pady=(25, 0))

If you want padding on both the top and the bottom, then you should not turn geometry propagation off. Personally, I think there is very rarely a case where turning propagation off is the right thing to do. By leaving propagation in place, the frame will grow or shrink so that it always fits the children widgets which is what you want 99 % of the time.

  • Related