首页 > 解决方案 > 如何使用滑块小部件的值?

问题描述

我想使用 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 窗口关闭。然后,一旦关闭,执行将继续,我将能够将滑块值用于我的目的。不幸的是,这不起作用。知道如何解决这个问题吗?

标签: pythonmatplotlibslider

解决方案


我不知道为什么您的代码在我的系统上的行为与您的不同,但可能的解决方案是将滑块的更新值存储在全局变量中:

slider_value = valinit

def update(val):
    global slider_value
    slider_value = val

sg.on_changed(update)

推荐阅读