从Python中的matplotlib按钮调用函数



我想通过按下matplotlib按钮来调用一个函数。

现在,以下方法有效:

  1. 运行脚本
  2. 按下图表窗口中的开始按钮=>cond=真
  3. 通过键入:plot_data((在控制台中执行函数

代码看起来与此类似,

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
#---Create BUTTON---
axButton1 = plt.axes([0.1,0.05,0.05,0.05]) #left,bottom, width, height
btn1 = Button(axButton1,"Start")
def start(event):
global cond
cond = True
print(cond)
btn1.on_clicked(start)
#---Setting empty list---
t = np.array([0])
data = np.array([0])
cond = False
#---Plotting REAL TIME data---
def plot_data():
global cond, t, data
if (cond == True):
#SOMETHING WILL BE EXECUTED

但是,我希望在按下启动按钮时执行该功能,而不是单独将命令再次写入控制台。我试着调用函数";plot_data(("从访问启动按钮的功能,

def start(event):
global cond
cond = True
print(cond)
plot_data()
btn1.on_clicked(start)

然而,这并不奏效。知道我可以试试什么吗?

以下可以是您的解决方案

import matplotlib.pylab as plt
from matplotlib.widgets import Button
fig, ax = plt.subplots()
x = [i for i in range(10)]
y = [i for i in range(10)]
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'PLOT')
(xm, ym), (xM, yM) = bnext.label.clipbox.get_points()

def on_button_clicked(event):
global x,y
ax.plot(x,y)
print(event)

bnext.on_clicked(on_button_clicked)
plt.show()

将上面的代码粘贴到main.py中,然后运行python main.py

如果您正在使用JUPYTER笔记本,请使用以下

%matplotlib inline
from matplotlib.pyplot import *
import ipywidgets
button = ipywidgets.Button(description="Plot")
out = ipywidgets.Output()
x = [i for i in range(10)]
y = [i for i in range(10)]
def on_button_clicked(b):
with out:
plot(x,y)
show()
button.on_click(on_button_clicked)
display(button)
out

最新更新