1 回答

TA贡献1813条经验 获得超2个赞
您可以使用<Enter>和<Leave>绑定该小部件来处理小部件何时应该滚动鼠标滚轮。
通过仅当光标移动到该小部件上时使用bind_allwith<MouseWheel><Enter> sequence 可以使用序列检查bind 和 unbinding<MouseWheel>当光标从小部件移开时。
看看这个例子。
import tkinter as tk
def set_mousewheel(widget, command):
"""Activate / deactivate mousewheel scrolling when
cursor is over / not over the widget respectively."""
widget.bind("<Enter>", lambda _: widget.bind_all('<MouseWheel>', command))
widget.bind("<Leave>", lambda _: widget.unbind_all('<MouseWheel>'))
root = tk.Tk()
root.geometry('300x300')
l0 = tk.Label(root, text='Hover and scroll on the labels.')
l0.pack(padx=10, pady=10)
l1 = tk.Label(root, text='0', bg='pink', width=10, height=5)
l1.pack(pady=10)
set_mousewheel(l1, lambda e: l1.config(text=e.delta))
l2 = tk.Label(root, text='0', bg='cyan', width=10, height=5)
l2.pack(pady=10)
set_mousewheel(l2, lambda e: l2.config(text=e.delta))
root.mainloop()
此示例适用于使用画布创建的可滚动框架,因为画布内的主框架有多个小部件,如果我们不使用bind_alloverbind则当光标移到该可滚动框架内的小部件上时,滚动将不起作用。
添加回答
举报