Home > OS >  Tkinter widget displacement with pack()
Tkinter widget displacement with pack()

Time:05-09

I want to pack two buttons (left and right) and a label (in the middle) in a frame. I want the label to fill the remaining space on the frame to both sides, but the widgets get displaced vertically with this code. What's the best way to do this? The widgets don't necessarily have to be packed on a frame but I want them to align horizontally while the text size of the label can change, but the buttons need to stay in place on the far left and right side. enter image description here

import tkinter as tk

root = tk.Tk()
root.geometry('600x800')
root.configure(background='#141414')

frm = tk.Frame(root)
frm.place(x=0, y=0, width=300, height=30)

btn1 = tk.Button(frm, text='button1')
lbl = tk.Label(frm, text='Lalalalalala')
btn2 = tk.Button(frm, text='button2')

btn1.pack(side='left')
lbl.pack(fill='x')
btn2.pack(side='right')


tk.mainloop()

CodePudding user response:

You can solve this problem a couple of ways. One solution is to pack the label to one side or the other rather than the top.

btn1.pack(side='left')
lbl.pack(side='left', fill='x', expand=True)
btn2.pack(side='right')

Another is to pack the buttons first, and then pack the label. With pack the order matters.

btn1.pack(side='left')
btn2.pack(side='right')
lbl.pack(fill='x', expand=True)

For an illustrated explanation of how pack works see this answer to the question Tkinter pack method confusion

  • Related