key_alt
key_alt

Reputation: 11

How do I keep this image in the center of the window?

I'm making a hangman-like game; for that, I need all the different stages of the man to be visualized, hence images. I want the entire tkinter window to be an image, when I change the size it pushes the image right.

from tkinter import *

root=Tk()
root.geometry("600x350")

canvas = Canvas(root, width=1600, height=900)
canvas.pack()
img = PhotoImage(file="4.png")
canvas.create_image(470,190, image=img, )
root.mainloop()

Upvotes: 1

Views: 365

Answers (1)

furas
furas

Reputation: 143187

If canvas is bigger than window then when you resize then it show more canvas but and it can looks like it moves image.

But if you use smaller canvas then pack() will try to keep centered horizontally. And if you add pack(expand=True) then it will try to keep it centered vertically.

In example code I added red background to window to show where is canvas

import tkinter as tk  # PEP8: import *

root = tk.Tk()
root.geometry("600x350")

root['bg'] = 'red'

img = tk.PhotoImage(file="lenna.png")

canvas = tk.Canvas(root, width=600, height=350)
canvas.pack(expand=True)
canvas.create_image(300, 175, image=img)

root.mainloop()

Image Lenna from Wikipedia

PEP 8 -- Style Guide for Python Code


Before resizing:

enter image description here

After resizing:

enter image description here


If you want to draw only image then you could use Label(image=img)

import tkinter as tk  # PEP8: import *

root = tk.Tk()
root.geometry("600x350")
root['bg'] = 'red'

img = tk.PhotoImage(file="lenna.png")

label = tk.Label(root, image=img)
label.pack(expand=True)

root.mainloop()

Before resizing:

enter image description here

After resizing:

enter image description here


BTW:

tkinter can bind() some function to event <Configure> and it will execute this function everytime when you resize window (and/or move window) - and this function may also move or resize image in window.

import tkinter as tk  # PEP8: import *
from PIL import Image, ImageTk

def resize(event):
    global img
    
    lower = min(event.width, event.height)
    #print(event.width, event.height, 'lower:', lower)
    
    new_image = original_image.resize((lower, lower))
    img = ImageTk.PhotoImage(new_image)  # need to assign to global variable because there is bug in PhotoImage
    
    label['image'] = img

# --- main ---

root = tk.Tk()
root.geometry("350x350")
root['bg'] = 'red'

original_image = Image.open("lenna.png")
img = ImageTk.PhotoImage(original_image)

label = tk.Label(root, image=img)
label.pack(expand=True)

root.bind('<Configure>', resize)

root.mainloop()

Before (it resized image at start to fit window):

enter image description here

After (it resized image to fit window):

enter image description here

enter image description here

enter image description here

Upvotes: 3

Related Questions