我正在学习如何使用matplotlib,现在我遇到了问题。当我在“tkinter项目”中创建Figure
并给它一个子图时,我使用NavigationToolbar2TkAgg
创建一个工具栏。此工具栏显示在图表的顶部。如何将其设置为其他位置,如底部或左侧?
这是代码:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
root = tk.Tk()
root.title("I am a newbie!")
# create the figure instances
fig = Figure()
a = fig.add_subplot(122)
b = fig.add_subplot(121)
# figure1 has two subplot and figure 2 has only one
fig2 = Figure(figsize=(2, 2))
c = fig2.add_subplot(111)
# create canvas1
canvas = FigureCanvasTkAgg(fig, root)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.X)
# put this to the top of the window
# toolbar for canvas1 (figure1)
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
# create canvas2
canvas2 = FigureCanvasTkAgg(fig2, root)
canvas2.show()
canvas2.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.X)
# put this to the bottom
# toolbar for canvas2 (figure2)
toolbar2 = NavigationToolbar2TkAgg(canvas2, root)
toolbar2.update()
# this function just to exit
def _quit():
root.quit()
root.destroy()
button = tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=tk.BOTTOM)
root.mainloop()
这是出现的窗口:
我想学习如何设置位置。
答案 0 :(得分:2)
实例化
NavigationToolbar2TkAgg
时
toolbar = NavigationToolbar2TkAgg(canvas, window)
调用方法NavigationToolbar2TkAgg._init_toolbar
。它将window
设置为父窗口小部件,并在方法的末尾调用self.pack(side=Tk.BOTTOM, fill=Tk.X)
。这会影响工具栏在window
内的放置方式。
通过为工具栏创建tk.Frame
小部件,可以更改工具栏的位置。
frame1 = tk.Frame(root)
frame2 = tk.Frame(root)
canvas = FigureCanvasTkAgg(fig, root)
toolbar = NavigationToolbar2TkAgg(canvas, frame1)
canvas2 = FigureCanvasTkAgg(fig2, root)
toolbar2 = NavigationToolbar2TkAgg(canvas2, frame2)
frame1.pack(side=tk.TOP, fill=tk.X)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.X)
frame2.pack(side=tk.TOP, fill=tk.X)
canvas2.get_tk_widget().pack(side=tk.TOP, fill=tk.X)
button = tk.Button(master=root, text='Quit')
button.pack(side=tk.TOP)
由于工具栏现在放在框架内,因此第二个工具栏的pack()
调用不会影响退出按钮。
有问题的方法:github。