如何在Flask/Python中捕获按钮点击信息以修改图片src属性
Flask按钮点击替换图片实现方案
需求说明
本人是Flask/Python新手,想实现以下功能:捕获用户的按钮点击信息,并用该信息修改页面元素——比如点击按钮1时,获取按钮详情,将其下方图片的src替换为另一张图片。
现有代码
HTML代码(buttonli.html)
<table border="1" class="dataframe"> <tbody> <tr> <td><button id="1" onclick="buttonClicked('1')">1</button><br/><img width="25" height="25" src="1"></td> <td><button id="2" onclick="buttonClicked('2')">2</button><br/><img width="25" height="25" src="2"></td> <td><button id="3" onclick="buttonClicked('3')">3</button><br/><img width="25" height="25" src="3"></td> <td><button id="4" onclick="buttonClicked('4')">4</button><br/><img width="25" height="25" src="4"></td> <td><button id="5" onclick="buttonClicked('5')">5</button><br/><img width="25" height="25" src="5"></td> <td><button id="6" onclick="buttonClicked('6')">6</button><br/><img width="25" height="25" src="6"></td> <td><button id="7" onclick="buttonClicked('7')">7</button><br/><img width="25" height="25" src="7"></td> <td><button id="8" onclick="buttonClicked('8')">8</button><br/><img width="25" height="25" src="8"></td> <td><button id="9" onclick="buttonClicked('9')">9</button><br/><img width="25" height="25" src="9"></td> <td><button id="10" onclick="buttonClicked('10')">10</button><br/><img width="25" height="25" src="10"></td> </tr> </tbody> </table>
Flask后端代码
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('buttonli.html') @app.route('/button_clicked', methods=['POST']) def button_clicked(): selected_button = request.form['button_id'] uploaded_image = request.files['uploaded_image'] if uploaded_image: uploaded_image.save(f"resimler/{selected_button}.jpg") return 'İşlem tamamlandı' if __name__ == '__main__': app.run(debug=True)
完整实现步骤
1. 调整项目结构
Flask默认从static文件夹读取静态资源,创建static/resimler目录用于存放图片,前端可通过/static/resimler/xxx.jpg访问图片。
2. 修改前端HTML,补充JavaScript逻辑
给每个图片添加唯一ID,实现buttonClicked函数,支持直接替换预存图片或上传图片后更新:
<table border="1" class="dataframe"> <tbody> <tr> <td><button id="1" onclick="buttonClicked('1')">1</button><br/><img id="img_1" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="2" onclick="buttonClicked('2')">2</button><br/><img id="img_2" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="3" onclick="buttonClicked('3')">3</button><br/><img id="img_3" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="4" onclick="buttonClicked('4')">4</button><br/><img id="img_4" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="5" onclick="buttonClicked('5')">5</button><br/><img id="img_5" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="6" onclick="buttonClicked('6')">6</button><br/><img id="img_6" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="7" onclick="buttonClicked('7')">7</button><br/><img id="img_7" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="8" onclick="buttonClicked('8')">8</button><br/><img id="img_8" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="9" onclick="buttonClicked('9')">9</button><br/><img id="img_9" width="25" height="25" src="/static/resimler/default.jpg"></td> <td><button id="10" onclick="buttonClicked('10')">10</button><br/><img id="img_10" width="25" height="25" src="/static/resimler/default.jpg"></td> </tr> </tbody> </table> <script> function buttonClicked(buttonId) { const imgElement = document.getElementById(`img_${buttonId}`); // 方式1:直接替换为预存的目标图片 // imgElement.src = `/static/resimler/new_${buttonId}.jpg`; // 方式2:触发图片上传,上传完成后更新图片 const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = 'image/*'; fileInput.onchange = function(e) { const formData = new FormData(); formData.append('button_id', buttonId); formData.append('uploaded_image', e.target.files[0]); fetch('/button_clicked', { method: 'POST', body: formData }).then(response => response.json()) .then(data => { if (data.status === 'success') { // 添加时间戳避免浏览器缓存旧图片 imgElement.src = `/static/resimler/${buttonId}.jpg?${new Date().getTime()}`; } }); }; fileInput.click(); } </script>
3. 修改Flask后端代码
调整图片保存路径到static/resimler,并返回JSON格式响应:
from flask import Flask, render_template, request, jsonify import os app = Flask(__name__) # 自动创建static/resimler目录 os.makedirs(os.path.join(app.static_folder, 'resimler'), exist_ok=True) @app.route('/') def index(): return render_template('buttonli.html') @app.route('/button_clicked', methods=['POST']) def button_clicked(): selected_button = request.form['button_id'] uploaded_image = request.files.get('uploaded_image') if uploaded_image and uploaded_image.filename != '': save_path = os.path.join(app.static_folder, 'resimler', f"{selected_button}.jpg") uploaded_image.save(save_path) return jsonify({'status': 'success', 'message': '图片上传成功'}) return jsonify({'status': 'error', 'message': '未选择有效图片'}) if __name__ == '__main__': app.run(debug=True)
4. 注意事项
- 若不需要上传功能,直接启用方式1的代码即可
- 添加时间戳是为了避免浏览器缓存旧图片,确保新图片能及时显示
- 确保
static/resimler目录有写入权限,否则图片无法保存
内容的提问来源于stack exchange,提问作者Hageshiku
相关产品推荐
相关产品推荐

