[英]How do I apply the same change across dynamic widgets in python tkinter?
[英]How do I change the width of Tkinter widgets in smaller increments (Python)?
box
的左側與some_label
的左側對齊。 我無法設置寬度以使some_label
的右側也與box
的右側對齊,因為不同寬度值之間的增量太大。 35 的width
將some_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.