We’ve been discovering practical Python GUI features in Part I and Part II.

In those GUI tutorials with Python, we’ve covered:

  • Python GUI Tutorial Part I:
    • layout
    • window
    • buttons
    • text
    • text size, window size
    • object alignment
    • color themes
  • Python GUI Tutorial Part II:
    • checkboxes
    • radio buttons
    • using GUI input in code
    • event loop to show the GUI window and get inputs

Holy Python is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Part III: File Browsers, Folder Browsers and Input Forms

Part III of the Tutorial will build on previous topics and also introduce:
  1. file browser
  2. folder browser
  3. input form

This is another crucial piece of the common GUI features. Using a File Browser (or Folder Browser) you can get the path of a file and point it to the code. Of course it can be domain or project specific but usage of these features is extremely common. Here are some possible examples:

Estimated Time

15 mins

Skill Level

Intermediate

Important Parameters

.FileBrowse, .Text
.FolderBrowse, .Window
.Input, .theme

Libraries

PySimpleGui

Game Developer Testing Results
  • Image Processing
    • Opening Images
    • Saving Images
    • Opening Effect Folder
  • Data Science
    • Raw Data Files for Input
    • Path to Save Analysis Results
    • Reporting
    • Path to Save Visualization (Graphs and Charts)
  • Game Development
    • Game Installation Path
    • Game Saving Path
  • Web Development
    • Saving Files Locally
    • Inserting Images or Videos
  • Finance
    • Saving Report Files
    • Opening Market Price Data
    • Saving Visualization
  • Medical Research
    • Image Files and Folders
    • Raw Data Files and Folders
    • Trained Model Input
  • Computer Vision
    • Path for Saving Video or Images
    • Trained Models (Faces, Lanes, Objects etc.)
  • Scripting
    • Paths for Windows Applications (or other OS)
    • Paths for Saving Files
    • Paths for Opening Files
So, it might seem a bit repetitive and limited but there is a use case in almost every field for file browsing especially regarding User Interface.
Let’s see how we can create file / folder browsers in Python with PySimpleGUI library.
Medical Doctor Working on her computer

Python File Browser GUI

We’ve covered key parameter to read input from GUI items in Python using PySimpleGUI.

We can apply the same knowledge to file and folder browsers. key parameter will be used to read the path of the selected file or folder in this case.

Creating file browsers in Python is pretty easy with PySimpleGUI. Here is a piece of code:

[sg.FileBrowse()]

 

1- File Browser Example with PySimpleGUI & Python

Often, software requires additional input from the user and main mechanisms are coded to be able to respond to those preferences. In this case, boolean selection items such as radio buttons or checklists become incredibly useful. In principal:

  • Radio buttons are used when either one of the options must be selected
  • Checklist boxes are used when either one or more options can either be checked or left unchecked.

In either case the options will be represented as True or False based on the input and this can be used as input to your code and particularly conditional statements in your code. There are probably infinite cases but some examples from the top of my head are:

Possible Checklist Boxes:

  • Red | Green | Blue | Black | White
  • Italic | Bold | Underline | Strike

These are just some simple probable examples from real life.

So let’s get to the juicy part, how do we actually create them and you’re not done once they are created, how to interpret / implement their input in the code.

Let’s build on the things we’ve accomplished in the first tutorial. (If you need a refresher on layout or  window check out Part I.)

Creating checkbox or checklist box with PySimpleGUI is easy. Here is the little piece of code you need. You can assigne a title and a default boolean state (here  it’s True).

[sg.FileBrowse()]

Now, let’s implement it in a layout and create a GUI window with it.

layout = [[sg.Text("Choose a file: "), sg.FileBrowse()]]

This can be the layout. There is a nice descriptive text before the file browse object. We can create a window with it as following:

window = sg.Window('My File Browser', layout, size=(300,200))
Python GUI File Browse Button

This is already cool enough and using key parameter we can start reading the file path. But, let’s also add an input field to optimize the visual experience. Once user selects a file, this input field will show the path in writing. It’s as simple as adding:

sg.Input()

Here is a complete code minus the “event loop” (the part that shows the GUI with an infinite loop and also reads values from the GUI window).

layout = [[sg.Text("Choose a file: "), sg.FileBrowse()]]
import PySimpleGUI as sg
sg.theme("DarkTeal2")
layout = [[sg.T("")], [sg.Text("Choose a file: "), sg.Input(), sg.FileBrowse()]]

###Building Window
window = sg.Window('My File Browser', layout, size=(600,150))

There are 2 rows in this GUI. First one consists of an empty string via sg.T(“”).

And second row consists of descriptive text, input field and file browser. (Browse button)

Wait, what? We just started and the main chunk of the tutorial is almost finished. Yes, that’s pretty much it. Can you believe how simple and straightforward it was and you can actually make sense of the code as a human. Even if you’ve never coded in your life, you could probably decode this piece of sophisticated but minimalist code with an analytical mind.

