如何在画布Python Tkinter中居中图像

5 python canvas image tkinter python-imaging-library

我正在制作一个节目.获取图像并将其放入画布中.所以它就像一个照片浏览器.但我想将图像放在画布小部件的中心.但它似乎进入了左上角.为什么这样做?我怎样才能将它放在画布小部件的中心?

码:

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()
Run Code Online (Sandbox Code Playgroud)

en_*_*ght 17

问题是这条线

self.viewWindow.create_image(0, 0, anchor=CENTER, image=imageFile, tags="bg_img")
Run Code Online (Sandbox Code Playgroud)

前两个论点,如这里所解释的:http://effbot.org/tkinterbook/canvas.htm,是图像的位置.原点位于画布的左上角.你的意思是

...(width/2, height/2, anchor=CENTER, ... )
Run Code Online (Sandbox Code Playgroud)

您想要的通常几何意义上的原点是画布的中心,或宽度的一半和高度的一半.

您似乎使用了"锚",就好像它指定了画布上的位置一样.它没有.中心处的"锚"意味着图像的中心将被放置在指定的坐标处.从链接源(effbot):

ANCHOR:相对于给定位置放置位图的位置.默认为CENTER.

如果由于某种原因您不知道窗口小部件的宽度和高度,请参阅如何在tkinter中找出当前窗口小部件的大小?.tl; dr是用的

canvas.winfo_width()
Run Code Online (Sandbox Code Playgroud)

canvas.winfo_height()
Run Code Online (Sandbox Code Playgroud)