python - 如何使用滑块小部件的值?
问题描述
我想使用 matplotlib 滑块小部件让用户选择一个值。我想添加一个按钮,用户完成后可以单击该按钮。这个按钮只是关闭 matplotlib 窗口。然后我想编写一个代码,在窗口关闭之前使用滑块值。我想出了以下脚本:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
#Create a slider
axcolor = 'lightgoldenrodyellow'
axg = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
gstart = 0
gend = 100
valinit = 50
valstep = 1
sg = Slider(axg, 'g', gstart, gend, valinit=valinit, valstep=valstep)
def update(event):
pass
sg.on_changed(update)
#Create quit button
quitax = plt.axes([0.8, 0.025, 0.1, 0.04])
quit_button = Button(quitax, 'Quit', color=axcolor, hovercolor='0.975')
def quit(event):
plt.close()
quit_button.on_clicked(quit)
while True:
if len(plt.get_fignums()) == 0:
break
#Here I planned to add code using the slider position before the user
#clicked on the quit button
g = sg.val
我希望底部的“while 循环”会暂停程序的执行,直到 matplotlib 窗口关闭。然后,一旦关闭,执行将继续,我将能够将滑块值用于我的目的。不幸的是,这不起作用。知道如何解决这个问题吗?
解决方案
我不知道为什么您的代码在我的系统上的行为与您的不同,但可能的解决方案是将滑块的更新值存储在全局变量中:
slider_value = valinit
def update(val):
global slider_value
slider_value = val
sg.on_changed(update)
推荐阅读
- python - SyntaxError:在 AOSP 代码中 repo init 的语法无效
- excel - 使用 VBA 从多个工作表中复制数据
- r - 如何为折线图手动添加图例
- laravel - Laravel 作曲家需要 laravel/ui^2.4 也不起作用。1.0 --dev 也不工作
- web-worker - 尝试将 libsodium 与 web worker 错误一起使用 TypeError: sodium.crypto_pwhash is not a function
- c++ - 使用带有 2d 向量的 push_back 时出现分段错误
- mysql - codeigniter 4 在选择查询中选择
- php - 我正在尝试使用 php 连接到我的数据库,我只是得到一个空白页
- azure-devops - 在 Azure Release Pipeline 中向特定用户进行身份验证
- spring - 在执行 job=[job] 时检测到重复的步骤 [step2]。如果任一步骤失败,都将在重新启动时再次执行