python 简化如何在单行中显示按钮

roqulrg3  于 2024-01-05  发布在  Python
关注(0)|答案(4)|浏览(143)

大家好,我正在建设一个简单的网络应用程序与streamlit在python。我需要添加3个按钮,但他们必须在同一行。
显然,下面的代码将它们放在三个不同的行上

  1. st.button('Button 1')
  2. st.button('Button 2')
  3. st.button('Button 3')

字符串
你有什么建议吗?

w3nuxt5m

w3nuxt5m1#

很明显这个应该可以了

  1. col1, col2, col3 = st.columns([1,1,1])
  2. with col1:
  3. st.button('1')
  4. with col2:
  5. st.button('2')
  6. with col3:
  7. st.button('3')

字符串

8ehkhllq

8ehkhllq2#

如果你像我一样,它可能会困扰你,列等间距,使布局没有视觉吸引力,因为按钮看起来相距甚远。
经过大量的CSS挖掘,我发现了一个非常简单的方法,不需要安装任何其他库。可以(至少对于当前版本的streamlit)应用以下CSS使列仅与按钮一样宽。我在文件的顶部包含了这个:

  1. st.markdown("""
  2. <style>
  3. div[data-testid="column"] {
  4. width: fit-content !important;
  5. flex: unset;
  6. }
  7. div[data-testid="column"] * {
  8. width: fit-content !important;
  9. }
  10. </style>
  11. """, unsafe_allow_html=True)

字符串
然后(对于我的用例):

  1. col1, col2, col3 = st.columns([1,1,1])
  2. with col1:
  3. st.button(...)
  4. with col2:
  5. st.button(...)
  6. with col3:
  7. st.download_button(...)

展开查看全部
pobjuy32

pobjuy323#

我有一个类似的问题-添加一个动作按钮到一个表。我来到了以下方法:

  1. import streamlit as st
  2. # # Show users table
  3. colms = st.columns((1, 2, 2, 1, 1))
  4. fields = ["№", 'email', 'uid', 'verified', "action"]
  5. for col, field_name in zip(colms, fields):
  6. # header
  7. col.write(field_name)
  8. for x, email in enumerate(user_table['email']):
  9. col1, col2, col3, col4, col5 = st.columns((1, 2, 2, 1, 1))
  10. col1.write(x) # index
  11. col2.write(user_table['email'][x]) # email
  12. col3.write(user_table['uid'][x]) # unique ID
  13. col4.write(user_table['verified'][x]) # email status
  14. disable_status = user_table['disabled'][x] # flexible type of button
  15. button_type = "Unblock" if disable_status else "Block"
  16. button_phold = col5.empty() # create a placeholder
  17. do_action = button_phold.button(button_type, key=x)
  18. if do_action:
  19. pass # do some action with row's data
  20. button_phold.empty() # remove button

字符串
它工作得很好。对象-user_table-是一个与DataFrame非常相似的字典,其中每个键-是一个列(即Python术语中的list)。下面是它的样子(注意“阻塞”-这是操作的结果):x1c 0d1x

展开查看全部
ryoqjall

ryoqjall4#

this answer进行了一点泛化,以使用动态数量的按钮:

  1. import streamlit as st # 1.18.1
  2. button_text = "foo", "bar", "baz"
  3. for text, col in zip(button_text, st.columns(len(button_text))):
  4. if col.button(text):
  5. col.write(f"{text} clicked")

字符串
如果文本不一定是唯一的:

  1. button_text = "foo", "bar", "foo"
  2. pairs = zip(button_text, st.columns(len(button_text)))
  3. for i, (text, col) in enumerate(pairs):
  4. if col.button(text, key=f"{text}-{i}"):
  5. col.write(f"{text}-{i} clicked")

展开查看全部

相关问题