python - 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!
解决方案
我想我明白你想做什么,但有两件事你做错了。第一个与此有关。如果您在函数内定义一个局部变量来保留您的图像对象,则在离开函数时您将失去对它的跟踪。第二个是您在旧对象上创建新对象,然后您将永远无法再次“输入”该对象。您可以使用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()
推荐阅读
- php - 尝试访问 null 类型值的数组偏移量,但找不到正确的解决方案
- javascript - react native:如何制作在按下复选框时会选中复选框的文本标签?
- javascript - 我正在尝试为 React 应用程序设置 SSL Pinning
- spring-boot-test - 春季启动 2.3 @MockBean
- rabbitmq - 无法使用 brew 服务启动 RabbitMQ
- reactjs - 如何将服务与组件分离
- php - 如何隐藏不同语言的未分类
- sql - 此查询如何正确编写?
- linux - .htaccess 在不应该时将子域重定向到顶级域
- excel - 如何私下分发 excel office 插件(w/office.js)?