Python tkinter 中的标签宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16363292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Label width in tkinter
提问by Mirac7
I'm writing an app with tkinter and I am trying to put several labels in a frame... Unfortunately,
我正在用 tkinter 编写一个应用程序,我试图在一个框架中放置几个标签......不幸的是,
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 windowTitlewidget in such way that it adapts to the lenght of the frame, or to set label width in pixels?
出于某种原因,设置标签宽度没有正确设置宽度,或者不使用像素作为测量单位......那么,有没有办法以windowTitle适应框架长度的方式放置小部件,或者以像素为单位设置标签宽度?
采纳答案by kalgasnik
heightand widthdefine the size of the label in text unitswhen it contains text.
Follow @Elchonon Edelson's advice and set size of frame + one small trick:
height并width在包含文本时以文本单位定义标签的大小。遵循@Elchonon Edelson 的建议并设置框架大小 + 一个小技巧:
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()

