I am working on a program. That gets a image and puts it in a canvas. So it is like a photo viewer. But I would like to get the image in the center of the canvas widget. But it seems to go into the top left corner. Why does it do this? And how can I get it in the center of the canvas widget?
Code:
from Tkinter import *
from PIL import ImageTk, Image
import os
class Application(Frame):
def __init__(self, parent):
Frame.__init__(self,parent)
self.pack(fill=BOTH, expand=True)
self.create_Menu()
self.create_widgets()
def create_Menu(self):
self.menuBar = Menu(self)
self.fileMenu = Menu(self.menuBar, tearoff=0)
self.fileMenu.add_command(label="Open", command=self.getImage)
self.fileMenu.add_separator()
self.fileMenu.add_command(label="Exit", command=self.exitProgram)
self.menuBar.add_cascade(label="File", menu=self.fileMenu)
root.config(menu=self.menuBar)
def create_widgets(self):
self.viewWindow = Canvas(self, bg="white")
self.viewWindow.pack(side=TOP, fill=BOTH, expand=True)
def getImage(self):
imageFile = Image.open("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg")
imageFile = ImageTk.PhotoImage(imageFile)
self.viewWindow.image = imageFile
self.viewWindow.create_image(0, 0, anchor=CENTER, image=imageFile, tags="bg_img")
def exitProgram(self):
os._exit(0)
root = Tk()
root.title("Photo Zone")
root.wm_state('zoomed')
app = Application(root)
root.mainloop()
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()