PySimpleGUI achieves something very elegant which can be described as Zen Of Python. That’s why I believe this Python GUI library is really big deal. It appears so simple yet it’s so powerful.

Let’s start reading the input and also add an event loop with an infinite while loop.

Python GUI File Browse Button with Input Field

Like in the previous tutorials, we’ll add this assignment to read from the window:

event, values = window.read()

We can also take advantage of the key parameter inside the File Browser object to read the path value, assign it to any variable we’d like and use it in the code. If you construct the FileBrowse object like this:

sg.FileBrowse(key="-IN-")

It’s value will be readable making this call:

values["-IN-"]

Check out the example:

import PySimpleGUI as sg
sg.theme("DarkTeal2")
layout = [[sg.T("")], [sg.Text("Choose a file: "), sg.Input(), sg.FileBrowse(key="-IN-")],[sg.Button("Submit")]]

###Building Window
window = sg.Window('My File Browser', layout, size=(600,150))
    
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif event == "Submit":
        print(values["-IN-"])

I’ve just added a button so if you click that button it prints the value read from the File Browser.

In computer language, if event is that button, it will print whatever we specify it to print.

Also note that File Browser object has a key parameter passed to it which has a value of: "-IN-"

2- Folder Browser Example + Simultaneous Reading

Folder Browser is pretty much the same thing. Instead of sg.FileBrowse("");

use: sg.FolderBrowse("")

However, I’d like to introduce another very cool function: simultaneous or instantaneous reading of values. This is also very simple and straightforward and can be achieved with one parameter:

 change_submits=True

Again, this is big deal. Using this functionality you can create GUI programs that immediately execute something as an item’s input changes. Makes everything even more exciting.

Let’s make a demonstration.

We already have an input field that changes every time something is selected via browser button. We can add a key parameter to this item and then we can add the change_submits parameter to it as well and assign it to True boolean.

This way, we can add a simple print function in our event loop to print the new value every time a path is selected.

Here goes:

import PySimpleGUI as sg
sg.theme("DarkTeal2")
layout = [[sg.T("")], [sg.Text("Choose a folder: "), sg.Input(key="-IN2-" ,change_submits=True), sg.FolderBrowse(key="-IN-")],[sg.Button("Submit")]]

###Building Window
window = sg.Window('My File Browser', layout, size=(600,150))
    
while True:
    event, values = window.read()
    print(values["-IN2-"])
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif event == "Submit":
        print(values["-IN-"])

The differences from the previous example are:

  • sg.FolderBrowse replaced sg.FileBrowse
  • sg.Input() object has 2 parameters:
    • key
    • change_submits
  • values of input field are being printed directly inside the While Loop
  • submit button is still there but it’s not necessarily demonstrating anything in this example.
  • Also, text is corrected as “Please select a folder”

We can print just by selecting a path so we’re not even using the Submit button here.

Also, sg.FolderBrowse won’t let you select a file. You can only navigate to paths and then make a selection which will be a folder path.

PySimpleGUI Folder Browse with Simultaneous Input Value Reading

Code for radio buttons in PySimpleGUI is also easy.

  • First parameter is the radio button’s title.
  • Second parameter is the radio button’s group. (Only one button in the same group can be selected)
  • Third parameter is its default state. ()

Let’s build on the first example. Let’s say it only prints if the checkbox is checked plus if the “Permission Granted” radio button is selected.

I’m defining keys as -IN-, -IN2- to have a system. You can assign pretty much any string value to them.

Python Simple File Browser GUI with PySimpleGUI

You can also create something like this with the Exit button by combining the knowledge from the first part of the tutorial about buttons.

Closing Thoughts and Summary

Wow, I can’t get over how simple and impressive PySmipleGUI is. We’ve accomplished a lot in this tutorial with very simple and readable code pieces. We have:

  • Created File Browse item
  • Created Folder Browse item
  • Created Input Fields in both examples
  • Discovered Simultaneous or Instant value reading from GUI objects.

I hope this knowledge can help someone bridge the gaps in their code, act as a stepping stone for new knowledge and exciting new projects.

GUI really compliments a coder’s work so well. Code suddenly becomes a product or software and something just more presentable. Achieving this without having to deal with complicated GUI code in a practical fashion is something I’m sure many programmers will instantly appreciate.

Additionally, GUI is even useful for the coders themselves in many occasions just to make the project a little bit more visual, to get ideas or to manage certain aspects of a project better.

In the next tutorial (Part III) we will discover Browser Features and how to make use of it with code implementation examples in Python.

You can also find the complete  code in this page via this link: HolyPython Github repositoryYou can also find the official repository page of PySimpleGUI library here.

This was Part III of Python PySimpleGUI GUI tutorial series.

Thank you for visiting!

Please share this post if you found it useful. 

Recommended Posts