我使用matplotlib和tk/tkinter,下面是"嵌入传统知识“
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':
如何删除工具栏按钮?
发布于 2019-12-03 11:46:04
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.
https://stackoverflow.com/questions/59155873
复制相似问题