【Python】tkinter实现matplotlib绘制图形和多个组件一起的全窗口滚动并绑定鼠标滚轮进行滚动
import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
class ScrollableWindow(ttk.Frame):
def __init__(self, parent, fig):
super().__init__(parent)
self.canvas = FigureCanvasTkAgg(fig, self)
self.canvas.draw()
self.vscrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.canvas.get_tk_widget().yview)
self.canvas.get_tk_widget().configure(yscrollcommand=self.vscrollbar.set)
self.vscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.pack(fill=tk.BOTH, expand=True)
# 绑定鼠标滚轮事件
self.canvas.get_tk_widget().bind("<MouseWheel>", self.on_mousewheel)
def on_mousewheel(self, event):
# 鼠标滚轮事件处理
print("MouseWheel Event!")
if __name__ == "__main__":
root = tk.Tk()
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
x = np.linspace(0, 10, 1000)
y = np.sin(x)
ax.plot(x, y)
sw = ScrollableWindow(root, fig)
root.mainloop()
这段代码创建了一个可滚动的窗口,其中包含了matplotlib绘制的图形,并且实现了鼠标滚轮事件的绑定。窗口中的FigureCanvasTkAgg
被放置在一个ttk.Frame
中,并且配置了垂直滚动条。鼠标滚轮事件通过bind
方法绑定到了窗口的特定方法上,可以用于执行滚动时的特定操作。
评论已关闭