2016-11-14 102 views
2

我希望能夠點擊html中的按鈕並調用python函數。 我試過this,它可以工作,但只適用於文本。我已經看到here,你可以使用按鈕的功能名稱的行動,但它不工作,我不知道爲什麼:/用按鈕調用python函數

而我不想要點擊按鈕轉到另一個頁面後,我想留在同一頁面上,只需執行函數中的代碼即可。

我的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將不會在Web瀏覽器上

+0

你不能打開窗戶Tkinter的在瀏覽器中,你能嗎? –

+0

我可以,那部分作品完美 – kemis

+1

真的嗎?它看起來像你讓服務器打開一個文件對話框。這應該不會工作,如果服務器在另一臺計算機上 –

回答

1

你想要一個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> 

你如何處理,在瓶,is in the documentation

+0

謝謝,我會研究:) – kemis

2

試試這個:

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

或只使用一個標籤:

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

爲了避免頁面重定向,你可以用這個:

return (''), 204 
+0

第一個不起作用,第二個就像我在我的問題中說的那樣工作,但我希望它是一個按鈕,重定向的作用是讓你得到+ 1:D 我把按鈕放在一個表格裏,我們ed動作在那裏,它現在有效,有點愚蠢,但作品,謝謝你 – kemis

+0

你可以使用CSS來設計它。 –