Restore focus after using file dialogs,
@@ -1979,28 +1979,60 @@ def _get_dialog_provider():
return filedialog
+def try_restore_focus_after_file_dialog(dialog_parent):
+ if dialog_parent is None:
+ return
+
+ logger.info("Restoring focus to %s", dialog_parent)
+ old_focused_widget = dialog_parent.winfo_toplevel().focus_get()
+
+ dialog_parent.winfo_toplevel().lift()
+ dialog_parent.winfo_toplevel().focus_force()
+ dialog_parent.winfo_toplevel().grab_set()
+ if running_on_mac_os():
+ dialog_parent.winfo_toplevel().grab_release()
+
+ if old_focused_widget is not None:
+ try:
+ old_focused_widget.focus_force()
+ except TclError:
+ logger.warning("Could not restore focus to %r", old_focused_widget)
+
+
def asksaveasfilename(**options):
# https://tcl.tk/man/tcl8.6/TkCmd/getOpenFile.htm
- _check_dialog_parent(options)
+ parent = _check_dialog_parent(options)
+ try:
return _get_dialog_provider().asksaveasfilename(**options)
+ finally:
+ try_restore_focus_after_file_dialog(parent)
def askopenfilename(**options):
# https://tcl.tk/man/tcl8.6/TkCmd/getOpenFile.htm
- _check_dialog_parent(options)
+ parent = _check_dialog_parent(options)
+ try:
return _get_dialog_provider().askopenfilename(**options)
+ finally:
+ try_restore_focus_after_file_dialog(parent)
def askopenfilenames(**options):
# https://tcl.tk/man/tcl8.6/TkCmd/getOpenFile.htm
- _check_dialog_parent(options)
+ parent = _check_dialog_parent(options)
+ try:
return _get_dialog_provider().askopenfilenames(**options)
+ finally:
+ try_restore_focus_after_file_dialog(parent)
def askdirectory(**options):
# https://tcl.tk/man/tcl8.6/TkCmd/chooseDirectory.htm
- _check_dialog_parent(options)
+ parent = _check_dialog_parent(options)
+ try:
return _get_dialog_provider().askdirectory(**options)
+ finally:
+ try_restore_focus_after_file_dialog(parent)
def _check_dialog_parent(options):
@@ -2033,6 +2065,8 @@ def _check_dialog_parent(options):
del options["master"]
del options["parent"]
+ return parent
+
class _ZenityDialogProvider:
# https://www.writebash.com/bash-gui/zenity-create-file-selection-dialog-224.html
