-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative_dialog.py
More file actions
78 lines (65 loc) · 2.51 KB
/
Copy pathnative_dialog.py
File metadata and controls
78 lines (65 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""native_dialog.py — native OS file dialogs via tkinter, with DPG fallback.
Tkinter dialogs are blocking, so each call spawns a daemon thread.
Callbacks are posted to _pending and drained on the main thread via flush(),
which is called from the render loop — safe for DPG operations.
"""
import threading
_pending: list = []
def flush() -> None:
"""Drain posted callbacks. Call from the render loop (main thread)."""
while _pending:
_pending.pop(0)()
def _post(fn) -> None:
_pending.append(fn)
def open_file(title: str, filetypes: list, initial_dir: str,
on_done, fallback_tag: str = "") -> None:
"""Open a native file-open dialog in a background thread.
on_done(path: str) is called on the main thread after user confirms.
Falls back to DPG dialog (fallback_tag) when tkinter is unavailable.
"""
def _run():
try:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
path = filedialog.askopenfilename(
title=title,
filetypes=filetypes,
initialdir=initial_dir,
)
root.destroy()
if path:
_post(lambda p=path: on_done(p))
except ImportError:
if fallback_tag:
import dearpygui.dearpygui as dpg
_post(lambda: dpg.show_item(fallback_tag))
threading.Thread(target=_run, daemon=True).start()
def save_file(title: str, filetypes: list, initial_dir: str,
default_ext: str, default_name: str,
on_done, fallback_tag: str = "") -> None:
"""Open a native file-save dialog in a background thread."""
def _run():
try:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
path = filedialog.asksaveasfilename(
title=title,
filetypes=filetypes,
initialdir=initial_dir,
defaultextension=default_ext,
initialfile=default_name,
)
root.destroy()
if path:
_post(lambda p=path: on_done(p))
except ImportError:
if fallback_tag:
import dearpygui.dearpygui as dpg
_post(lambda: dpg.show_item(fallback_tag))
threading.Thread(target=_run, daemon=True).start()