0

I developed a code at work which I want to make a bit more user friendly to share it with my team. This code requires to know the specific location of the file and code to be in the same folder to run. Long story short, I want to add the option to open a dialog window so they can select the file from any directory. I tried the code below since I want that, right after the file is selected and returns its location, then the Tkinter top window automatically closes without the need of using a button so my team can continue with the next step in the process.

The problem is that the it opens three Tkinter windows and they all remain open after the file is selected.

from tkinter import *
from tkinter import filedialog

top = Toplevel()
root = Tk()
root.fileName = filedialog.askopenfilename(filetypes = (("data migration","*.xlsx"),("data migration","*.csv")))
top.destroy()
top.update()

In addition to aforementioned problems, when I try to close those persisting windows, it shuts down Python.

So far the solutions I've found they all add a button which what I'm trying to avoid if possible.

carlosdlcf
  • 25
  • 1
  • 7

2 Answers2

0

Make a function instead and have your function call top.destroy() at the end:

from tkinter import *
from tkinter import filedialog

root = Tk()

top = Toplevel()

def func():
    fileName = filedialog.askopenfilename(filetypes = (("data migration","*.xlsx"),("data migration","*.csv")))
    #do whatever you need to do with your filename
    print (fileName)
    top.destroy()

func()

root.mainloop()
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • Thank you for your help. Your recommendation about using a function helped to prevent Python shutting down. However, the root window was still active. I combined your recommendation with a solution from [Function to close the window in Tkinter ](https://stackoverflow.com/questions/8009176/function-to-close-the-window-in-tkinter) Below is the code I put together with your help. Thanks. – carlosdlcf Sep 28 '19 at 02:42
  • I assumed you have something else going on with your root window. If you don't, you can skip the idea of creating a `Toplevel()` at first place and put `root.destroy()` in `func` instead. – Henry Yik Sep 28 '19 at 11:04
0

Combined solution:

from tkinter import *
from tkinter import filedialog

root = Tk()

top = Toplevel()

def func():
    fileName = filedialog.askopenfilename(filetypes = (("data migration","*.xlsx"),("data migration 2","*.csv")))
    #do whatever you need to do with your filename
    print (fileName)
    top.destroy()

def quit():
    root.destroy()    

func()
quit()

root.mainloop()
carlosdlcf
  • 25
  • 1
  • 7