适用于多个文本框的提交功能

时间:2017-11-17 16:08:15

标签: python matplotlib textbox

我正在创建一个Matplotlib GUI,我希望以交互方式重新缩放x和y轴。为此,我想使用四个文本框,我可以分别设置x和y轴限制的最小值和最大值。我到目前为止的代码是:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import TextBox
import matplotlib.gridspec as gridspec

fig, ax = plt.subplots()
ax.plot([1,3,2])

fig.subplots_adjust(bottom=0.4)
gs = gridspec.GridSpec(2,2)
gs.update(left=0.4, right=0.7, bottom=0.15, top=0.25, hspace=0.1)

axes = [fig.add_subplot(gs[i,j]) for i,j in [[0,0],[0,1],[1,0],[1,1]]]
# create the textboxes
tb_xmin = TextBox(axes[0],'x', hovercolor='0.975', label_pad=0.1)
tb_xmax = TextBox(axes[1],'',  hovercolor='0.975')
tb_ymin = TextBox(axes[2],'y', hovercolor='0.975', label_pad=0.1)
tb_ymax = TextBox(axes[3],'',  hovercolor='0.975')

def submit(val):
    data = eval(val)
    # how to know which limit to set here?
    ax.set_xlim(data)
    plt.draw()

for tb in [tb_xmin,tb_xmax,tb_ymin,tb_ymax]:
    tb.on_submit(submit)
plt.show()

enter image description here

但是我坚持使用submit功能。我希望有一个功能,可以识别哪个文本框提交和输入,并在输入有效和数据范围内设置适当的最小值或最大值。
任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

为了通过TextBox输入更新限制,您可以将一些参数与值一起传递给函数。一种方法是创建一个lambda函数,该函数预设了这些参数,具体取决于要更新的​​限制。

def submit(val,func,pos):
    data = float(val)    
    func([data,None][::pos])

tb_xmin.on_submit(lambda val: submit(val, ax.set_xlim, 1))
tb_xmax.on_submit(lambda val: submit(val, ax.set_xlim, -1))
tb_ymin.on_submit(lambda val: submit(val, ax.set_ylim, 1))
tb_ymax.on_submit(lambda val: submit(val, ax.set_ylim, -1))

另一种选择是始终在提交时调用相同的函数,让函数从所有4个TextBox中收集值并同时设置限制。

import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox
import matplotlib.gridspec as gridspec

fig, ax = plt.subplots()
ax.plot([1,3,2])

fig.subplots_adjust(bottom=0.4)
gs = gridspec.GridSpec(2,2)
gs.update(left=0.4, right=0.7, bottom=0.15, top=0.25, hspace=0.1)

axes = [fig.add_subplot(gs[i,j]) for i,j in [[0,0],[0,1],[1,0],[1,1]]]
# create the textboxes
xlim = ax.get_xlim()
ylim = ax.get_ylim()
tb_xmin = TextBox(axes[0],'x', initial = str(xlim[0]), hovercolor='0.975', label_pad=0.1)
tb_xmax = TextBox(axes[1],'',  initial = str(xlim[1]), hovercolor='0.975')
tb_ymin = TextBox(axes[2],'y', initial = str(ylim[0]), hovercolor='0.975', label_pad=0.1)
tb_ymax = TextBox(axes[3],'',  initial = str(ylim[1]), hovercolor='0.975')

def submit(val):
    lim = [float(tb.text) for tb in [tb_xmin,tb_xmax,tb_ymin,tb_ymax]]
    ax.axis(lim)
    fig.canvas.draw_idle()

for tb in [tb_xmin,tb_xmax,tb_ymin,tb_ymax]:
    tb.on_submit(submit)
plt.show()