在 Tkinter 中垂直滚动多个绘图

问题描述 投票:0回答:1

我想用 Matplotlib 绘制多个图,将它们添加到 Tkinter 框架中(将它们一个接一个地堆叠),并能够在图之间垂直滚动。 每个图应填充 x 方向,并具有最小 y 高度,因此,如果多个图的总高度高于窗口的高度,则应启用滚动。

我找到了一种滚动单个大图形(由多个子图组成)的方法,但我被迫使用无法生成子图的库,所以我的想法是将单个图一个一个地堆叠在另一个图下面,将它们视为 Tkinter小部件。

到目前为止,我有以下内容,但正如您所看到的,滚动条存在但不起作用。 任何见解都会有用。

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

from matplotlib.figure import Figure

f = Figure()
a = f.add_subplot(111)

g = Figure()
b = g.add_subplot(111)

from tkinter import *
root=Tk()
frame=Frame(root)
frame.pack(expand=True, fill=BOTH)
canvas=Canvas(frame,bg='#FFFFFF',scrollregion=(0,0,500,500))
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
vbar.config(command=canvas.yview)
canvas.config()
canvas.config(yscrollcommand=vbar.set)
canvas.pack(side=LEFT,expand=True,fill=BOTH)

middle = Frame(canvas, bg="yellow")
middle.pack(side="bottom", expand=True, fill="both")

canvas_1 = FigureCanvasTkAgg(f, middle)
canvas_1.get_tk_widget().pack(expand=True, fill="both")
canvas_1.draw()

bottom = Frame(canvas, bg="blue")
bottom.pack(side="bottom", expand=True, fill="both")

canvas_2 = FigureCanvasTkAgg(g, bottom)
canvas_2.get_tk_widget().pack(expand=True, fill="both")
canvas_2.draw()

root.mainloop()

产生:

enter image description here

enter image description here

python matplotlib tkinter
1个回答
0
投票

使用

middle.pack()
放置框架
middle
(与框架
bottom
相同)不会激活滚动条。

您需要使用

middle
将框架
canvas.create_window()
放入画布中,并将两个图放入框架
middle
中(因此可以删除框架
bottom
)。

以下是修改后的代码:

from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

f = Figure()
a = f.add_subplot(111)

g = Figure()
b = g.add_subplot(111)

root = Tk()

frame = Frame(root)
frame.pack(expand=True, fill=BOTH)

canvas = Canvas(frame, bg='#FFFFFF', width=700, height=700,
                highlightthickness=0)

vbar = Scrollbar(frame, orient=VERTICAL, command=canvas.yview)
vbar.pack(side=RIGHT, fill=Y)

canvas.config(yscrollcommand=vbar.set)
canvas.pack(side=LEFT, expand=True, fill=BOTH)

middle = Frame(canvas, bg="yellow")
# put the frame using .create_window()
canvas.create_window(0, 0, window=middle, anchor='nw')

# put the two plots into same frame "middle"
canvas_1 = FigureCanvasTkAgg(f, middle)
canvas_1.get_tk_widget().pack(expand=True, fill=BOTH)
canvas_1.draw()

canvas_2 = FigureCanvasTkAgg(g, middle)
canvas_2.get_tk_widget().pack(expand=True, fill=BOTH)
canvas_2.draw()

# update canvas scrollregion option whenever the frame is resized
middle.bind(
    '<Configure>',
    lambda e: canvas.config(scrollregion=canvas.bbox('all'))
)

root.mainloop()

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.