【发布时间】:2016-02-25 17:29:09
【问题描述】:
基于this answer,我想在主图像下方添加第二个小部件。
当用户调整此图像的大小时,图像旨在适合窗口。
参见@Marcin 的示例:
问题是,如果我在窗口中添加任何小部件,就会发生一些奇怪的事情(这里是文本):
图像逐渐增长,直到填满整个窗口,第二个小部件消失。
这是我的代码:
from tkinter import *
from PIL import Image, ImageTk
from io import BytesIO
import base64
root = Tk()
root.title("Title")
root.geometry("600x600")
class ImageFrame(Frame):
def __init__(self, master, *pargs):
Frame.__init__(self, master, *pargs)
self.black_pixel = BytesIO(base64.b64decode("R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="))
self.image = Image.open(self.black_pixel)
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)
self.width = 1
self.height = 1
def _resize_image(self,event):
new_width = event.width
new_height = event.height
if new_width != self.width or new_height != self.height:
self.width = new_width
self.height = new_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)
img = ImageFrame(root)
txt = Text(root)
img.pack(fill=BOTH, expand=YES)
txt.pack()
root.mainloop()
我尝试使用不同的选项包装 img 和 txt,但没有任何改变。
请问有人知道我做错了什么吗?
【问题讨论】:
-
我敢打赌,这与
事件会在任何使窗口调整大小时触发的事实有关,而不仅仅是当用户拖动窗口句柄时。如果回调中的代码可以改变窗口大小,那么它可能会导致回调近乎连续地触发。
标签: python image python-3.x tkinter image-resizing