Skip to content

tkinter.filedialog.askdirectory trims trailing whitespace from selected paths, causing validation issues #133334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Sang0920 opened this issue May 3, 2025 · 1 comment
Labels
stdlib Python modules in the Lib dir topic-tkinter type-bug An unexpected behavior, bug, or error

Comments

@Sang0920
Copy link

Sang0920 commented May 3, 2025

Environment:

  • Python Version: Python 3.12.3
  • Operating System: Ubuntu 24.04.2 LTS
  • Tk Version: Tcl/Tk 8.6.14
  • Desktop Environment: GNOME

Problem Description:

The tkinter.filedialog.askdirectory() function appears to normalize the selected path by trimming trailing whitespace characters. If a user selects a directory whose actual name on the filesystem includes one or more trailing spaces, the path string returned by askdirectory() does not include these spaces.

This discrepancy causes problems when attempting to use the returned path string for validation (e.g., with os.path.isdir()) or other filesystem operations, as the trimmed path does not match the actual directory name and therefore appears not to exist or not to be a directory.

Steps to Reproduce:

  1. Create a directory with a trailing space in its name on a Linux filesystem:
    mkdir "/tmp/test dir "
    # Verify the space exists
    ls -b /tmp # Should show 'test dir\ ' or similar representation
  2. Run the following minimal Python script:
    # filepath: reproduce_bug.py
    import tkinter as tk
    from tkinter import filedialog
    import os
    
    root = tk.Tk()
    root.withdraw() # Hide the main window
    
    print("Please select the '/tmp/test dir ' directory...")
    selected_path = filedialog.askdirectory(initialdir='/tmp', title='Select Directory with Trailing Space')
    
    if selected_path:
        print(f"\nPath returned by askdirectory: {repr(selected_path)}")
        print(f"os.path.isdir on returned path: {os.path.isdir(selected_path)}")
    
        # Manually construct the path *with* the expected trailing space
        actual_path = selected_path + " "
        print(f"\nPath with space added manually: {repr(actual_path)}")
        print(f"os.path.isdir on manually corrected path: {os.path.isdir(actual_path)}")
    
        # Verify the directory actually exists with the space
        print(f"\nDirect check on '/tmp/test dir ': {os.path.isdir('/tmp/test dir ')}")
    else:
        print("Dialog cancelled.")
    
    root.destroy()
  3. When the dialog appears, navigate to tmp and select the test dir directory.
  4. Observe the output.

Expected Behavior:

The selected_path variable should contain the string '/tmp/test dir ' (including the trailing space), and os.path.isdir(selected_path) should return True.

Actual Behavior:

The selected_path variable contains the string '/tmp/test dir' (the trailing space is missing). Consequently, os.path.isdir(selected_path) returns False. The subsequent check using the manually added space (actual_path) correctly returns True.

Example Output:

Please select the '/tmp/test dir ' directory...

Path returned by askdirectory: '/tmp/test dir'
os.path.isdir on returned path: False

Path with space added manually: '/tmp/test dir '
os.path.isdir on manually corrected path: True

Direct check on '/tmp/test dir ': True

Impact:

This behavior makes it unreliable to use the path returned by askdirectory directly when directory names might contain trailing spaces. Developers need to implement workarounds, such as attempting to find matching directories in the parent (which is heuristic and error-prone) or forcing users to manually type/edit paths, negating the convenience of the file dialog.

Note:

It's understood that this path normalization might be inherited from the underlying native OS file dialog. However, it raises the question of whether Tkinter's wrapper could or should attempt to preserve the exact selection or provide an option to control this normalization behavior.

@ZeroIntensity ZeroIntensity added topic-tkinter type-bug An unexpected behavior, bug, or error labels May 3, 2025
@terryjreedy
Copy link
Member

tkinter.filedialog.askdirectory(options) returns tkinter.filedialog.Directory(**options).show(). Directory(superclass tkinter.commondialog.Dialog) uses tk_chooseDirectory. This uses native file dialogs and there are few options and none about name stripping. Directory._fixresult (called tk_chooseDirectory returns result.string when result is a Tcl path object. I presume the latter is a Python wrapper, defined in _tkinter.c, of the tcl object. If python strips directory trailing strings, it would be in creating this string attribute. This is as far as I will look.

@picnixz picnixz added the stdlib Python modules in the Lib dir label May 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stdlib Python modules in the Lib dir topic-tkinter type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

4 participants