55

我有这个可滚动的框架(实际上是画布内的框架)。

import Tkinter as tk
class Scrollbarframe():
    def __init__(self, parent,xsize,ysize,xcod,ycod):
        def ScrollAll(event):
                canvas1.configure(scrollregion=canvas1.bbox("all"),width=xsize,height=ysize,bg='white')
        self.parent=parent
        self.frame1=tk.Frame(parent,bg='white')
        self.frame1.place(x=xcod,y=ycod)
        canvas1=tk.Canvas(self.frame1)
        self.frame2=tk.Frame(canvas1,bg='white',relief='groove',bd=1,width=1230,height=430)
        scrollbar1=tk.Scrollbar(self.frame1,orient="vertical",command=canvas1.yview)
        canvas1.configure(yscrollcommand=scrollbar1.set)
        scrollbar1.pack(side="right",fill="y")
        canvas1.pack(side="left")
        canvas1.create_window((0,0),window=self.frame2,anchor='nw')
        self.frame2.bind("<Configure>",ScrollAll)

我想将鼠标滚轮绑定到滚动条,以便用户可以向下滚动框架,而无需使用滚动条上的箭头按钮。环顾四周后,我为我的canvas1like添加了一个绑定

self.frame1.bind("<MouseWheel>", self.OnMouseWheel)

这是功能:

def OnMouseWheel(self,event):
    self.scrollbar1.yview("scroll",event.delta,"units")
    return "break" 

但是当我使用鼠标滚轮时滚动条不会移动。谁能帮我这个?我想要的是当用户使用鼠标滚轮(在框架区域内/滚动条上)时,画布应该自动向上或向下滚动。

4

6 回答 6

95

也许最简单的解决方案是为鼠标滚轮进行全局绑定。然后,无论鼠标下是什么小部件或哪个小部件具有键盘焦点,它都会触发。然后,您可以无条件地滚动画布,或者您可以聪明地找出应该滚动的窗口。

例如,在 Windows 上,您将执行以下操作:

self.canvas = Canvas(...)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
...
def _on_mousewheel(self, event):
    self.canvas.yview_scroll(-1*(event.delta/120), "units")

请注意,self.canvas.bind_all这有点误导-您更正确地应该调用root.bind_all,但我不知道您定义什么或如何定义根窗口。无论如何,这两个电话是同义词。

平台差异:

  • 在 Windows 上,您绑定到<MouseWheel>并且需要除以event.delta120(或其他一些因素,具体取决于您希望滚动的速度)
  • 在 OSX 上,您绑定到<MouseWheel>并且需要event.delta不加修改地使用
  • 在 X11 系统上,您需要绑定到<Button-4>and <Button-5>,并且您需要除以event.delta120(或其他一些因素,具体取决于您想要滚动的速度)

还有更精细的解决方案涉及虚拟事件并确定哪个窗口具有焦点或在鼠标下方,或者通过绑定传递画布窗口引用,但希望这能让您入门。

于 2013-07-03T20:47:43.313 回答
45

根据@BryanOakley 的回答,这是一种仅滚动焦点小部件(即当前鼠标光标位于其上的小部件)的方法。

绑定到位于画布内的可滚动框架上发生的事件,方式如下(<Enter>是画布内的框架):<Leave>scrollframe

    ...

    self.scrollframe.bind('<Enter>', self._bound_to_mousewheel)
    self.scrollframe.bind('<Leave>', self._unbound_to_mousewheel)

    return None

def _bound_to_mousewheel(self, event):
    self.canv.bind_all("<MouseWheel>", self._on_mousewheel)

def _unbound_to_mousewheel(self, event):
    self.canv.unbind_all("<MouseWheel>")

def _on_mousewheel(self, event):
    self.canv.yview_scroll(int(-1*(event.delta/120)), "units")
于 2016-06-16T11:50:42.800 回答
14

此链接为您提供了如何使用滚轮的示例。

http://www.daniweb.com/software-development/python/code/217059/using-the-mouse-wheel-with-tkinter-python

我希望这有帮助!

