user1764386
user1764386

Reputation: 5631

Python - keeping Tkinter window open?

Right now I am using Tkinter to prompt the user for a file.

Tk().withdraw() # keep the root window from appearing
file_path = askopenfilename() # show dialog box and return file path

# check if extension is valid

If the user selected the wrong file type, I re-prompt them with a new window.

Is there a way, instead, to keep the same tkinter window open unless the file selected is valid?

so instead of this:

# 1) prompt user to open file
# 2) close file browser window
# 3) check if extension is valid
# 4) if not, print error and re-prompt user with new browser window

I want to do this:

# 1) prompt user to open file
# 2) check if extension is valid while keeping window open
# 3) if not, print error, re-prompting with same window

Any help is appreciated.

Upvotes: 0

Views: 1353

Answers (2)

Brian L
Brian L

Reputation: 3251

If you want the user to open a particular file type, use the filetypes argument. It takes a list of file type definitions, which you specify as a description and an extension:

filepath = askopenfilename(filetypes = [
    ('Text Files', '.txt'),
    ('Python Scripts', '.py'),
    ('INI Files', '.ini')
])

Upvotes: 1

Moro
Moro

Reputation: 49

You could set the file browser window to only display the file type you want to user to select, but they can get around that rather easy by selecting the type drop down box. You could however on file select (user clicks OK to select the file and close the file browser window) check to see if the file extension is one of the types you desire and if it is not simple clear the file path variable and call the file browser open function again. That way they are trapped in selecting a file until they select the correct file type. This does however present the issue of them possible no knowing why they are back where they started from, so you may want to add a popup window or something before reopening the file browser window to make it a little more user friendly.

Upvotes: 0

Related Questions