简体   繁体   中英

tkinter filedialog.askopenfilename() window won't close in python 3

I was playing around with tkinter in python 2x and whenever I use filename = tkFileDialog.askopenfilename() I can easily open a file for use and the dialog window closes automatically after.

Somehow this doesn't work in python 3x. An example code:

import tkinter
from tkinter import filedialog

    def character_mentions():
        filename = filedialog.askopenfilename()
        with open(filename, 'r') as infile:
            reader = csv.reader(infile)
            dict_of_mentions = {rows[1]:rows[2] for rows in reader}
        print(dict_of_mentions)

This gives me the output I'm seeking, but the the empty root window stays open, blank. When I press the X button, it freezes and forces me to shut it down with the task manager.

Any ideas on what to do here? Thanks in advance!

You need to create a tkinter instance and then hide the main window.

In the function you can simply destroy() the tkinter instance once your function is complete.

import tkinter
from tkinter import filedialog

root = tkinter.Tk()
root.wm_withdraw() # this completely hides the root window
# root.iconify() # this will move the root window to a minimized icon.

def character_mentions():
    filename = filedialog.askopenfilename()
    with open(filename, 'r') as infile:
        reader = csv.reader(infile)
        dict_of_mentions = {rows[1]:rows[2] for rows in reader}
    print(dict_of_mentions)
    root.destroy()

character_mentions()

root.mainloop()

if you want a drop-in replacement for filedialog that implements the described solution you can use the following class (myfile.py):

import tkinter as tk
from tkinter import filedialog as fd


# noinspection PyPep8Naming
class filedialog(tk.Tk):

    @classmethod
    def askopenfilename(cls, *args, **kwargs):
        root = cls()
        root.wm_withdraw()
        files = fd.askopenfilename(*args, **kwargs)
        root.destroy()
        return files

This way the usage syntax doesn't need to change eg instead of from tkinter import filedialog you can use from myfile import filedialog and just use filedialog.askopenfilename()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM