![](/img/trans.png)
[英]How to set the dimensions of a button equal to a variable in Python tkinter?
[英]How do I give tkinter labels equal dimensions?
標簽目前並排,這是我想要的。 但是每個標簽的寬度都不同。 有沒有辦法讓每個標簽具有相同的寬度?
還有一種方法可以讓標簽具有相同的測量值,同時一直填充到250?
這是我目前的代碼:
from tkinter import *
root = Tk()
root.geometry("250x50")
w = Label(root, text="Label UNO", bg="red", fg="white")
w.pack(side=LEFT)
w = Label(root, text="Label2", bg="green", fg="black")
w.pack(side=LEFT)
w = Label(root, text="Label DREI", bg="blue", fg="white")
w.pack(side=LEFT)
root.mainloop()
您應該嘗試檢查包裝上的tkinter 文檔 :
檢查這是否是您要找的:
root = Tk()
root.geometry("250x50")
w = Label(root, text="Label UNO", bg="red", fg="white")
w.pack(side=LEFT, fill=BOTH, expand=True)
w = Label(root, text="Label2", bg="green", fg="black")
w.pack(side=LEFT, fill=BOTH, expand=True)
w = Label(root, text="Label DREI", bg="blue", fg="white")
w.pack(side=LEFT, fill=BOTH, expand=True)
root.mainloop()
填充參數基本上填充父容器。
Expand參數將用於額外的剩余空間。
另外一定要看看tkinter的重量, 這里有一個例子。
您可以使用關鍵字參數width
和height
與tk.Label
import tkinter as tk
if __name__ == '__main__':
root = tk.Tk()
root.geometry("250x50")
label_frame = tk.Frame(root)
w = tk.Label(label_frame, text="Label UNO", bg="red", fg="white", width=8, height=2)
w.pack(side=tk.LEFT)
w = tk.Label(label_frame, text="Label2", bg="green", fg="black", width=8, height=2)
w.pack(side=tk.LEFT)
w = tk.Label(label_frame, text="Label DREI", bg="blue", fg="white", width=8, height=2)
w.pack(side=tk.LEFT)
label_frame.pack(expand=True)
root.mainloop()
tkinter is imported as tk
以保持名稱空間整潔。
tk.Labels
包含在tk.Frame
,因此一旦構建完成,在將幀打包到GUI中之前,您不必擔心它。
當標簽包含文本時,寬度和高度的單位為“文本單位”。
要使標簽寬度相同 ,只需將width
選項添加到label
例如width=10
這將指定字符寬度中的空間大小。
如果要將相同的寬度應用於多個標簽,請將寬度值存儲在變量中,例如label_w = 10
所以你的代碼可能如下所示:
from tkinter import *
root = Tk()
root.geometry("250x50")
label_w = 10
w = Label(root, text="Label UNO", bg="red", fg="white", width=label_w)
w.pack(side=LEFT)
w = Label(root, text="Label2", bg="green", fg="black", width=label_w)
w.pack(side=LEFT)
w = Label(root, text="Label DREI", bg="blue", fg="white", width=label_w)
w.pack(side=LEFT)
root.mainloop()
同時填充最多250個
這取決於你要創建多少個標簽,讓我們說window_width = 250
和labels_all = 3
然后width
選項也將是width = window_width/labels_all
,如果你不寫geometry
值,窗口大小將自動適合標簽。
如果您的窗口足夠簡單 ,您可以考慮使用expand
名為expand=1
的Packer Option expand
,如果您的標簽有顏色,還要包括fill
選項,填寫法定值:'x','y','both','none ”。
有關更多信息,請檢查label-options , packer-options
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.