Search code examples
pythonimagetkinterresize

Python - Tkinter seems to be adding extra padding around the image on a label


Just starting to program in Python. Fist time posting here. My intent is to use a ttk.frame to contain a 10x10 grid of text labels with one cell replaced by an image label. For ease, I left all the text labels blank in the posted code.
When I draw the labels using grid, I find that the cell with the image label expands slightly - as if the image doesn't fit snippet of screen shot.

The result is that one row and one column are bigger than the others.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry('650x768')
frame = ttk.Frame()

frame=ttk.Frame(root)
frame.pack(expand=True, fill='both', side='left')

# iterate thru the cells populating each with a blank text label
for row in range(20): 
    frame.grid_rowconfigure(row, weight=1)
    for column in range (20):
        frame.grid_columnconfigure(column, weight=1)
        label = tk.Label(frame, borderwidth=1, relief='solid', anchor='center', bg='lightgrey')
        label.grid(column=column, row=row, sticky="nsew")

# draw the image label at grid coord (3,3) 
image = tk.PhotoImage(file='./resources/image_file.png')
label = ttk.Label(frame, image=image, anchor='center')
label.grid(column=3, row=3)

root.mainloop()

This is the image file I am using (24x20 px)
I tried changing pad and ipad settings on the label and the frame.
I tried using fewer columns and rows (5x5 and 10x10 vs 20x20). That change yields larger cells because the frame dimensions remain constant. After that the image label took up even less space within the cell, but that cell still expands slightly. The image is pretty small. You can see that the grey background color fills up the cell around the image label. I assume that means the image label should fit.
I'm sure I'm missing something simple, but I've been searching for a while and cannot find a solution.


Solution

  • After adding cell_size and setting the sticky to nsew, this should work.

    import tkinter as tk
    from tkinter import ttk
    
    root = tk.Tk()
    root.geometry('650x768')
    frame = ttk.Frame(root)
    frame.pack(expand=True, fill='both', side='left')
    
    cell_size = 32
    
    # iterate thru the cells populating each with a blank text label
    for row in range(20):
        frame.grid_rowconfigure(row, weight=1, minsize=cell_size)
        for column in range(20):
            frame.grid_columnconfigure(column, weight=1, minsize=cell_size)
            label = tk.Label(frame, borderwidth=1, relief='solid', anchor='center', bg='lightgrey')
            label.grid(column=column, row=row, sticky="nsew")
    
    # Draw the image label at grid coord (3, 3)
    image = tk.PhotoImage(file='./resources/image_file.png')
    label = ttk.Label(frame, image=image, anchor='center')
    label.grid(column=3, row=3, sticky="nsew")
    
    root.mainloop()
    

    This is the output. Do you need this?