在Streamlit中使用Python选择任何小部件后如何停止重新加载页面

Posted

技术标签:

【中文标题】在Streamlit中使用Python选择任何小部件后如何停止重新加载页面【英文标题】:How to stop reloading the page after selecting any widget with Python in Streamlit 【发布时间】:2021-12-15 08:03:43 【问题描述】:

目前,我有两个问题,如下所述:

问题 1

当我使用 Streamlit 选择任何小部件时,页面总是会重新加载。

如何重现:

    加载页面 选择文件夹 选择多选中的任何项目 当前:页面已重新加载

期望:停止重新加载页面。


问题 2

按钮Import source自动运行

如何重现:

    加载页面 选择文件夹 注意标签 当前:显示文字The button runs?

期望:文字不显示,功能只在点击按钮时运行。


Main.py:

import streamlit as st
import Views.DBImport as dbImport
import Controllers.MongoDBConnection as con
import Processor as processor
import Scraper as scraper
import os
import tkinter as tk
from tkinter import filedialog
import numpy as np

st.title('Test System')

def ProcessFile(dirName):
    fileList = []
    dirlist = []
    fileName = None
    for root, dirs, files in os.walk(dirName):
        for file in files:
            fileList.append([file])
            dirlist.append([dirPath + '/' + file])
            if not fileName:
                fileName = file.split(".")[0]
    if not fileList or not dirlist:
        st.write('Cannot read source folder!')
        st.stop()
    return np.concatenate((fileList, dirlist), axis=1), fileName

def ImportData(title, totalRecords, options, sampleRate, times):
    title = title + sampleRate
    return title

def ReadProperty(fileName, dirName):
    ecgProperty = processor.GetSourceProperty(fileName, dirName)
    # st.write(ecgProperty.channel)
    if not ecgProperty.channel:
        st.write('Cannot read source property!')
        st.stop()

    col1, col2, col3 = st.columns(3)
    with col1:
        title = st.text_input('Source name', 'Test')
        st.text('Total records')
        totalRecords = st.text(str(ecgProperty.record))
    with col2:
        options = st.multiselect(
            'Channel(s)',
            ['I', 'II', 'III',
             'aVR', 'aVL', 'aVF',
             'V1', 'V2', 'V3',
             'V4', 'V5', 'V6'])
        st.text('Total channels')
        st.text(str(len(options)))
    with col3:
        sampleRate = st.slider('Sample rate', 0, 10000,
                               ecgProperty.sample_rate)
        st.text('Time(s)')
        times = st.text(str(ecgProperty.time))

    if st.button('Import source'):
        result = ImportData(title, totalRecords, options, sampleRate, times)
        st.write('result: %s' % result)
    else:
        st.write('The button runs?')

# Set up tkinter
root = tk.Tk()
root.withdraw()

# Make folder picker dialog appear on top of other windows
root.wm_attributes('-topmost', 1)

# Folder picker button
st.text('Please select a folder:')
clicked = st.button('Folder Picker')
if clicked:
    dirPath = filedialog.askdirectory(master=root)
    dirName = st.text_input('Selected folder:', dirPath)
    # Process to get the list of files when selecting the folder
    fileList, fileName = ProcessFile(dirName)

    # Read ECG properties when user selects a source
    ReadProperty(fileName, dirName)

【问题讨论】:

【参考方案1】:

这两个问题有不同的解决方案。

问题 1

您可能需要的是st.form

with st.form(key="form"):
    files = st.file_uploader("Files", accept_multiple_files=True)
    submit_button = st.form_submit_button(label="Submit choice")

if submit_button:
    if files:
        st.markdown("You chose the files ".format(", ".join([f.name for f in files])))
    else:
        st.markdown("You did not choose any file but clicked on 'Submit choice' anyway")
else:
    st.markdown("You did not click on submit button.")

st.form 确保您可以选择所需的任何内容,并且在您单击通过st.form_submit_button(label="Submit choice") 调用的按钮之前,不会重新加载任何小部件。它适用于任何输入:

    name = st.text_input("Your name")
    selected_cities = st.multiselect("Cities", ["Paris", "Milan", "Tokyo"])
    submit_button = st.form_submit_button(label="Submit choice")

if submit_button:
    st.markdown(" wants to live in the following cities: ".format(name, ",".join(selected_cities)))

问题 2

您需要的是st.stop。它告诉 Streamlit 停止执行您的应用程序。

if st.button('Import source'):
    result = ImportData(title, totalRecords, options, sampleRate, times)
    st.write("result: %s" % result)
else: 
    st.write("You did not click on 'Import source', we stop here.")
    st.stop()
    st.write("This is never run, it is just after a stop..")

st.write("This is run because you clicked on 'Import source'")

【讨论】:

以上是关于在Streamlit中使用Python选择任何小部件后如何停止重新加载页面的主要内容,如果未能解决你的问题,请参考以下文章

无 在 Python 中运行 streamlit 时出现类型错误

streamlit—让交互网页的搭建无比简单

如何使用python在streamlit应用程序中打开atoti链接?

Python+Streamlit aggrid+MongoDB GridFS构建低代码文档管理应用(文档查询下载实用篇)

streamlit - 同步输入字段

如何使用python在streamlit和plotly中创建列?