如何以较小的增量(Python)更改Tkinter小部件的宽度?

如何以较小的增量(Python)更改Tkinter小部件的宽度?,python,tkinter,widget,label,width,Python,Tkinter,Widget,Label,Width,框的左侧与某些标签的左侧对齐。由于不同宽度值之间的增量太大,我无法设置宽度,使某些标签的右侧也与框的右侧对齐。如果宽度为35,则将某些标签的右端置于太左位置,如果宽度为36,则将其置于太右位置 from tkinter import * root = Tk() root.geometry('500x500') box = Frame(root, width=383, height=246, bg='black') box.place(x=241, y=65, anchor=CENTER)

框的左侧与
某些标签的左侧对齐。由于不同宽度值之间的增量太大,我无法设置宽度,使
某些标签的右侧也与
框的右侧对齐。如果
宽度
为35,则将
某些标签的右端置于太左位置,如果
宽度
为36,则将其置于太右位置

from tkinter import *
root = Tk()

root.geometry('500x500')

box = Frame(root, width=383, height=246, bg='black')

box.place(x=241, y=65, anchor=CENTER)

some_label = Label(root, text='Some Label', borderwidth=1, relief='solid')

some_label.place(x=50, y=210)

some_label.config(width=35, font=('TkDefaultFont', 15))  # whether width is 35 or 36, the label never aligns with the box

mainloop()

要以像素为单位设置标签的宽度,必须包含图像。最简单的方法是使用一个透明像素,并将其显示在标签中,标签上的
component='center'
不会偏移文本

或者,您可以简单地使用一个包含框架来控制小部件的大小

在我的示例中,我已经包括了这两种方法

from tkinter import *

root = Tk()
root.geometry('500x500')

box = Frame(root, width=383, height=246, bg='black')
box.place(x=241, y=65, anchor=CENTER)

some_label = Label(root, text='Some Label', borderwidth=1, relief='solid')
some_label.place(x=50, y=210)
img = PhotoImage(file='images/pixel.gif')       # Create image
some_label.config(image=img, compound='center') # Set image in label
some_label.config(width=379, font=('TkDefaultFont', 15))    # Size in pixels

# Alternateivly control size by an containing widget:
container = Frame(root, bg='tan')   # Let frame adjust to contained widgets
container.place(x=241, y=360, anchor=CENTER)
# Let the contained widget set width
other_box = Frame(container, height=100, width=383, bg='black') # Set width
other_box.pack()
other_label = Label(container, text='Some Label', borderwidth=1, relief='solid')
other_label.pack(expand=True, fill=X, pady=(20,0))  # Expand to fill container
other_label.config(font=('TkDefaultFont', 15))

mainloop()
如果要进行复杂的GUI设计,
grid()
几乎总是更易于使用。

由于使用了
place()
,因此可以直接指定宽度:

将tkinter作为tk导入
root=tk.tk()
根几何体('500x500')
框=tk.Frame(根,宽=383,高=246,bg='black')
箱位(x=241,y=65,锚=c')
some_label=tk.label(根,text='some label',borderwidth=1,relief='solid')
一些_label.place(x=241,y=210,width=383,anchor='c')#将宽度设置为与“box”相同
some_label.config(font=('TkDefaultFont',15))
root.mainloop()