[Python] Why won't the file dialog open when I use withdraw() early in the program? [closed]

Discussão em 'Python' iniciado por Stack, Novembro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm in a CS class for college right now, and we've gotten to the part in our Python course where we learn how to read, write, and append to external files. We were given some class work where we have to use the tkinter file dialog to open a file with info we need to read, then create one to write some info by processing the first file's data.

    But I've reached a major issue. In class, we were taught that we could get the tkinter base window to disappear without removing the dialog by using root.withdraw() (assuming we already imported tkinter and created the root) before we use the askopenfilename() or asksaveasname() functions. And yet, every time I try to run the program with root.withdraw() in the beginning, it freezes infinitely and won't do a damn thing.

    But then if I move it to the end after both with statements where I do my processing, the dialog opens up, but with the tkinter window! What the heck is going on with this program? How do I go about keeping the window closed while doing two separate with statements?

    Here's the code, simplified to one with statement and excluding it's contents since they have no real bearing on what's going on:

    def main():

    #import file dialog modules
    from tkinter.filedialog import askopenfilename, asksaveasfilename

    # This will prevent root (ghost) window
    import tkinter
    root = tkinter.Tk()
    root.withdraw()

    read_file_name = askopenfilename()
    with open(read_file_name, "r") as file:
    ...


    No other solutions that I've found to similar inquiries work whatsoever for this specific case, either by using root.update() or moving withdraw() or anything of that sort. I would appreciate any feedback on how to get this to function the intended way.

    Continue reading...

Compartilhe esta Página