How to center a image in a canvas Python Tkinter How to center a image in a canvas Python Tkinter tkinter tkinter

How to center a image in a canvas Python Tkinter


The problem is the line

self.viewWindow.create_image(0, 0, anchor=CENTER, image=imageFile, tags="bg_img")

The first two arguments, as explained here: http://effbot.org/tkinterbook/canvas.htm, are the position of the image. The origin is in the top left of the canvas. What you mean is

...(width/2, height/2, anchor=CENTER, ... )

The origin in the usual geometric sense that you want is at the center of the canvas, or half its width and half its height.

You seemed to have used "anchor" as if it specifies the location on the canvas. It doesn't. "anchor" at center means that the center of the image will be placed at the specified coordinates. From the linked source (effbot):

ANCHOR: Where to place the bitmap relative to the given position. Default is CENTER.

If for some reason you don't know the width and height of the widget, see How to find out the current widget size in tkinter?. The tl;dr is to use

canvas.winfo_width()

and

canvas.winfo_height()