I'm using a matplotlib button to create another plot with a button. However, the second button in the second plot does not work. Could anyone take a look at my code and give me some help?
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import tkinter as tk
from matplotlib.widgets import Button
def next1(event):
print("you clicked here")
def next0(event):
# plt.close('all')
fig, ax = plt.subplots()
rects = ax.bar(range(10), 20*np.random.rand(10))
axnext1 = plt.axes([0.11, 0.05, 0.05, 0.0375])
bnext1 = Button(axnext1, 'Next2')
print(bnext1.label)
bnext1.on_clicked(next1)
plt.show()
fig, ax = plt.subplots()
rects = ax.bar(range(10), 20*np.random.rand(10))
axnext0 = plt.axes([0.11, 0.05, 0.05, 0.0375])
bnext0 = Button(axnext0, 'Next1')
print(bnext0.label)
bnext0.on_clicked(next0)
plt.show()
CodePudding user response:
It seems problem is because you assign second button to local variable (inside function) and python deletes this object when it finishes function. Button has to be assigned to global variable - to keep it after finishing function.
def next0(event):
global bnext1
# ... code ...
BTW:
After clicking first button it shows me information (not erorr message)
QCoreApplication::exec: The event loop is already running
because second window tries to create new event loop
but event loop
already exists - created by first window.
To resolve this problem you can run second window in non-blocking mode.
def next0(event):
global bnext1
# ... code ...
plt.show(block=False)