用一个按钮调用python函数 [英] Calling a python function with a button
问题描述
我已经尝试这个,它的工作原理,但仅用于文本。我已经看到这里你可以使用的功能名称在行动的按钮,但它不工作,我不知道为什么:/ / $ / />
我不希望点击按钮后去另一个页面,我想留在同一页面,只是从函数执行代码。
我的py文件:
from flask import Flask
from flask import render_template
import tkinter as tk
from tkinter import filedialog
import sys $ b $ 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()
返回file_path
$ c $
< / p $ p
!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>
我真的对python和flask很陌生,所以每一个帮助都是值得赞赏的。 b
编辑:我现在知道tkinter不能在web浏览器中工作了。 你需要一个HTML文件输入对话框。
< form action =/ upload>
< input type =filename =fileuploadvalue =fileuploadid =fileupload>
< label for =fileupload>选择要上传的文件< / label>
< input type =submitvalue =Klik>
< / form>
您如何在Flask中处理这个问题,在文档中
I want to be able to click on a button in html and call a python function.
I have tried this and it works but only for text. And I have seen here that you can use the function name in action for buttons but it does not work and I dont know why :/
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 :
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:
<!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.
EDIT: i now know that tkinter will not work in web browsers
解决方案 You want an HTML file input dialog.
<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
这篇关于用一个按钮调用python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!