I am having problems using matplotlib and tkinter at the same time. I am trying to create a matplot graphic with radio buttons and embed it in tkinter Following some examples and documentation over the Internet, I have created the following code:
import random
import matplotlib
import tkinter as Tk
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
matplotlib.use('TkAgg')
root = Tk.Tk()
root.wm_title("Embedding in TK")
class TKInterGUI():
def __init__(self, master,fig):
self.fig = fig
self.master = master
def test(self):
canvas = FigureCanvasTkAgg(self.fig[0], self.master)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
ax = self.fig[0].add_axes([0.10, 0.7, 0.15, 0.15],facecolor='yellow')
r = RadioButtons(ax, ('2 Hz', '4 Hz', '0 Hz'))
fig = []
fig.append(plt.Figure(figsize=(5,5), dpi=100))
my_gui = TKInterGUI(root,fig)
my_gui.test()
Tk.mainloop()
This code generate the graphic and the radio buttons like intended. BUT the radio buttons do not work. They get completely irresponsive. Now if I change the radio Button code to the main program like the code bellow, it all works fine:
import random
import matplotlib
import tkinter as Tk
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
matplotlib.use('TkAgg')
root = Tk.Tk()
root.wm_title("Embedding in TK")
class TKInterGUI():
def __init__(self, master,fig):
self.fig = fig
self.master = master
def test(self):
canvas = FigureCanvasTkAgg(self.fig[0], self.master)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
fig = []
fig.append(plt.Figure(figsize=(5,5), dpi=100))
my_gui = TKInterGUI(root,fig)
my_gui.test()
ax = fig[0].add_axes([0.10, 0.7, 0.15, 0.15],facecolor='yellow')
r = RadioButtons(ax, ('2 Hz', '4 Hz', '0 Hz'))
Tk.mainloop()
Can anyone explain why the first code does not work, but the second one does?