Waldkamel
Waldkamel

Reputation: 153

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!

Upvotes: 2

Views: 5742

Answers (2)

wiseboar
wiseboar

Reputation: 335

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 e.g. instead of from tkinter import filedialog you can use from myfile import filedialog and just use filedialog.askopenfilename()

Upvotes: 0

Mike - SMT
Mike - SMT

Reputation: 15226

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()

Upvotes: 2

Related Questions