Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tkinter: displays only a portion of an image

This only displays the bottom right corner of my image. What am I doing wrong?

from Tkinter import *
from PIL import Image, ImageTk

class Application(Frame):
    def __init__(self, titl, master=None):
        Frame.__init__(self, master)
        self.grid()

        self.create_widgets()
        self.master.title(titl)

    def create_widgets(self):

        image_file = 'sample.jpg'
        image1 = ImageTk.PhotoImage(Image.open(image_file))
        w = image1.width()
        h = image1.height() 
        self.canvas = Canvas(self, width=w+5, height=h+5)
        self.canvas.grid(row=0, column=0)
        self.canvas.create_image(0,0, image=image1)
        self.canvas.image = image1

app = Application('Image')

app.mainloop()
like image 927
foosion Avatar asked Sep 02 '11 20:09

foosion


1 Answers

You have to set the anchor to NW (NorthWest) because its value is CENTER by default, which as the name suggests centers the image on the given coordinates:

self.canvas.create_image(0,0, image=image1, anchor=NW)

Or you can change that later if you keep the image id:

self.idImage = self.canvas.create_image(0,0, image=image1)
...
self.canvas.itemconfig(self.idImage, anchor=NW)

http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_image-method

like image 193
alexisdm Avatar answered Nov 15 '22 03:11

alexisdm