Search code examples
python-3.xtkinterpython-imaging-librarytkinter-canvas

Dynamically resize images in Tkinter


I have several images that I need to display in a Tkinter window (I'll probably use a canvas to display them - possibly a label). These images will take up about a third of the screen. I need the image-screen ratio to be consistent when the user uses different sized monitors.

So say the user uses a tiny monitor, the images need to take up the same photo-screen ration on the small screen, to when the user uses a massive 4K monitor.

Will Tkinter automatically do this for me? Or will I have to implement it myself - if so, is that even possible?

I don't have any code because I have no idea where to start. I thought that I could use PIL or pillow maybe, but I'm fairly new to them.

Any help would be appreciated, thanks :)


Solution

  • 1) You need to get current screen resolution: How do I get monitor resolution in Python?
    2) Then you need to adjust size of your image (How do I resize an image using PIL and maintain its aspect ratio?) and/or your window (https://yagisanatode.com/2018/02/23/how-do-i-change-the-size-and-position-of-the-main-window-in-tkinter-and-python-3/)

    So the code should look like that:

    from win32api import GetSystemMetrics
    from Tkinter import Tk
    
    screen_width, screen_height = GetSystemMetrics(0), GetSystemMetrics(1)
    
    root = Tk() # this is your window
    root.geometry("{}x{}".format(screen_width//2, screen_height//2)) # set size of you window here is example for 1/2 screen height and width
    
    img = Image.open("picture_name.png", "r") # replace with picture path
    width, height = screen_width//4, screen_height//4 # determine widght and height basing on screen_width, screen_height
    img.resize((width, height), Image.ANTIALIAS) 
    
    # todo: create more Tkinter objects and pack them into root
    
    root.mainloop()
    

    This should probably solve your problem. Regarding Tkinter usage, there are a lot of tutorials, example: http://effbot.org/tkinterbook/