繁体   English   中英

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

[英]How do I change the width of Tkinter widgets in smaller increments (Python)?

box的左侧与some_label的左侧对齐。 我无法设置宽度以使some_label的右侧也与box的右侧对齐,因为不同宽度值之间的增量太大。 35 的widthsome_label的右端some_label太靠左的地方,而 36 的width some_label它放在太靠右的地方。

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()

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

import tkinter as tk

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

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

some_label = tk.Label(root, text='Some Label', borderwidth=1, relief='solid')
some_label.place(x=241, y=210, width=383, anchor='c') # set width to same as 'box'
some_label.config(font=('TkDefaultFont', 15))

root.mainloop()

要以像素为单位设置标签的宽度,您必须包含一个图像。 最简单的方法是使用透明像素并将其显示在带有compound='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()几乎总是更容易使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM