【发布时间】:2019-03-30 14:30:12
【问题描述】:
我想要一个实现 HTTP API(例如使用 Flask)的 Python 程序,它可以在该程序上接收消息以在屏幕上显示各种窗口(例如使用 tkinter)。
构建这样一个程序的好方法是什么?我相信我需要两个单独的线程:一个用于绘制 tkinter 窗口,一个用于侦听 HTTP 请求。
说,我想向例如发送一个 http 请求。 /show_window,然后在屏幕上显示并保持一个窗口,直到向 /hide_window 发送请求,然后关闭窗口。
我可以通过 tkinter 很好地绘制窗口。但是如果我把它放在 Flask 路由中,它当然会卡在 window.mainloop() 上。
import tkinter as tk
from flask import Flask
app = Flask(__name__)
@app.route("/show")
def show():
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.attributes('-alpha', 0.0) #For icon
root.iconify()
window = tk.Toplevel(root)
window.geometry("%sx%s" % (screen_width, screen_height))
window.configure(background='black', cursor='none')
window.overrideredirect(1)
window.attributes('-topmost', 1)
close = tk.Button(window, text = "Close Window", command = lambda: root.destroy())
close.pack(fill = tk.BOTH, expand = 0)
window.mainloop() # app is stuck here until gui window is closed
return "show!"
@app.route("/hide")
def hide():
### Code to destroy or hide the Window here.
return "hide"
我在想我需要两个线程:一个运行 Flask + 一个启动窗口,然后 Flask 线程需要向窗口线程发送消息以显示、隐藏、创建、销毁窗口,等等 但我不确定该怎么做。
注意,使用 Flask 或 tkinter 绝不是必需的。这只是看起来很适合用于 API 的简单 Web 框架和创建 GUI 窗口的简单方法的工具。
【问题讨论】:
标签: python user-interface flask tkinter python-multithreading