我是 tkinter 的初學者。我添加了一個可調整大小的背景,效果很好。看看代碼'''
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()
''' 但是在畫布上放置一個框架后它不起作用。我不知道這是為什么。請幫幫我!'''
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()
'''
uj5u.com熱心網友回復:
"<Configure>"主視窗和所有子視窗都呼叫事件!
使用以下可以排除子"<Configure>"事件:
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()
另外,請注意,因為第一次顯示視窗時會觸發事件,所以不需要處理事件之外的背景。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512058.html
標籤:Pythontkintertkinter-canvas
