你可以在画布上做。在画布上放置标签并使用bind
函数Enter
和Leave
事件:
# imports
import tkinter as tk
# creating master
master = tk.Tk()
# hover functions
def motion_enter(event):
my_label.configure(fg='green')
print('mouse entered the canvas')
def motion_leave(event):
my_label.configure(fg='grey')
print('mouse left the canvas')
# create canvas, on which if you hover something happens
canvas = tk.Canvas(master, width=100, height=100, background='grey')
canvas.pack(expand=1, fill=tk.BOTH)
# create label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
# binding enter and leave functions
master.bind('<Enter>', motion_enter)
master.bind('<Leave>', motion_leave)
# set window size
master.geometry('400x200')
# start main loop
master.mainloop()
当您悬停画布或创建函数中的任何其他内容时,您可以更改任何对象的配置。玩弄对象和代码来做任何你想做的事。
同样正如提到的,您可以将标签或其他对象存储在列表或字典中以更改单独的对象,例如:
# imports
import tkinter as tk
# creating master
master = tk.Tk()
d = {}
# hover functions
def motion_enter(event):
d['first'].configure(fg='green')
print('mouse entered the canvas')
def motion_leave(event):
d['first'].configure(fg='grey')
print('mouse left the canvas')
# create canvas, on which if you hover something happens
canvas = tk.Canvas(master, width=100, height=100, background='grey')
canvas.pack(expand=1, fill=tk.BOTH)
# create label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
d['first'] = my_label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
d['second'] = my_label
# binding enter and leave functions
master.bind('<Enter>', motion_enter)
master.bind('<Leave>', motion_leave)
# set window size
master.geometry('400x200')
# start main loop
master.mainloop()
编辑 1
如果要在鼠标离开画布时删除标签,可以编写这样的函数:
def motion_enter(event):
d['first'].pack()
d['second'].pack()
print('mouse entered the canvas')
def motion_leave(event):
d['first'].pack_forget()
d['second'].pack_forget()
print('mouse left the canvas')
或者只是在前面添加 2 行来组合它们。