如何在tkinter中将图像与画布相匹配?

2024-04-26 11:13:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用tkinter把一张图片贴到画布上。我希望完整图像与画布窗口一起显示展开/收缩。然后我需要能够把按钮、标签和条目放在图片的顶部,有人能帮忙吗

尝试使用.pack(side = both, expand = True),但是我无法使用.grid()来指定按钮的确切位置等

class Example(Frame):
    def __init__(self, master, *pargs):
        Frame.__init__(self, master, *pargs)

        self.image = Image.open("Menu_Display.png")
        self.img_copy= self.image.copy()
        self.background_image = ImageTk.PhotoImage(self.image)
        self.background = Label(self, image=self.background_image)
        self.background.pack(fill = BOTH, expand = YES)
        self.background.bind('<Configure>', self._resize_image)

    def _resize_image(self,event):

        new_width = event.width
        new_height = event.height

        self.image = self.img_copy.resize((new_width, new_height))

        self.background_image = ImageTk.PhotoImage(self.image)
        self.background.configure(image =  self.background_image)

e = Example(root)
e.pack(fill = BOTH, expand = YES)

root.mainloop()

这非常有效,除了我不能在上面添加更多对象或指定它们的位置


Tags: imageselfeventnewexample画布图片width