gpt4 book ai didi

python - 适合多个文本框的提交功能

转载 作者:行者123 更新时间:2023-12-02 03:44:08 28 4
gpt4 key购买 nike

我正在制作一个 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 功能困住了。我想要一个函数来识别哪个文本框提交和输入,并在输入有效且在数据范围内的条件下设置适当的最小值或最大值。
谁能帮帮我吗?

最佳答案

为了通过文本框输入更新限制,您可以将一些参数与值一起传递给函数。实现此目的的一种方法是创建一个 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 个文本框中收集值并同时设置限制。

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()

关于python - 适合多个文本框的提交功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47354800/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com