用于在画布上滚动的 Tkinter 鼠标滚轮操作

wal*_*xia 2 python scroll tkinter mousewheel

我是 Python 新手,在向画布添加鼠标滚动操作时遇到问题。我有一个垂直滚动条。当我手动滚动滚动条或将鼠标悬停在滚动条上并滚动鼠标滚轮时,滚动条工作正常。我的问题是,我希望能够在画布上滚动鼠标滚轮,甚至只是在框架上滚动,只要鼠标悬停在其上,其中的内容就会滚动。

我花了几个小时在 stackoverflow 上查看与此相关的所有类似问题,但我的修改似乎都不起作用。我目前遇到一个无法纠正的奇怪错误。由于我的修改,错误仅在我开始滚动时显示,但不会导致崩溃。错误是:

Exception in Tkinter callback
    Traceback (most recent call last):
        File "C:\Users\twaku\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
                return self.func(*args)
        File "C:/Users/twaku/PycharmProjects/DCSui/FileToSubmit.py", line 152, in _on_mousewheel
                self.canvas.yview_scroll(int(-1 * (event.delta / 120), "units"))
        TypeError: 'str' object cannot be interpreted as an integer
Run Code Online (Sandbox Code Playgroud)

现在,如果我删除int类型转换,我会收到此错误:

Exception in Tkinter callback
    Traceback (most recent call last):
        File "C:\Users\twaku\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
                return self.func(*args)
        File "C:/Users/twaku/PycharmProjects/DCSui/FileToSubmit.py", line 156, in _on_mousewheel
                self.canvas.yview_scroll(-1 * (event.delta / 120), "units")
        File "C:\Users\twaku\Anaconda3\lib\tkinter\__init__.py", line 1745, in yview_scroll
                self.tk.call(self._w, 'yview', 'scroll', number, what)
            _tkinter.TclError: expected integer but got "1.0"
Run Code Online (Sandbox Code Playgroud)

所以现在我在这两个错误之间来回徘徊。

这是我的代码:

Exception in Tkinter callback
    Traceback (most recent call last):
        File "C:\Users\twaku\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
                return self.func(*args)
        File "C:/Users/twaku/PycharmProjects/DCSui/FileToSubmit.py", line 152, in _on_mousewheel
                self.canvas.yview_scroll(int(-1 * (event.delta / 120), "units"))
        TypeError: 'str' object cannot be interpreted as an integer
Run Code Online (Sandbox Code Playgroud)

fig*_*eam 5

除法时,结果是浮点数。尝试使用整数除法:

def _on_mousewheel(self, event):
    self.canvas.yview_scroll(-1 * (event.delta // 120), "units")
                                        here:--^
Run Code Online (Sandbox Code Playgroud)

现在,您可能想要检查鼠标指针悬停在哪个小部件上方,因为_on_mousewheel()当鼠标指针悬停在滚动条上时会调用该函数,使其滚动速度提高两倍。