作為我正在制作的專案的一部分,我有以下函式可以創建指定 x 和 y 單元格的網格:
def grid():
x = 5
z = 5
for i in range(x * z):
b = Label(letters, width=0, height=0,font=("Noto Sans SemiBold", 14), text=str(i)[0])
b.grid(row=math.floor(i / x), column=i % x, sticky="nsew", padx=1, pady=1)
for i in range(x):
letters.columnconfigure(i, weight=1)
for i in range(x (z - x)):
letters.rowconfigure(i, weight=1)
這作業正常,除了每個單元格上的文本太小(忽略當前文本,我的最終將類似于 wordle,因為每個單元格將包含一個大字母)。這是當前尺寸

如果我增加文本大小,就會發生這種情況:

本質上,每個字符周圍的間距保持不變,這意味著文本仍然沒有充分填充框。因此,我的問題是如何在不增加單元格大小的情況下增加文本的大小,以便我的字符填充每個單元格。
uj5u.com熱心網友回復:
您可以創建一個 1x1 空白影像并將此影像添加到每個標簽,然后您可以指定不受所用字體大小影響的width和像素:height
...
blank = PhotoImage()
def grid():
x = 5
z = 5
for i in range(x * z):
b = Label(letters, width=100, height=100, image=blank, font=("Noto Sans SemiBold", 24), text=str(i)[0], compound='c')
b.grid(row=math.floor(i / x), column=i % x, sticky="nsew", padx=1, pady=1)
for i in range(x):
letters.columnconfigure(i, weight=1)
for i in range(x (z - x)):
letters.rowconfigure(i, weight=1)
...
字體大小 24 的結果:

字體大小為 64 的結果:

uj5u.com熱心網友回復:
我建議您使用place()幾何管理器,因為它允許精確定位。
import math
import tkinter as tk
def grid():
x = 5
z = 5
fontsize = 64
pad = 2
cellsize = fontsize pad
font = ("Noto Sans SemiBold", -fontsize) # Neg font size to set size in pixels.
for i in range(x * z):
b = tk.Label(letters, width=2, height=1, font=font, text=str(i)[0], relief='ridge')
row, col = divmod(i, x)
b.place(x=row*cellsize, y=col*cellsize)
root = tk.Tk()
root.geometry('400x400')
letters = tk.Frame(root)
letters.pack(fill='both', expand=True)
grid()
root.mainloop()
以下是一些螢屏截圖,顯示了使用不同fontsize值的結果:
fontsize=24:

fontsize=64:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486923.html
