I am beginner in tkinter. I have added a resizable background which is perfectly working. Have look to the code '''
import tkinter as tk
from PIL import ImageTk, Image
homeWin = tk.Tk()
homeWin.geometry("400x400")
background = ImageTk.PhotoImage(file = "bg.png")
hw_canvas = tk.Canvas(homeWin, width = 400, height=400)
hw_canvas.pack(fill="both", expand=True)
bg = hw_canvas.create_image(0, 0, image = background, anchor = "nw")
def bg_resizable(e):
global image, resized, image2
# open image to resize it
image = Image.open("bg.png")
# resize the image with width and height of root
resized = image.resize((e.width, e.height), Image.LANCZOS)
image2 = ImageTk.PhotoImage(resized)
hw_canvas.create_image(0, 0, image=image2, anchor='nw')
homeWin.bind("<Configure>", bg_resizable)
homeWin.mainloop()
''' but after placing a frame on the canvas it is not working. I don't know why this is. Pleas help me with it! '''
import tkinter as tk
from PIL import ImageTk, Image
homeWin = tk.Tk()
homeWin.geometry("400x400")
background = ImageTk.PhotoImage(file = "bg.png")
hw_canvas = tk.Canvas(homeWin, width = 400, height=400)
hw_canvas.pack(fill="both", expand=True)
bg = hw_canvas.create_image(0, 0, image = background, anchor = "nw")
def bg_resizable(e):
global image, resized, image2
# open image to resize it
image = Image.open("bg.png")
# resize the image with width and height of root
resized = image.resize((e.width, e.height), Image.LANCZOS)
image2 = ImageTk.PhotoImage(resized)
hw_canvas.create_image(0, 0, image=image2, anchor='nw')
homeWin.bind("<Configure>", bg_resizable)
sl_frame = tk.Frame(hw_canvas, bg="white", width= 200, height=500)
sl_frame.place(relx= 0.5, rely= 0.5, anchor="center")
homeWin.mainloop()
'''
CodePudding user response:
"<Configure>"
events get called for main window and all children!
Using the following can exclude child "<Configure>"
events:
import tkinter as tk
from PIL import ImageTk, Image
def bg_resizable(e):
global image, resized, image2
# main window has no master
if e.widget.master:
return
# resize the image with width and height of root
resized = image.resize((e.width, e.height), Image.LANCZOS)
image2 = ImageTk.PhotoImage(resized)
hw_canvas.itemconfigure(bg, image=image2)
image = Image.open("bg.png") # open image once, global
homeWin = tk.Tk()
homeWin.geometry("400x400")
hw_canvas = tk.Canvas(homeWin, width = 400, height=400)
hw_canvas.pack(fill="both", expand=True)
bg = hw_canvas.create_image(0, 0, anchor='nw')
sl_frame = tk.Frame(hw_canvas, bg="white", width= 200, height=500)
sl_frame.place(relx= 0.5, rely= 0.5, anchor="center")
homeWin.bind("<Configure>", bg_resizable)
homeWin.mainloop()
Also, note because event fires when window is first shown, there is not need to handle background outside of event.