Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 e.g. instead of
from tkinter import filedialog
you can use from myfile import filedialog
and just use filedialog.askopenfilename()
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.