基于this answer,我想在主图像下面添加第二个小部件。如何防止图像在调整大小时填充整个Tkinter窗口?
当用户调整大小时,该图像适合窗口。
请参阅从@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
有不同的选择,但它chnanged什么。
有没有人有我的做法错误的想法,请?
我敢打赌,这与事实有关,事实上,任何事情都会使窗口调整大小,而不仅仅是当用户拖动窗口句柄时触发事件。如果回调中的代码可以改变窗口大小,那么它可能会导致回调持续发射。 – Kevin