如何确定画布的mainloop行为?

时间:2019-06-20 11:25:55

标签: python-3.x tkinter

我无法解决这种方法的错误。

如果运行此代码,则会出现黑屏的画布,如果我取消对Screen类中的app.mainloop()的注释,则会出现带有图像的画布(这是预期的)。

在这两种情况下,唯一不同的是无论是在Application类还是在子类中,我都启动了mainloop。我想念什么吗?

import tkinter

from PIL import Image, ImageTk


class Screen:
    def __init__(self, app):
        self.width, self.height = app.winfo_screenwidth()//2, app.winfo_screenheight()//2
        app.geometry("%dx%d+0+0" % (self.width, self.height))

        app.bind("<Escape>", lambda x: (x.widget.withdraw(), x.widget.quit()))

        self.canvas = tkinter.Canvas(app, width=self.width, height=self.height)
        self.canvas.pack()
        self.canvas.configure(background="black")

        image = Image.open("<IMAGE_PATH>")
        resized_image = self.resize_image(image)
        resized_image = ImageTk.PhotoImage(resized_image)
        _ = self.canvas.create_image(self.width / 2, self.height / 2, image=resized_image)
        # app.mainloop()

    def resize_image(self, image):
        width, height = image.size
        ratio = min(self.width / width, self.height / height)
        width = int(width * ratio)
        height = int(height * ratio)
        return image.resize((width, height), Image.ANTIALIAS)


class Application(tkinter.Tk):
    def __init__(self):
        tkinter.Tk.__init__(self)
        self.screen_widget = Screen(self)
        print('running')
        self.mainloop()


if __name__ == "__main__":
    Application()

0 个答案:

没有答案