programmer12
programmer12

Reputation: 111

Tkinter window not closing despite quit() and destroy()

I'm running Tkinter to get a file path using the function filedialog.askopenfilename(). The program is getting the file path correctly but once I click "Open" on the file I want, the code destroy() does not destroy the GUI window that is open.

I've tried both the destroy() and the quit() functions, though I read that destroy() is preferred. I read that if I do root.destroy(), it is supposed to destroy the GUI that is open. What is happening is that, after the user picks a file, then clicks open, the finder window then becomes totally greyed out and unresponsive. I'm guessing this is the point at which we can execute a destroy, but it's not working for me.

I'm really not sure where I'm going wrong. Would really like to delete the Tkinter browser. My code does continue executing despite the browser being open, but it's unprofessional.

import tkinter
from tkinter import filedialog
import os

root = tkinter.Tk()
root.withdraw() #use to hide tkinter window

def search_for_file_path ():
    currdir = os.getcwd()
    tempdir = filedialog.askopenfilename(parent=root, initialdir=currdir, title='Please select a directory')
    if len(tempdir) > 0:
        print ("You chose: %s" % tempdir)
    return tempdir


file_path_variable = search_for_file_path()
root = tkinter.Tk()
root.destroy()
print ("\nfile_path_variable = ", file_path_variable)

Upvotes: 0

Views: 2556

Answers (3)

programmer12
programmer12

Reputation: 111

Seem to have fixed the problem! When I execute the script from the terminal, instead of clicking "run" inside the python app, it works. I'm not sure why one works and not the other, but I'll take it.

Upvotes: 0

Python beginner
Python beginner

Reputation: 3

If it were me than I would use root.mainloop() and then root.destroy(). There are other ways but I am not sure if they work.

Upvotes: 0

Ayoub Benayache
Ayoub Benayache

Reputation: 1164

remove the second instance

import tkinter
from tkinter import filedialog
import os

root = tkinter.Tk()
root.withdraw() #use to hide tkinter window

def search_for_file_path ():
    currdir = os.getcwd()
    tempdir = filedialog.askopenfilename(parent=root, initialdir=currdir, title='Please select a directory')
    if len(tempdir) > 0:
        print ("You chose: %s" % tempdir)
    return tempdir


file_path_variable = search_for_file_path()
# remove the second instance
root.destroy()
print ("\nfile_path_variable = ", file_path_variable)

Upvotes: 1

Related Questions