import tkinter as tk
from PIL import Image, ImageTk, ImageEnhance
import pygame, pyautogui
pygame.init()
# Initialize the main window
window = tk.Tk()
window.geometry("776x582")
window.resizable(0, 0)
window.config(cursor="@NORMAL.cur")
#canvas
canvas = tk.Canvas(window, width=776, height=582)
canvas.place(x=0, y=0, anchor=tk.NW)
background_image = tk.PhotoImage(file="bg.png")
canvas.create_image(0, 0, image=background_image, anchor=tk.NW, tags="background")
img1 = Image.open("char1.png").convert("RGBA")
img2 = Image.open("char2.png").convert("RGBA")
char1_img = ImageTk.PhotoImage(img1)
char2_img = ImageTk.PhotoImage(img2)
char1 = canvas.create_image(176, 250,image=char1_img,anchor=tk.NW)
char2 = canvas.create_image(200, 200,image=char2_img,anchor=tk.NW)
def brightness(image,val):
return ImageEnhance.Brightness(image).enhance(val)
def character(canv,char_x, char_y, char_w, char_h,img,char_img,char):
#character
img = brightness(img,1)
canv.itemconfig(char,image=char_img)
def motion(event,img):
x, y = event.x, event.y
if char_x < x < char_x + char_w and char_y < y < char_y + char_h:
img = brightness(img,1.3)
char_img = ImageTk.PhotoImage(img)
else:
img = brightness(img,1)
char_img = ImageTk.PhotoImage(img)
canv.itemconfig(char, image=char_img)
canv.bind('<Motion>', lambda event:motion(event,img))
#characters
character(canvas,176, 250, 103, 213,img1,char1_img,char1)
window.mainloop()
如果鼠标进入,我想更改img的亮度,但是当我更改它时,img没有更新idk为什么,我尝试使用.itemconfig(并在那里指定明亮的图像),我希望你们帮助我出来了。
分配给函数内局部变量的图像将在退出函数后被垃圾收集。
建议使用类和实例变量来存储图像:
class Character:
def __init__(self, canv, img, char):
self._canv = canv
self._img = img
self._char = char
canv.tag_bind(char, "<Enter>", lambda e: self.set_brightness(1.3))
canv.tag_bind(char, "<Leave>", lambda e: self.set_brightness(1))
def set_brightness(self, level):
img = brightness(self._img, level)
# use instance variable to store the image reference
# to prevent the image from garbage collection
self._photo = ImageTk.PhotoImage(img)
self._canv.itemconfig(self._char, image=self._photo)
#characters
Character(canvas, img1, char1)