【问题标题】:Calling a python function with a button使用按钮调用 python 函数
【发布时间】:2017-03-27 18:31:18
【问题描述】:

我希望能够单击 html 中的按钮并调用 python 函数。 我已经尝试过this,它有效,但仅适用于文本。我已经看到here 你可以在按钮上使用函数名,但它不起作用,我不知道为什么:/

而且我不想在单击按钮后转到另一个页面,我想留在同一页面上,只执行函数中的代码。

我的 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

我的 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>

我对 python 和烧瓶真的很陌生,所以每一个帮助都非常感谢。

编辑:我现在知道 tkinter 不能在网络浏览器中运行

【问题讨论】:

  • 你不能在浏览器中打开 tkinter 窗口,对吗?
  • 我可以,那部分效果很好
  • 真的吗?看起来您正在让服务器打开一个文件对话框。如果服务器在另一台计算机上,这应该不起作用
  • 使用&lt;input type='file'&gt;。 Tk 是一个 GUI 库。即使你让它工作,它也不会成为浏览器的一部分。
  • @MilosRadosavljevic TkInter 不是 Web UI 库。它不适用于 Web 应用程序。它可能看起来适用于您的情况,但实际上它永远不会适用于 Web 应用程序。此外,action 是您尝试附加到button 的自定义属性,因为button 元素没有action 属性。

标签: python flask


【解决方案1】:

试试这个:

<button action="{{ url_for('uploaduj') }}">Klik</button> 

或者只是使用一个标签:

<a href="{{ url_for('uploaduj') }}">Klik</a> 

为了避免页面重定向,你可以使用这个:

return (''), 204

【讨论】:

  • 第一个不起作用,第二个就像我在问题中所说的那样起作用,但我希望它是一个按钮。重定向有效,因此您获得 +1 :D 我将按钮放在一个表单中并在那里使用了操作,现在它可以工作了,有点愚蠢但可以工作,谢谢
  • 你可以使用 CSS 来设置样式。
【解决方案2】:

您想要一个 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>

你如何在 Flask 中处理这个问题,is in the documentation

【讨论】:

  • 链接已失效。
猜你喜欢
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
  • 2016-07-31
  • 2021-11-03
相关资源
最近更新 更多