无法获取在函数内初始化的小部件的值

2024-06-06 15:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它从ipywidgets生成一个下拉小部件,其中包含一个目录列表作为选项。我的问题是,如果我在函数外部实现了widget global,它将不会加载新列表来生成带有更改值的下拉列表。我的想法是写一个函数。每次都会重现下拉列表。不是很有效,但很有效。但现在我想观察一下,在一次改变后,他的价值会下降。问题是,observe将通过下拉调用另一个无法达到该值的函数。值,因为下拉小部件不是全局的。我能换什么?你知道吗

def path_output(d):
    clear_output()
    global lowest_dirs
    value=path_input.value
    if os.path.isfile(value) == True:
        html_ausgabe ="""<h1><center>%s</center></h1>""" % "-- This is a file! --" 
        display(HTML(html_ausgabe))
        welcome_msg() 
    elif os.path.isdir(value) == True:
        global lowest_dirs
        lowest_dir()
        header("test")
    else:
        msg = "-- \""+value+"\" is no directory --"
        html_ausgabe ="""<h1><center>%s</center></h1>""" % msg
        display(HTML(html_ausgabe))
        welcome_msg() 

def header(self):
    global dropdown_hd_value
    clear_output()
    #print(lowest_dirs)
    dropdown_hd=widgets.Dropdown(
        options=lowest_dirs, 
        value=None, 
        description='Path:', 
        disabled=False, 
        layout = Layout(display='center',align_items='center', width='80%')
    )
#     print(dropdown_hd.value)
    if dropdown_hd.value == None:
        msg = "-- Your are now in the \""+path_input.value+"\" directory sdfs--"
    else:
        msg = "-- Your are now in the \""+path_input.value+"asdsa"+"\" directory sdfs--"

    html_ausgabe ="""<h1><center>%s</center></h1>""" % msg
    display(HTML(html_ausgabe))
    display(HBox([dropdown_hd, button_reset]))

    dropdown_hd.observe(dropdown_hd_getvalue, 'value')
    dropdown_hd_value=dropdown_hd.value



def dropdown_hd_getvalue(b):
    clear_output()
    global dropdown_hd
    global dropdown_hd_value
    print(dropdown_hd.value)

你想要什么?我想得到一个下拉列表,可以通过读取目录的更改列表重建。你知道吗


Tags: path函数列表outputvaluehtmldisplaymsg