如何使用鼠标滚轮在 Tkinter 中滚动,如果它在滚动条所在的框架中?

我知道有.bind.bind_all方法,但是这两个都有问题。如果您使用.bind,它只会在您的光标位于该框架的空白处时滚动。如果您使用.bind_all, 鼠标所在的任何位置,如果您使用鼠标滚轮,它就会滚动。有没有办法只有当光标在某个帧中时才用鼠标滚轮滚动它?



慕的地10843
浏览 66回答 1
1回答

慕姐8265434

您可以使用<Enter>和<Leave>绑定该小部件来处理小部件何时应该滚动鼠标滚轮。通过仅当光标移动到该小部件上时使用bind_allwith<MouseWheel><Enter> sequence 可以使用序列检查bind 和 unbinding<MouseWheel>当光标从小部件移开时。看看这个例子。import tkinter as tkdef set_mousewheel(widget, command):&nbsp; &nbsp; """Activate / deactivate mousewheel scrolling when&nbsp;&nbsp; &nbsp; cursor is over / not over the widget respectively."""&nbsp; &nbsp; widget.bind("<Enter>", lambda _: widget.bind_all('<MouseWheel>', command))&nbsp; &nbsp; 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则当光标移到该可滚动框架内的小部件上时,滚动将不起作用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python