Home > Blockchain >  Tkinter Python Filedialog Certain Files Only?
Tkinter Python Filedialog Certain Files Only?

Time:09-27

So I was messing around with the python keyboard module and then I wondered how do I make a file dialog popup when you pressed ctrl S so I searched stack overflow I quickly found out how to with:

from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

But what I want to know is how can I filter out the files by like *.txt or *.py with the same method. So if anyone has an answer please tell me.

CodePudding user response:

askopenfilename can get many arguments - ie. start folder, list to create menu to select different files, etc.

You should find it in any tutorial for askopenfilename

askopenfilename(filetypes=[('Text', '*.txt'), ('Python', '*.py')] )

You can also use without *

filetypes=[('Text', '.txt'), ('Python', '.py')]

Or more complex

filetypes=[('A-Text', 'a*.txt'), ('B-Text', 'b*.txt')]

Minimal working code

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename(filetypes=[('Text', '*.txt'), ('Python', '*.py')] )

if file_path:
    print(file_path)
    
else:
    print('Not selected')
  • Related