Skip to content

importing soundcard blocks tkinter.filedialog.askdirectory on Windows #182

@johnohagan

Description

@johnohagan

On Windows, the following code blocks after the print statement, unless the commented lines are uncommented:

from tkinter import filedialog
#import ctypes
#ctypes.windll.ole32.CoInitialize(None)
import soundcard

print('opening dialog')
filedialog.askdirectory()

I copied this solution from a 2018 Stack Exchange post. The workaround is pretty simple and doesn't seem to cause any issues, but it took forever to debug as the cause was far from obvious.

I don't pretend to understand the details (I'm generally a Linux user and came across this while porting something to Windows) but it's something to do with how Microsoft's COM handles threads. If the thread-handling state is set to multi-threaded, it's incompatible with that particular dialog widget (other tkinter dialogs work fine). It seems likely that soundcard is doing this - possibly at lines 41-49 of mediafoundation.py:

        if platform.win32_ver()[0] == '8':
            # On Windows 8, according to Microsoft, the first use of 
            # IAudioClient should be from the STA thread. Calls from 
            # an MTA thread may result in undefined behavior.
            
            # CoInitialize initialises calling thread to STA.
            hr = _ole32.CoInitialize(_ffi.NULL)
        else:
            hr = _ole32.CoInitializeEx(_ffi.NULL, COINIT_MULTITHREADED)

Maybe just calling _ole32.CoInitialize(_ffi.NULL) for all Windows versions would solve the problem? I don't know enough about this to know if that's a viable solution.

Thanks for your work on this module!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions