Home > database >  Increase text size without changing grid cell size tkinter
Increase text size without changing grid cell size tkinter

Time:06-03

As part of a project I'm making, I have the following function that creates a grid of specified x and y cells:

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)

This works fine except the text is too small on each cell (ignore the current text, my final will be similar to wordle in that each cell will contain a large letter). This is the current size

Grid with text too small

And this is what happens if I increase the text size:

Grid with text too large

Essentially, the spacing around each character remains the same meaning the text still doesn't adequately fill the boxes. As such, my question is how can I increase the size of the text without also increasing the size of the cells, so my characters fill each cell.

CodePudding user response:

I suggest you use the place() geometry manager because it allows precise positioning.

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

Here's some screenshots showing the results of using different fontsize values:

fontsize=24:

screenshot1

fontsize=64:

screenshot2

CodePudding user response:

You can create a 1x1 blank image and add this image to every label, then you can specify the width and height in pixels which not affected by the size of the font used:

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

Result of font size 24:

enter image description here

Result of font size 64:

enter image description here

  • Related