Reputation: 1646
I'm writing an app with tkinter and I am trying to put several labels in a frame... Unfortunately,
windowTitle=Label(... width=100)
and
windowFrame=Frame(... width=100)
are very different widths...
So far, I use this code:
windowFrame=Frame(root,borderwidth=3,relief=SOLID,width=xres/2,height=yres/2)
windowFrame.place(x=xres/2-160,y=yres/2-80)
windowTitle=Label(windowFrame,background="#ffa0a0",text=title)
windowTitle.place(x=0,y=0)
windowContent=Label(windowFrame,text=content,justify="left")
windowContent.place(x=8,y=32)
...
#xres is screen width
#yres is screen height
For some reason, setting label width doesn't set width correctly, or doesn't use pixels as measurement units... So, is there a way to place windowTitle
widget in such way that it adapts to the lenght of the frame, or to set label width in pixels?
Upvotes: 10
Views: 59265
Reputation: 3205
height
and width
define the size of the label in text units when it contains text.
Follow @Elchonon Edelson's advice and set size of frame + one small trick:
from tkinter import *
root = Tk()
def make_label(master, x, y, h, w, *args, **kwargs):
f = Frame(master, height=h, width=w)
f.pack_propagate(0) # don't shrink
f.place(x=x, y=y)
label = Label(f, *args, **kwargs)
label.pack(fill=BOTH, expand=1)
return label
make_label(root, 10, 10, 10, 40, text='xxx', background='red')
make_label(root, 30, 40, 10, 30, text='xxx', background='blue')
root.mainloop()
Upvotes: 14