【问题标题】:"Mouse over" event in tkintertkinter 中的“鼠标悬停”事件
【发布时间】:2020-05-25 20:45:53
【问题描述】:

我正在尝试制作一个 python 脚本,如果您将鼠标放在 tkinter 中的某个元素上会发生某些事情。我知道我可以创建一个通过 after 重复的函数并创建一个 if statement 但我认为那里可能是一种更简单的方法。 HTML 中的onmouseover 事件就是我想要的一个例子。 提前致谢! 我的代码:

from tkinter import Tk, Canvas, PhotoImage
root=Tk()
c=Canvas(root, width=500, height=500) # width and height are placeholders here
root.title("wdihihfwaheuih") # the title too
imag = PhotoImage(file="example.pgm")
image = c.create_image(250, 250, anchor="c", image=imag) # <-- element i want to "onmouseover"
root.mainloop()

【问题讨论】:

标签: python tkinter mouseevent


【解决方案1】:

这里是做什么:

#Create element called 'elem'

#Binding hovers
def on_start_hover():
    #What you do when the mouse hovers

def on_end_hover():
    #What to do when the mouse stops hovering

elem.bind('<Enter>', on_start_hover)
elem.bind('<Leave>', on_end_hover)

【讨论】:

  • “elem”是什么类型,是 PhotoImage 吗?我收到一个错误: Traceback(最近一次调用最后一次):文件“main.py”,第 45 行,在 game = Main() 文件“main.py”,第 22 行,在 init self.camicon.bind("") AttributeError: 'int' 对象没有属性 'bind'
  • "elem" 必须是 Tkinter 小部件,您可以将 Photoimage 放在标签或按钮上,然后绑定。
猜你喜欢
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2020-06-25
  • 2011-11-09
  • 2011-08-17
  • 1970-01-01
  • 2012-10-12
相关资源
最近更新 更多