基於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