python tkinter:仅显示图像的一部分

时间:2011-09-02 20:08:39

标签: python image tkinter

这只显示我图片的右下角。我做错了什么?

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()

1 个答案:

答案 0 :(得分:7)

您必须将锚点设置为NW(NorthWest),因为默认情况下它的值为CENTER,顾名思义就是将图像置于给定坐标的中心位置:

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

或者,如果您保留图片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