TK 怎么让滚轮让鼠标点击滑动
时间: 2023-10-01 10:09:51 浏览: 58
你可以使用Tkinter中的Canvas小部件来实现此功能。以下是一个示例代码:
```python
import tkinter as tk
class ScrollableCanvas(tk.Frame):
def __init__(self, parent, **kwargs):
tk.Frame.__init__(self, parent, **kwargs)
# 创建滚动条
self.v_scroll = tk.Scrollbar(self, orient=tk.VERTICAL)
self.v_scroll.pack(side=tk.RIGHT, fill=tk.Y)
# 创建画布
self.canvas = tk.Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.v_scroll.set)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# 绑定滚轮事件
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
# 配置滚动条
self.v_scroll.config(command=self.canvas.yview)
# 创建画布内部的框架
self.inner_frame = tk.Frame(self.canvas)
self.canvas.create_window((0, 0), window=self.inner_frame, anchor="nw")
# 配置画布内部的框架自适应大小
self.inner_frame.bind("<Configure>", self._on_inner_frame_configure)
def _on_mousewheel(self, event):
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
def _on_inner_frame_configure(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
# 使用示例
root = tk.Tk()
root.geometry("200x200")
scrollable_canvas = ScrollableCanvas(root)
scrollable_canvas.pack(fill=tk.BOTH, expand=True)
for i in range(50):
tk.Label(scrollable_canvas.inner_frame, text=f"Label {i}").pack()
root.mainloop()
```
这个示例代码中,我们创建了一个名为`ScrollableCanvas`的小部件,它是一个具有滚动条的画布。我们在画布上绑定了滚轮事件,以便用户可以使用鼠标滚轮来滚动画布。
阅读全文