how can i open the file explorer to open again when the user exist out?

Viewed 28

the problem i am trying to solve is when the user starts the program , a file explorer opens. if the user exist the window i want to ask the user if they want to quit the program y or n.

from tkinter.filedialog import askdirectory
import pyinputplus as py

def get_location_path():
    while True:
        path = askdirectory(title='Select Folder') # shows dialog box and return the path to the folder the user picks
        if path == '':
            y = py.inputYesNo("would you like to quit the program? ")
            if y == 'yes':
              break
            if y == 'no':
              continue
        else:
            return path


        
y = get_location_path()
print(y)

when i run the program and i exist the window without picking a folder, it will ask me if i want to quit the program, if i type y it quits the program but if i type n it does nothing and i cant even exist the program by pressing CTRL + C

enter n:

would you like to quit the program? n
empyty space
1 Answers

I've had to add some code to get your code to work as a tkinter app - it seems like you want this to run as a command line app which isn't what tkinter is for; however, I've tried to come up with a solution that uses tkinter since that's how this question is tagged.

import tkinter as tk
# import pyinputplus as py  # (you don't need this if using tkinter)
from tkinter import messagebox as tkm  # use native tkinter dialogs instead
from tkinter.filedialog import askdirectory


class App(tk.Tk):
    def __init__(self):
        super().__init__(). # initialize tk
        self.title('My App')
        self.geometry('640x480')
        
        self.path = ''  # create a variable to store the path
        self.get_location_path()  # prompt the user for a path

    def get_location_path(self):
        self.path = askdirectory(title='Select Folder')  # show file dailog
        
        if self.path:  # if a path is selected...
            self.use_location_path()  # do whatever needs to be done with the path
        elif (  # no path selected; ask the user if they want to quit
            tkm.askyesno(
                title='Exit Program?',
                message='Would you like to quit the program?'
            )
        ):
            self.destroy()  # yes, quit
        else:
            self.get_location_path()  # no, ask for path again

    def use_location_path(self):
        print(self.path)  # do some work...
        self.destroy()  # quit once the work is done



if __name__ == '__main__':
    App().mainloop()  # run the app
Related