Tkinter displaying an image on fullscreen

114 Views Asked by At

I am trying to set a background image for a menu. However, the image comes with some white padding that I can't quite remove.

The image works fine and it is being every element i place on the screen.

I am looking for a way to remove this padding. Or, in other words, for the image to fit the whole screen.

This is my code

from tkinter import Tk, Label, Button, Menu, PhotoImage

window = Tk()
window.state('zoomed')

color1 = '#020f12'
color2 = '#05d7ff'
color3 = '#65e7ff'
color4 = 'BLACK'

background = PhotoImage(file = r'C:\Users\acout\OneDrive - Activos Reais\Uni\Git\Tkinter\cars_background.png')
background_label= Label(window, image=background)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

def configure_window():
    window.geometry("800x600") # this might interfere with window.state zoomed idk
    window.configure(background='#b3ffff')
    window.title("My Tkinter game yo - car go brrr")
    window.iconbitmap(default = r'C:\Users\acout\OneDrive - Activos Reais\Uni\Git\Tkinter\carro.ico')
    window.columnconfigure(0, weight=1)
    window.columnconfigure(1, weight=1)
    window.rowconfigure(0, weight=1)
    window.rowconfigure(1, weight=1)
    window.rowconfigure(2, weight=1)


this is what it looks like: enter image description here

1

There are 1 best solutions below

0
acw1668 On

In order to resize an image to fit a window, you need a library like Pillow to resize the image whenever the window (or the label containing the image) is resized:

...
from PIL import Image, ImageTk
...
# load the image
background = Image.open('C:/Users/acout/OneDrive - Activos Reais/Uni/Git/Tkinter/cars_background.png')
background_label= Label(window)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

# function to resize the image
def resize_background_image(event):
    resized = background.resize((event.width, event.height))
    tkimg = ImageTk.PhotoImage(resized)
    background_label.configure(image=tkimg)
    # use an attribute to save the reference of image to avoid garbage collection
    background_label.image = tkimg  

# call the resize function when the label is resized
background_label.bind("<Configure>", resize_background_image)
...