Below is a Browse class that lets the user browse files and show the path in an entry frame. This is pretty short and basic.

import tkinter as tk
from tkinter import filedialog as fd

class Browse(tk.Frame):
    """ Creates a frame that contains a button when clicked lets the user to select
    a file and put its filepath into an entry.

    def __init__(self, master, initialdir='', filetypes=()):
        self.filepath = tk.StringVar()
        self._initaldir = initialdir
        self._filetypes = filetypes

    def _create_widgets(self):
        self._entry = tk.Entry(self, textvariable=self.filepath)
        self._button = tk.Button(self, text="Browse...", command=self.browse)

    def _display_widgets(self):
        self._entry.pack(fill='x', expand=True)

    def browse(self):
        """ Browses a .png file or all files and then puts it on the entry.


if __name__ == '__main__':
    root = tk.Tk()

    file_browser = Browse(root, initialdir=r"C:\Users",
                                filetypes=(('Portable Network Graphics','*.png'),
                                                            ("All files", "*.*")))
    file_browser.pack(fill='x', expand=True)


Review Concern(s):

  • My main concern is to code in an easy to read, efficient, and well-structured manner while still learning the language and concepts such as OOP. Feel free to mention the tiniest issue or improvement that comes to your mind, as I am a beginner and I probably need it.

1 Answer 1


I think it looks pretty good.

Personally I wouldn't use a StringVar, unless part of the goal was to allow the caller to link this variable to some other widget. Often, the use of StringVar just adds another object to keep track of without providing much of a benefit in return, since you can easily set the value of an entry or label widget without it.

I also personally find it a bit easier to define the file types as a variable since it can be cumbersome to squeeze a bunch of file types into the list of parameters. In this case it's not too bad, but you might want to consider doing it like this:

filetypes = (
    ('Portable Network Graphics','*.png'),
    ("All files", "*.*")
file_browser = Browse(root, initialdir=r"C:\Users",
  • \$\begingroup\$ Thanks for your review. I actually didn't initially use a StringVar too, based on your suggestions in a question. Then I wanted to use it so that if the user manipulated the content of the entry with keyboard self.filename would be in sync. I thought it would be misguiding to give the user an entry that they can edit and then have no account for that edit. \$\endgroup\$
    – Nae
    Jan 8, 2018 at 22:49
  • \$\begingroup\$ That makes sense. \$\endgroup\$ Jan 8, 2018 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.