Skip to content

Commit 2c86b59

Browse files
committed
tkinter embed matplotlib toolbar removes buttons
1 parent 5e7d7a2 commit 2c86b59

File tree

1 file changed

+83
-0
lines changed
  • tkinter/embed-matplotlib/NavigationToolbar-remove-buttons-from-toolbar.itemtoolsitem

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#!/usr/bin/env python3
2+
3+
# date: 2019.12.03
4+
# https://stackoverflow.com/questions/59155873/how-to-remove-toolbar-button-from-navigationtoolbar2tk-figurecanvastkagg
5+
6+
import tkinter
7+
8+
from matplotlib.backends.backend_tkagg import (
9+
FigureCanvasTkAgg, NavigationToolbar2Tk)
10+
# Implement the default Matplotlib key bindings.
11+
from matplotlib.backend_bases import key_press_handler
12+
from matplotlib.figure import Figure
13+
14+
import numpy as np
15+
16+
17+
root = tkinter.Tk()
18+
root.wm_title("Embedding in Tk")
19+
20+
fig = Figure(figsize=(5, 4), dpi=100)
21+
t = np.arange(0, 3, .01)
22+
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
23+
24+
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
25+
canvas.draw()
26+
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
27+
28+
# ---
29+
30+
# remove button `Pan` from toolbar
31+
NavigationToolbar2Tk.toolitems = [t for t in NavigationToolbar2Tk.toolitems if
32+
t[0] not in ('Pan',)]
33+
34+
# ---
35+
36+
toolbar = NavigationToolbar2Tk(canvas, root)
37+
toolbar.update()
38+
39+
print(toolbar.toolitems)
40+
41+
# ---
42+
43+
44+
toolbar.children['!button4'].pack_forget()
45+
46+
# ---
47+
#To remove Pan button - it is 4th button
48+
49+
toolbar.children['!button4'].pack_forget()
50+
51+
#To assign new function to existing button - ie. Home
52+
53+
def my_function():
54+
print("Pressed Home")
55+
56+
toolbar.children['!button1'].config(command=my_function)
57+
58+
# ---
59+
60+
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
61+
62+
63+
def on_key_press(event):
64+
print("you pressed {}".format(event.key))
65+
key_press_handler(event, canvas, toolbar)
66+
67+
canvas.mpl_connect("key_press_event", on_key_press)
68+
69+
70+
def _quit():
71+
root.quit() # stops mainloop
72+
root.destroy() # this is necessary on Windows to prevent
73+
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
74+
75+
button = tkinter.Button(master=root, text="Quit", command=_quit)
76+
button.pack(side=tkinter.BOTTOM)
77+
78+
label = tkinter.Button(master=root, text="Label")
79+
label.pack(side=tkinter.BOTTOM)
80+
81+
tkinter.mainloop()
82+
# If you put root.destroy() here, it will cause an error if the window is
83+
# closed with the window manager.

0 commit comments

Comments
 (0)