第1个回答 2023-07-28
使用`bind()`方法来绑定鼠标事件,然后在事件处理函数中通过计数器来实现不同次数的效果:
import tkinter as tk
def on_hover(event):
global hover_count
hover_count += 1
if hover_count == 1:
button.place(x=100, y=100)
button.configure(text="第一次悬停")
elif hover_count == 2:
button.place(x=200, y=200)
button.configure(text="第二次悬停")
hover_count = 0
root = tk.Tk()
root.geometry("400x300")
button = tk.Button(root, text="悬停按钮")
button.place(x=50, y=50)
button.bind('<Enter>', on_hover)
root.mainloop()
首先创建了一个全局变量`hover_count`来记录鼠标悬停的次数。然后通过`button.bind('<Enter>', on_hover)`语句将鼠标的悬停事件与`on_hover`函数绑定。在`on_hover`函数中,每次鼠标悬停都会将`hover_count`加1,并根据悬停次数设置按钮的位置和文本。当悬停次数为1时,按钮移动到(100, 100)的位置,并将文本设置为"第一次悬停";当悬停次数为2时,按钮移动到(200, 200)的位置,并将文本设置为"第二次悬停"。本回答被提问者采纳