File size: 9,997 Bytes
2679bb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import streamlit as st

class StreamlitTutorial:
    def __init__(self):
        st.set_page_config(page_title="Learn Streamlit", layout="wide")
        self.init_session_state()
        self.setup_styles()

    def init_session_state(self):
        if 'code_input' not in st.session_state:
            st.session_state.code_input = ""
            st.session_state.current_topic = "Basic Text Elements"

    def setup_styles(self):
        st.markdown("""
        <style>
        .code-example { 
            margin-bottom: 1.5rem;
        }
        .live-output {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 1rem;
            margin: 0.5rem 0 1.5rem 0;
        }
        .section-title {
            margin-bottom: 1rem;
            padding: 0.5rem 0;
        }
        .button-container {
            display: flex;
            justify-content: space-between;
            gap: 1rem;
        }
        </style>
        """, unsafe_allow_html=True)

    def get_text_elements(self):
        return [
            ("Title", "st.title('Main Title')"),
            ("Header", "st.header('Header')"),
            ("Subheader", "st.subheader('Subheader')"),
            ("Normal text", "st.write('Normal text')"),
            ("Markdown text", "st.markdown('**Bold** and *italic*')"),
            ("Colored text", "st.markdown(':blue[Blue text]')")
        ]

    def get_input_elements(self):
        return [
            ("Text Input", "name = st.text_input('Enter your name')"),
            ("Number Input", "num = st.number_input('Enter a number', min_value=0, max_value=100)"),
            ("Slider", "value = st.slider('Select value', 0, 100, 50)"),
            ("Selectbox", "option = st.selectbox('Choose option', ['A', 'B', 'C'])"),
            ("Checkbox", "checked = st.checkbox('Enable feature')")
        ]

    def render_text_elements(self, col):
        with col:
            st.markdown("### πŸ“ Code Examples")
            for title, code in self.get_text_elements():
                with st.container(border=True):
                    st.markdown(f"**{title}**")
                    st.code(code)
                    st.markdown("Live output:")
                    with st.container(border=True):
                        exec(code)

    def render_input_elements(self, col):
        with col:
            st.markdown("### πŸ“ Code Examples")
            for title, code in self.get_input_elements():
                with st.container(border=True):
                    st.markdown(f"**{title}**")
                    st.code(code)
                    st.markdown("Live output:")
                    with st.container(border=True):
                        exec(code)

    def render_help_section(self, col):
        with col:
            st.markdown("### πŸ“š Learning Guide")
            
            with st.expander("🎯 Basic Concepts", expanded=True):
                st.markdown("""
                **What are Text Elements?**
                - Basic building blocks for displaying text
                - Range from titles to formatted text
                - Support markdown formatting
                """)
                
            with st.expander("πŸ’‘ Best Practices"):
                st.markdown("""
                **Writing Tips:**
                1. Use appropriate heading levels
                2. Keep text concise and clear
                3. Use formatting for emphasis
                4. Add visual hierarchy with headers
                
                **Code Structure:**
                ```python
                st.title('Main Title')
                st.header('Section Header')
                st.subheader('Sub-section')
                st.write('Regular text')
                ```
                """)
            
            with st.expander("πŸ” Examples & Use Cases"):
                st.markdown("""
                **Common Patterns:**
                
                1. Page Structure
                ```python
                st.title('Dashboard')
                st.header('Sales Data')
                st.subheader('Monthly Trends')
                ```
                
                2. Formatted Text
                ```python
                st.markdown('**Bold** and *italic*')
                st.markdown(':blue[Colored text]')
                ```
                
                3. Mixed Elements
                ```python
                st.title('Report')
                st.write('Regular text')
                st.markdown('- Bullet point')
                ```
                """)
            
            with st.expander("⚠️ Common Mistakes"):
                st.markdown("""
                1. Skipping header levels
                2. Overusing formatting
                3. Inconsistent styling
                4. Missing hierarchy
                
                **How to Avoid:**
                - Plan your page structure
                - Use consistent formatting
                - Test different screen sizes
                - Keep it simple
                """)
            
            with st.expander("πŸš€ Advanced Tips"):
                st.markdown("""
                **Advanced Formatting:**
                ```python
                # Custom HTML
                st.markdown('''
                    <span style='color:blue'>
                        Custom styled text
                    </span>
                ''', unsafe_allow_html=True)
                
                # Complex Markdown
                st.markdown('''
                    # Title
                    ## Subtitle
                    * Point 1
                        * Subpoint
                    > Quote
                ''')
                ```
                
                **Layout Combinations:**
                ```python
                col1, col2 = st.columns(2)
                with col1:
                    st.header('Column 1')
                with col2:
                    st.header('Column 2')
                ```
                """)

    def render_playground(self, col, snippets):
        with col:
            st.markdown("### πŸ’» Practice Playground")
            
            # Code input area
            code_input = st.text_area(
                "Try Streamlit commands:",
                value=st.session_state.code_input,
                height=200,
                placeholder="Example:\nst.title('My Title')"
            )

            # Quick Snippets with better alignment
            with st.container(border=True):
                st.markdown("#### πŸ“š Quick Snippets")
                
                cols = st.columns([4, 1])
                with cols[0]:
                    selected_snippet = st.selectbox(
                        "Choose snippet:",
                        list(snippets.keys()),
                        label_visibility="collapsed"
                    )
                with cols[1]:
                    if st.button("Add", use_container_width=True):
                        new_code = snippets[selected_snippet]
                        if code_input:
                            code_input += f"\n{new_code}"
                        else:
                            code_input = new_code
                        st.session_state.code_input = code_input

            # Control buttons
            col1, col2, col3 = st.columns(3)
            with col1:
                if st.button("▢️ Run", use_container_width=True):
                    st.session_state.code_input = code_input
            with col2:
                if st.button("πŸ”„ Reset", use_container_width=True):
                    st.session_state.code_input = ""
                    code_input = ""
            with col3:
                if st.button("πŸ’Ύ Copy", use_container_width=True):
                    st.code(code_input)

            # Live output
            st.markdown("#### 🎨 Live Output")
            with st.container(border=True):
                if code_input:
                    try:
                        exec(code_input)
                    except Exception as e:
                        st.error(f"Error: {str(e)}")

            # Tips
            with st.expander("πŸ’‘ Tips & Help"):
                st.markdown(self.get_topic_tips(st.session_state.current_topic))

    def get_topic_tips(self, topic):
        tips = {
            "Basic Text Elements": """
                **Quick Tips:**
                - Use markdown for formatting
                - Try different header levels
                - Combine text elements
                - Use colored text with :color[text]
            """,
            "Input Widgets": """
                **Quick Tips:**
                - Use unique keys for widgets
                - Store widget values in variables
                - Add validation for inputs
                - Combine widgets for complex inputs
            """
        }
        return tips.get(topic, "Tips coming soon!")

    def run(self):
        with st.sidebar:
            st.title("Streamlit Tutorial")
            st.session_state.current_topic = st.radio(
                "Choose a Topic:",
                ["Basic Text Elements", "Input Widgets", "Layouts & Containers", 
                 "Data Display", "Charts & Plots", "Interactive Components"]
            )

        if st.session_state.current_topic == "Basic Text Elements":
            cols = st.columns([1.2, 1, 1])
            self.render_text_elements(cols[0])
            self.render_help_section(cols[1])
            self.render_playground(cols[2], dict(self.get_text_elements()))
            
        elif st.session_state.current_topic == "Input Widgets":
            cols = st.columns([1.2, 1, 1])
            self.render_input_elements(cols[0])
            self.render_help_section(cols[1])
            self.render_playground(cols[2], dict(self.get_input_elements()))

if __name__ == "__main__":
    app = StreamlitTutorial()
    app.run()