Skip to content

[tkinter] filedialog ask* functions can return an empty tuple when cancelled - #16642

Open
hoangchunghien wants to merge 2 commits into
python:mainfrom
hoangchunghien:tkinter-filedialog-cancel
Open

hoangchunghien wants to merge 2 commits into
python:mainfrom
hoangchunghien:tkinter-filedialog-cancel

Conversation

@hoangchunghien

Copy link
Copy Markdown
Contributor

Fixes #16637

askopenfilename, asksaveasfilename and askdirectory were typed as returning str, but when the dialog is cancelled they can return an empty tuple. Which one you get depends on the Tk version. I cancelled each function under Xvfb on Linux:

function Tk 8.6.15 (Python 3.13.9) Tk 9.0.3 (Python 3.14.4)
askopenfilename () ()
asksaveasfilename () ()
askdirectory '' ()
askopenfilenames () ()
askopenfile, asksaveasfile None None
askopenfiles () ()

So the three str functions become str | tuple[()], as suggested in the issue. The others already match: askopenfilenames is Literal[""] | tuple[str, ...], the file-object ones return None or an empty tuple as typed. I did not check Windows or macOS, where Tk uses native dialogs.

Added assert_type cases to check_tkinter.py. regr_test.py stdlib (3.13, 3.10, and win32), mypy_test.py stdlib/tkinter, pyright_test.py, black and flake8 pass locally.

@github-actions

This comment has been minimized.

@AlexWaygood
AlexWaygood requested a review from Akuli October 29, 2026 20:41
# Cancelling a dialog gives an empty string or an empty tuple, depending on the Tk version.
assert_type(tkinter.filedialog.askopenfilename(), str | tuple[()])
assert_type(tkinter.filedialog.asksaveasfilename(), str | tuple[()])
assert_type(tkinter.filedialog.askdirectory(), str | tuple[()])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please delete these tests. They are unnecessary: now that we have gotten this right once, it's very unlikely to break in the future.

@hoangchunghien

Copy link
Copy Markdown
Contributor Author

Removed them in b37beaa, thanks.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Return types in tkinter.filedialog

2 participants