# explore the mouse wheel with the Tkinter GUI toolkit
# Windows and Linux generate different events
# tested with Python25
import Tkinter as tk
def mouse_wheel(event):
    global count
    # respond to Linux or Windows wheel event
    if event.num == 5 or event.delta == -120:
        count -= 1
    if event.num == 4 or event.delta == 120:
        count += 1
    label['text'] = count
count = 0
root = tk.Tk()
root.title('turn mouse wheel')
root['bg'] = 'darkgreen'
# with Windows OS
root.bind("<MouseWheel>", mouse_wheel)
# with Linux OS
root.bind("<Button-4>", mouse_wheel)
root.bind("<Button-5>", mouse_wheel)
label = tk.Label(root, font=('courier', 18, 'bold'), width=10)
label.pack(padx=40, pady=40)
root.mainloop()
于 2013-07-03T15:35:14.587 回答
12

为了摆脱奇怪的因子 120,我们可以只看 event.delta 值的符号。这使得在 Windows、Linux 和 Mac OS 下使用相同的处理程序变得很容易。

# Mouse wheel handler for Mac, Windows and Linux
# Windows, Mac: Binding to <MouseWheel> is being used
# Linux: Binding to <Button-4> and <Button-5> is being used

def MouseWheelHandler(event):
    global count

    def delta(event):
        if event.num == 5 or event.delta < 0:
            return -1 
        return 1 

    count += delta(event)
    print(count)

import tkinter
root = tkinter.Tk()
count = 0
root.bind("<MouseWheel>",MouseWheelHandler)
root.bind("<Button-4>",MouseWheelHandler)
root.bind("<Button-5>",MouseWheelHandler)
root.mainloop()
于 2017-01-06T12:38:27.990 回答
2

如果你有兴趣

如何同时滚动 2 个列表框

#listbox scrollbar

from tkinter import *
root = Tk()

def scrolllistbox2(event):
    listbox2.yview_scroll(int(-1*(event.delta/120)), "units")


scrollbar = Scrollbar(root)
#scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(root)
listbox.pack()
for i in range(100):
    listbox.insert(END, i)
# attach listbox to scrollbar
listbox.config(yscrollcommand=scrollbar.set)
listbox.bind("<MouseWheel>", scrolllistbox2)

listbox2 = Listbox(root)
listbox2.pack()
for i in range(100):
    listbox2.insert(END, i+100)
listbox2.config(yscrollcommand=scrollbar.set)

#scrollbar.config(command=listbox.yview)

root.mainloop()

或者...

from tkinter import *
root = Tk()
root.geometry("400x400")
def scrolllistbox(event):
    ''' scrolling both listbox '''
    listbox2.yview_scroll(int(-1*(event.delta/120)), "units")
    listbox1.yview_scroll(int(-1*(event.delta/120)), "units")


def random_insert():
    ''' adding some numbers to the listboxes '''
    for i in range(100):
        listbox1.insert(END, i)
        listbox2.insert(END, i + 100)

# SCROLLBAR
scrollbar = Scrollbar(root)
#scrollbar.pack(side=RIGHT, fill=Y)

# LISTBOX 1
listbox1 = Listbox(root)
listbox1.pack()
# attach listbox to scrollbar with yscrollcommand
# listbox1.config(yscrollcommand=scrollbar.set)

# The second one
listbox2 = Listbox(root)
listbox2.pack()
listbox2.config(yscrollcommand=scrollbar.set)
# scroll the first one when you're on the second one
# listbox2.bind("<MouseWheel>", scrolllistbox)
root.bind("<MouseWheel>", scrolllistbox)

# scroll also the second list when you're on the first
listbox1.bind("<MouseWheel>", scrolllistbox)

random_insert()
#scrollbar.config(command=listbox.yview)

root.mainloop()
于 2019-08-19T07:56:03.067 回答
1

作为上述的补充,“delta”比例因子很容易计算,因为平台信息可通过sysandplatform模块(可能还有其他模块)获得。

def my_mousewheel_handler(event):
    if sys.platform == 'darwin': # for OS X # also, if platform.system() == 'Darwin':
        delta = event.delta
    else:                            # for Windows, Linux
        delta = event.delta // 120   # event.delta is some multiple of 120
    if event.widget in (widget1, widget2, ):
        'do some really cool stuff...'
于 2020-12-19T14:24:11.377 回答