首页 > 解决方案 > How to hover Image using Canvas ? TKinter

问题描述

I have a code that is working perfectly on Label widget but i am quite confuse how to convert this to Canvas ?

This is what the code I have tried.

from tkinter import * 

def onObjectClick1(event):
    print("1")
    my_pic1 = PhotoImage(file="start000-before.png")
    obj1 = canv.create_image(50,50,image=my_pic1, anchor=NW)

def onObjectClick2(event):
    print("2")
    my_pic2 = PhotoImage(file="start000-after.png")
    obj2 = canv.create_image(50,50,image=my_pic2, anchor=NW)
    
root = Tk()    
canv = Canvas(root, width=300, height=300)
my_pic1 = PhotoImage(file="start000-before.png")
obj1 = canv.create_image(50,50,image=my_pic1, anchor=NW)
canv.tag_bind(obj1, '<Enter>', onObjectClick1)        
canv.tag_bind(obj1, '<Leave>', onObjectClick2)        
canv.pack()

root.mainloop()

I am new in Tkinter. Thanks!

标签: pythonpython-3.xuser-interfacetkintertkinter-canvas

解决方案


我想我明白你想做什么,但有两件事你做错了。第一个与有关。如果您在函数内定义一个局部变量来保留您的图像对象,则在离开函数时您将失去对它的跟踪。第二个是您在旧对象上创建新对象,然后您将永远无法再次“输入”该对象。您可以使用Canvas.itemconfig()来更改项目图像,但要小心,因为这样做会丢失项目绑定,因此您需要再次执行此操作。试试这个,看看它是否是你所期望的:

from tkinter import * 

def onObjectClick1(event):
    print("1")
    canv.itemconfig(obj1, image=my_pic2)
    canv.tag_bind(obj1, '<Leave>', onObjectClick2)     

def onObjectClick2(event):
    print("2")
    canv.itemconfig(obj1, image=my_pic1)
    canv.tag_bind(obj1, '<Enter>', onObjectClick1)        
    
root = Tk()    
canv = Canvas(root, width=300, height=300)
my_pic1 = PhotoImage(file="start000-before.png")
my_pic2 = PhotoImage(file="start000-after.png")

obj1 = canv.create_image(50,50,image=my_pic1, anchor=NW)
canv.tag_bind(obj1, '<Enter>', onObjectClick1)        
canv.tag_bind(obj1, '<Leave>', onObjectClick2)        
canv.pack()

root.mainloop()

推荐阅读