且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flask桌面应用程序文件选择器

更新时间:2023-10-19 18:08:46

虽然我不确定流程是否冻结(可能是Tk和您正在使用的库之间的冲突绘制webview?)这可能是一个问题,用户可以延迟(无论在理论上使用视图)。

我推荐的方法是将瓶子视图函数启动/消息一个单独的线程,然后立即返回。 (无论你想在对话框后面想要什么背景)。另一个线程负责以本地操作系统的方式做对话窗口,然后当用户选择了一些内容并完成时,在内部发送另一个请求,以完成需要的任何操作与选定的文件。

我以前从未在桌面应用程序中这样做过,但是它的一些变化(可能是一个单独的过程,而不是一个单独的线程,但理论是相似的)是我喜欢在服务器上处理长时间运行的任务。


I'm trying to use Flask to build the GUI for a desktop application (i.e. a web app running on a server running locally bundled with an embedded browser). Things mostly seem to work for now, but I'd like to add a file chooser to allow users to select a directory on their computer. I need the full path of the directory so opening a dialog using HTML/JavaScript won't work (because of security restrictions).

What I've tried doing instead is to launch a Tkinter file dialog when a button is pressed on the page. The problem is that while it does appear to launch something, the process just freezes (without displaying a window) and I'm forced to kill it, after which the page redirects to '/view_1_actions' and I get an "Error code: ERR_EMPTY_RESPONSE" error (i.e. the Flask app only crashes after I kill what appears to be the dialog window).

Here's my code:

HTML:

<form action="/view_1_actions" method="post">
    <input type="submit" name="submit" value="Select"></input>
</form>

Python:

from flask import Flask, request, redirect
from Tkinter import Tk
from tkFileDialog import askdirectory

@app.route('/view_1_actions', methods = ['POST'])
def view_1_actions():
    if request.form['submit'] == 'Select':
        Tk().withdraw()
        dirname = askdirectory()
    return redirect('/')

Granted this a rather strange scenario since you wouldn't usually be launching a graphical interface on the "server side", but my question is whether there is a way to fix this or an alternative solution I could use to display a file chooser dialog (preferably the native one for each OS).

While I'm not sure about the process freezing (perhaps a conflict between Tk and the library you're using to draw the webview?) it is potentially a problem that the user can delay the response of the view function indefinitely (all the while in theory "using" the view).

What I would recommend would be to have the flask view function start/message a separate thread and then return immediately. (With whatever background you want behind the dialog.) The other thread is responsible for doing the dialog window in a native OS fashion, then when the user selects something and it finishes, send another flask request internally that will do whatever it needs to do with the selected file.

I've never done this in a desktop app before, but some variation of this (might be a separate process rather than a separate thread, but the theory is similar) is how I like to handle long running tasks on a server.