В примере на matplotlib в качестве менеджера геометрии используется pack. Я хочу использовать сетку вместо. Поэтому я немного изменил пример, но он не работает:
from tkinter import *
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 = 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().grid(row = 0, column = 0)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().grid(row = 1, column = 1)
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 = Button(master=root, text="Quit", command=_quit)
button.grid(row = 2, column = 3)
mainloop()
Если я пытаюсь выполнить этот код, я получаю следующую ошибку:
---------------------------------------------------------------------------
TclError Traceback (most recent call last)
<ipython-input-3-32ca748b44c3> in <module>
21 canvas.get_tk_widget().grid(row = 0, column = 0)
22
---> 23 toolbar = NavigationToolbar2Tk(canvas, root)
24 toolbar.update()
25 canvas.get_tk_widget().grid(row = 1, column = 1)
~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/_backend_tk.py in __init__(self, canvas, window)
591 # so that Tool implementations can reuse the methods.
592 self.window = window
--> 593 NavigationToolbar2.__init__(self, canvas)
594
595 def destroy(self, *args):
~/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in __init__(self, canvas)
2625 # This cursor will be set after the initial draw.
2626 self._lastCursor = cursors.POINTER
-> 2627 self._init_toolbar()
2628 self._idDrag = self.canvas.mpl_connect(
2629 'motion_notify_event', self.mouse_move)
~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/_backend_tk.py in _init_toolbar(self)
657 self._message_label = tk.Label(master=self, textvariable=self.message)
658 self._message_label.pack(side=tk.RIGHT)
--> 659 self.pack(side=tk.BOTTOM, fill=tk.X)
660
661 def configure_subplots(self):
~/anaconda3/lib/python3.7/tkinter/__init__.py in pack_configure(self, cnf, **kw)
2141 self.tk.call(
2142 ('pack', 'configure', self._w)
-> 2143 + self._options(cnf, kw))
2144 pack = configure = config = pack_configure
2145 def pack_forget(self):
TclError: cannot use geometry manager pack inside . which already has slaves managed by grid
Я заменил пакет на сетку в коде, но ошибка говорит, что я все еще использую пакет. Кто-нибудь знает, как это исправить?