Interactive Text Display Web App with Python and Flask
Build an Interactive Text Display Web App with Python and Flask
This tutorial guides you through creating a web application that reads and displays text from CSV files with interactive elements. Users can select chapters and sections, reveal hidden text, and interact with the displayed content.
Here's a breakdown of the steps:
1. Setting up the Flask Application:
First, we'll create the Flask app, define routes, and handle requests.pythonfrom flask import Flask, render_template, requestimport csv
app = Flask(name)
@app.route('/')def index(): chapters = ['Chapter 1', 'Chapter 2'] sections = ['Section 1', 'Section 2'] return render_template('index.html', chapters=chapters, sections=sections)
@app.route('/choose', methods=['POST'])def choose(): chapter = request.form['chapter'] section = request.form['section'] csv_file = f'Text/{chapter}_{section}.csv' with open(csv_file, 'r') as file: reader = csv.reader(file) data = list(reader) return render_template('text.html', data=data)
if name == 'main': app.run(debug=True)
2. Crafting the HTML Templates:
Next, we'll design the HTML templates for the index page (chapter/section selection) and the text display page.
**index.html:**html
Select Chapter and Section
**text.html:**html
Text Display
{{ row[0] }} {{ row[1] }} {{ row[2] }} {{ row[3] }}
{% endfor %}3. Styling with CSS:
We'll add some basic styling to enhance the appearance of our web page.
**style.css:**cssh1 { text-align: center;}
form { text-align: center;}
#question p { text-align: center;}
.column2, .column3, .column4 { color: transparent;}
#type { display: block; margin: 0 auto;}
button { display: block; margin: 0 auto;}
4. Adding Interactivity with JavaScript:
Finally, we'll use JavaScript to handle button clicks, text display, and interactive elements.
**script.js:**javascriptfunction showAnswer() { var columns = document.getElementsByClassName('column2'); for (var i = 0; i < columns.length; i++) { columns[i].style.color = 'black'; } // Add code here to reveal column3 and column4}
function revealText(element) { element.style.color = 'black';}
function hideText(element) { element.style.color = 'transparent';}
function clearText() { var question = document.getElementById('question'); var type = document.getElementById('type'); question.innerHTML = ''; type.value = ''
原文地址: https://www.cveoy.top/t/topic/fw4t 著作权归作者所有。请勿转载和采集!