如何使用鼠标滚轮在 Tkinter 中滚动,如果它在滚动条所在的框架中?
How to use the mouse wheel to scroll in Tkinter, if it's in the frame the scrollbar is in?
我知道有.bind
和.bind_all
两种方法,但是这两种方法都有问题。如果您使用 .bind
,只有当您的光标位于该帧的空白 space 时,它才会滚动。如果你使用.bind_all
,你的鼠标在任何地方,如果你使用鼠标滚轮,它就会滚动。有没有办法只在光标在某一帧时才用鼠标滚轮滚动?
您可以使用该小部件的 <Enter>
和 <Leave>
绑定来处理该小部件何时应进行鼠标滚轮滚动。
仅当光标移到该小部件上时,才将 bind_all
与 <MouseWheel>
序列一起使用 可以使用 <Enter>
序列绑定进行检查并在光标离开小部件时取消绑定 <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()
此示例与使用 canvas 创建的 Scrollable 框架配合得很好,因为 canvas 中的主框架有多个小部件,如果我们不使用 bind_all
而不是 bind
如果光标移到可滚动框架内的小部件上,则滚动将不起作用。
我知道有.bind
和.bind_all
两种方法,但是这两种方法都有问题。如果您使用 .bind
,只有当您的光标位于该帧的空白 space 时,它才会滚动。如果你使用.bind_all
,你的鼠标在任何地方,如果你使用鼠标滚轮,它就会滚动。有没有办法只在光标在某一帧时才用鼠标滚轮滚动?
您可以使用该小部件的 <Enter>
和 <Leave>
绑定来处理该小部件何时应进行鼠标滚轮滚动。
仅当光标移到该小部件上时,才将 bind_all
与 <MouseWheel>
序列一起使用 可以使用 <Enter>
序列绑定进行检查并在光标离开小部件时取消绑定 <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()
此示例与使用 canvas 创建的 Scrollable 框架配合得很好,因为 canvas 中的主框架有多个小部件,如果我们不使用 bind_all
而不是 bind
如果光标移到可滚动框架内的小部件上,则滚动将不起作用。