How to do it...

The first button of our application will trigger a call to the askopenfilename function, whereas the second one will call the askdirectory function:

import tkinter as tk
import tkinter.filedialog as fd

class App(tk.Tk):
def __init__(self):
super().__init__()
btn_file = tk.Button(self, text="Choose file",
command=self.choose_file)
btn_dir = tk.Button(self, text="Choose directory",
command=self.choose_directory)
btn_file.pack(padx=60, pady=10)
btn_dir.pack(padx=60, pady=10)

def choose_file(self):
filetypes = (("Plain text files", "*.txt"),
("Images", "*.jpg *.gif *.png"),
("All files", "*"))
filename = fd.askopenfilename(title="Open file",
initialdir="/", filetypes=filetypes)
if filename:
print(filename)

def choose_directory(self):
directory = fd.askdirectory(title="Open directory",
initialdir="/")
if directory:
print(directory)

if __name__ == "__main__":
app = App()
app.mainloop()

Since these dialogs can be dismissed, we added conditional statements to check whether the dialog function returns a non-empty string before printing it into the console. We would need this validation in any application that must perform an action with this path, such as reading or copying files, or changing permissions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset