在 Python 的 streamlit 中单击按钮两次时小部件消失 [重复]

问题描述 投票:0回答:1

我想要达到的目标

仅当在流光中单击按钮时才显示小部件。耗时操作的返回值将加载到小部件。在操作完成时,该按钮被禁用。每次单击按钮时,操作的新值都会加载到它。

问题

单击一次按钮时,将显示小部件。但是,当再次单击该按钮时,它会消失。看起来整个网页都被重置了。再次单击该按钮时,将再次显示小部件。系列活动循环进行。

环境

  • Windows 8.1
  • Python 3.9.13
  • streamlit 1.20.0

最小的可复制示例

import streamlit as st
import streamlit.components.v1 as stc

def very_heavy_operation():
    return 'result'

def main():
    process_btn_ph = st.empty()
    process_btn = process_btn_ph.button('process', disabled=False, key='1')
    text_wait = st.empty()

    print(process_btn) # for debug
    if process_btn:
        process_btn_ph.button('process', disabled=True, key='2')
        text_wait.markdown('**processing...**')
        result = very_heavy_operation()

        stc.html(f'<div>{result}</div>', height=100, scrolling=True)

        process_btn_ph.button('process', disabled=False, key='3')
        text_wait.empty()
        
if __name__ == '__main__':
    main()

我试过的

我用谷歌搜索“streamlit button placeholder push twice reset”但是没有找到有用的信息。

当按钮被点击一次时,

print(process_btn) # for debug
产生
True
。但是当再次点击它时,它会产生
False
。如果
process_btn_ph.button()
中的两个
if process_btn:
被删除,代码将按我想要的方式工作。我相信
process_btn_ph.button()
做错了什么,但我不知道如何解决它。

非常感谢任何建议。提前致谢。

python html button widget streamlit
1个回答
0
投票

Jamiu S. 建议的帖子回答了我的问题。非常感谢!
st.file_uploader 返回 None

import streamlit as st
import streamlit.components.v1 as stc

import random

def very_heavy_operation():
    return str(random.randint(0, 10))

def main():
    process_btn_ph = st.empty()
    process_btn = process_btn_ph.button('process', disabled=False, key='1')
    text_wait = st.empty()

    print(process_btn) # for debug

    if 'process_btn_state' not in st.session_state:
        st.session_state.process_btn_state = False

    if process_btn or st.session_state.process_btn_state:
        st.session_state.process_btn_state = True

        process_btn_ph.button('process', disabled=True, key='2')
        text_wait.markdown('**processing...**')
        result = very_heavy_operation()

        stc.html(f'<div>{result}</div>', height=100, scrolling=True)

        process_btn_ph.button('process', disabled=False, key='3')
        text_wait.empty()

if __name__ == '__main__':
    main()
© www.soinside.com 2019 - 2024. All rights reserved.