dorlox
dorlox

Reputation: 75

Centering an image as canvas on tkinter

canvas = tk.Canvas(root, height=400, width=1100)
image = PhotoImage(file="C:\\Users\\name\\Pictures\\picture.png")
canvas.create_image(0, 0, anchor="center", image=image)
canvas.place(relx=0.5, rely=0.5, anchor="center")
root.resizable(width=False, height=False)
canvas.pack()

I have tried making an image the canvas for my GUI and it will not center it self on the application...I've tried all types of functions like relative X and Y to the canvas and anchoring but I can't seem to get it to center it self..

Upvotes: 0

Views: 3971

Answers (1)

scotty3785
scotty3785

Reputation: 7006

You need to use the create_image(x,y,...) to specify the coordinates for the middle of the canvas. The centre is the height/width divided by two.

from tkinter import *

root = Tk()
HEIGHT = 400
WIDTH = 1100
canvas = Canvas(root, height=HEIGHT, width=WIDTH)
image = PhotoImage(file=r"C:\Users\User\MyImage.png")
canvas.create_image(WIDTH/2, HEIGHT/2, anchor="center", image=image)
root.resizable(width=False, height=False)
canvas.pack()

root.mainloop()

Upvotes: 3

Related Questions