Created
August 10, 2025 22:48
-
-
Save jsbueno/c79cfe9818edf7919f5a2e95a05df8e8 to your computer and use it in GitHub Desktop.
"Hello world" tkinter app with a fastapi backend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tkinter, fastapi | |
import requests | |
port = 8003 | |
localurl = f"http://localhost:{port}/" | |
def uimain(): | |
def doit(): | |
endpoint = "transform/" | |
xis = requests.get(localurl + endpoint, params={"text":entryvar.get()}) | |
outvar.set(xis.json()["text"]) | |
window = tkinter.Tk() | |
text = tkinter.Entry(window, textvariable=(entryvar:=tkinter.Variable()) ) | |
label = tkinter.Label(window, textvariable=(outvar:=tkinter.Variable()) ) | |
button = tkinter.Button(window, text="ok", command=doit) | |
for widget in (text, label, button): | |
widget.pack() | |
tkinter.mainloop() | |
def backmain(): | |
global app | |
app = fastapi.FastAPI() | |
@app.get("/transform/") | |
async def transform(text: str): | |
return {"text": text.upper() * 2} | |
if __name__ == "__main__": | |
import os, subprocess | |
if not (pid:=os.fork()): | |
fastapi = subprocess.Popen(["fastapi", "run", "--port", str(port), __file__]) | |
open("tkfront.pid", "wt").write(str(fastapi.pid)) | |
fastapi.wait() | |
exit(0) | |
try: | |
uimain() | |
finally: | |
os.system(f"kill {open('tkfront.pid').read()}") | |
os.unlink("tkfront.pid") | |
else: | |
backmain() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment