用按钮调用python函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40583347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a python function with a button
提问by kemis
I want to be able to click on a button in html and call a python function. I have tried thisand it works but only for text. And I have seen herethat you can use the function name in action for buttons but it does not work and I dont know why :/
我希望能够单击 html 中的按钮并调用 python 函数。我试过这个,它有效,但仅适用于文本。我在这里看到您可以在按钮中使用函数名称,但它不起作用,我不知道为什么:/
And I dont want after the click of the button go to to another page, I want to stay on the same page and just execute the code from the function.
而且我不想在单击按钮后转到另一个页面,我想留在同一页面上并只执行函数中的代码。
my py file :
我的 py 文件:
from flask import Flask
from flask import render_template
import tkinter as tk
from tkinter import filedialog
import sys
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('hello.html')
@app.route('/upload/')
def uploaduj():
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
return file_path
my html file:
我的 html 文件:
<!doctype html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Flaskr</h1>
<div class=metanav>
<button action="/upload/">Klik</button>
</div>
I am really new to python and flask so every help is appreciated.
我对 python 和烧瓶真的很陌生,所以感谢每一个帮助。
EDIT:i now know that tkinter will not work in web browsers
编辑:我现在知道 tkinter 不能在网络浏览器中工作
采纳答案by OneCricketeer
You want an HTML file input dialog.
您需要一个 HTML 文件输入对话框。
<form action="/upload">
<input type="file" name="fileupload" value="fileupload" id="fileupload">
<label for="fileupload"> Select a file to upload</label>
<input type="submit" value="Klik">
</form>
How you handle that in Flask, is in the documentation
你如何在 Flask 中处理它,在文档中
回答by Grey Li
Try this:
尝试这个:
<button action="{{ url_for('uploaduj') }}">Klik</button>
or just use a tag:
或者只使用一个标签:
<a href="{{ url_for('uploaduj') }}">Klik</a>
To avoid page redirect, you can use this :
为避免页面重定向,您可以使用:
return (''), 204