我将tp / tkinter与matplotlib结合使用,遵循“ Embedding in Tk”
self._figure = Figure()
self._axes: matplotlib.axes.Axes = self._figure.add_subplot(111)
self._canvas = FigureCanvasTkAgg(self._figure, master=frame)
toolbar = NavigationToolbar2Tk(self._canvas, frame)
toolbar.update()
self._figure.canvas.manager.toolmanager.remove_tool("pan")
应该可以,但是不能。
# self._figure.canvas does not have attribute 'manager'
从vs代码的屏幕截图中可以看到,FigureCanvasTkAgg没有属性'manager':
如何删除工具栏按钮?
答案 0 :(得分:1)
似乎Canvas
中嵌入的NavigationToolbar2Tk
和tkinter
具有不同的结构和不同的功能。标准matplotlib
窗口使用Qt
作为后端。
toolbar = NavigationToolbar2Tk(self._canvas, frame)
列出有关按钮的信息
print(toolbar.toolitems)
要删除Pan
按钮-这是第四个按钮
toolbar.children['!button4'].pack_forget()
要将新功能分配给现有按钮-即Home
def my_function():
print("Pressed Home")
toolbar.children['!button1'].config(command=my_function)
添加新按钮
button = tkinter.Button(master=toolbar, text="Quit", command=_quit)
#button.pack()
button.pack(side="left")
以相同的方式添加其他tkinter
个小部件-Label
,Entry
等。
编辑:如评论中的ImportanceOfBeingErnest所述,它可以做得更优雅。
NavigationToolbar2Tk.toolitems = [t for t in NavigationToolbar2Tk.toolitems if
t[0] not in ('Pan',)]
完整的示例
import tkinter
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
# ---
NavigationToolbar2Tk.toolitems = [t for t in NavigationToolbar2Tk.toolitems if
t[0] not in ('Pan',)]
# ---
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
print(toolbar.toolitems)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
# closed with the window manager.