0

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?

2
  • Don't have time to look at this in detail, but I guess, that matplotlib and tkinter both require their own main loop. Probably you execute either the mainloop of tkinter ot the one of matplotlib.thus there's always one part of the GUI that will not be repsonsive. Perhaps you can run the mainloop of matplotlib in a separate thread. Commented Jun 14, 2020 at 22:53
  • 2
    Short answer is your RadioButtons is just a local variable and got GCed. Store it as a class attribute, i.e. self.r = RadioButtons(ax, ('2 Hz', '4 Hz', '0 Hz')). Commented Jun 15, 2020 at 2:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.