How to Use Watermarkd: A Batch Watermarking Library with GUI

What is watermarking?

Watermarking is a technology of printing less opaque text or symbols on images and items. Believe it or not it’s considered an ancient technology as old as paper since it’s been used on special letters, stamps and printed currency.

As digital imaging has never been such a humongous part of humans’ lives, the usage, creation and demand related to digital images rises as well. Despite the rise of open source and sharing mentality in the digital community, there seems to still be significant room for watermarking applications and so the demand for innovation continues.

Star shaped watermarks among with other patterns on 100 Euro banknote

Why Watermarkd?

Watermarkd is a Python library published by Holypython.com under the open source license Apache-2.0.

In this post we will try to demonstrate what can be accomplished with Watermarkd library.

Watermarkd library allows users to handle watermarking operations in Python directly from the terminal or through use of an optional GUI component.

Since it’s specialized only for watermarking tasks, Watermarkd has a very light graphical user interface. You can probably get an image watermarked (or watermarkd!) during the time it takes to start up a major Image Manipulation software.

It has the most commonly used features when it comes to watermarking and expected to cater to 90% or more of the people looking to watermark an image.

How does Watermarkd work?

Currently, Watermarkd library consists of one sole class named Spread which houses two functions that spread out watermark text on image(s):

  • single function: Spread.single() can be used to apply watermark on a single image (photo).
  • batch function: Spread.batch() can be used to apply watermark to multiple images in a folder.
Here are some images created with Watermarkd on the go.
Medical Field Watermarking
Business confidentiality communicated through watermark

Below you can see various usage types of Watermarkd Library under four titles:

– Single Function Usage

– Batch Function Usage

– Single Function Usage with GUI

– Batch Function Usage with GUI

Single Function Usage

Single function can be used in two main ways:

  • through command line without any interface using its parameters
  • through GUI by enabling gui parameter via True boolean.

as simple as passing True argument to gui as below:

single(gui=True)

Let’s first investigate usage scenarios without gui:

import Watermarkd as wmd

wmd.Spread.single(img_path=r"c:/myimage.png")

This code, once executed, will create a watermarkd image on the user’s Desktop. You don’t have to assign gui parameter to False since it’s the default option. So, basically it’s the same thing as this code:

wmd.Spread.single(gui=False, img_path=r"c:/myimage.png")

Also, please note that, when not using gui, the only parameter you have to pass an argument to is img_path, since all the other parameters have default values and hence, they are optional.

Let’s continue to explore other parameters that can be passed to the single function:

 

  • gui, (bool), default False : enables GUI
  • img_path, (string), mandatory parameter :signifies image path
  • wm_text,  (string), default= “Watermarkd”) : Watermark Text
  • wm_trans, (int [1-255]), default= 85 : Signifies Watermark Transparency 
  • font_size, (int), default= 55) : Watermark Font Size
  • font_name, (string), default= “arial.ttf” : Font Type
  • filename, (string), default=”Watermarkd” : File Name for Saving
  • save_to_path, (string), default=”Desktop/watermarkd_” : Saving Folder Path
  • save_to_suffix, (string), default=”.png” : File Type for Saving 
  • output_filename, (default= r”c:/Users/”+user_path+”/Desktop/watermarkd.png”) : File Name For Saving

Here is another example, in which watermark text is assigned to “Inception”:

from Watermarkd import Spread

f = r"c:/Users/ABC/Desktop/film.png"
Spread.single(img_path=f, wm_text="Inception")
Film Making Industry Watermarking

Batch Function Usage

Batch function is very similar to single function with a few subtle differences. First and foremost, it handles a folder of images rather than a single image. 

So, img_path parameter is exchanged with folder_path parameter.

Otherwise the rest of the differences are mainly internal which you can check out in the source code if you like.

from Watermarkd import Spread

Spread.batch(folder_path=r"c:/User/ABC/New_Photos")

This code will read all the images from the given folder New_Photos, and create an output folder named Watermarkd_ in user’s Desktop and save all the watermarked files there with the default values for optional parameters. Check out a list of parameters below for adjusting different values such as: watermark text, font size, font type, file name, path name, transparency etc.

If you check out the source code, most of the variable names are also conveniently borrowed from the single function.

Regarding the inner workings of the batch function, the main thing is: it doesn’t apply the watermarking algorithm to a single image, instead watermarking algorithm and positioning etc are placed inside a for loop which iterates through the images in the given folder.

So, in simpler words, folder is iterated with a for loop, image file name is taken which becomes the img_path similar to single function, then watermarking is applied and then files is saved and next iteration starts with the next file.

Here is another example:

from Watermarkd import Spread

f=r"c:/User/ABC/New_Photos"
Spread.batch(folder_path=f, wm_text="Photographer A. C. Jonah, #927-654-92**")
  • gui, (bool), default False : enables GUI
  • folder_path, (string), mandatory parameter  :signifies folder path
  • wm_text,  (string), default= “Watermarkd”) : Watermark Text
  • wm_trans, (int [1-255]), default= 85 : Signifies Watermark Transparency 
  • font_size, (int), default= 55) : Watermark Font Size
  • font_name, (string), default= “arial.ttf” : Font Type
  • filename, (string), default=”Watermarkd” : File Name for Saving
  • save_to_path, (string), default=”Desktop/watermarkd_” : Saving Folder Path
  • save_to_suffix, (string), default=”.png” : File Type for Saving 
  • output_filename, (default= r”c:/Users/”+user_path+”/Desktop/watermarkd.png”) : File Name For Saving
More Photo Examples:
Model Promoting Holypython.com Watermarked with Watermarkd
Young Model Posing For Photography Agency with Watermarkd
Univeristy of Utah Campus Watermarked with Watermarkd
New Release Poster for Software

Watermarkd Usage: Single Function with GUI

Usage with GUI is pretty straightforward.

  1. Pick an image file
  2. Type your watermark text
  3. Choose a watermark text size. Options are:
    • Normal (by default)
    • Small
    • Large
    • Value: Let’s a custom font value to be entered. Possibly something like ~150 for high rez images where something like 30 might suffice for a low resolution image.
  4. Transparency: This value defines the transparency (or opacity) of your watermark text. 85 is the default value but you can go all the way down to 0 for a completely transparent text (Watermark would be invisible then). 255, the maximum value will create a solid white watermark text (which is more just a white text than watermark since it’s not transparent at all. It can sometimes be useful nevertheless.)
  5. Save as: Different options to save watermarked image as different image types such as:
    1. png (default)
    2. jpg
    3. gif
    4. bmp
  6. Save to: Path or folder that you’d like to save your watermarked image to. You can either type it or choose it with the help of the Path button.
  7. Filename: Filename you’d like to save your watermarked image under.

Once submit is pressed all the inputs from the user get registered and watermarking process starts.

It can last anywhere between miliseconds to a couple of seconds depending on the resolution of the image. (For the very high resolutions you might need to allow 2-3 seconds which also depends on the availability of computation resources.)

Just as GUI is a new dimension for the Python coder, Packaging also is a new dimension that opens up a whole new world of opportunities and skillset.

To activate GUI component all you have to do is:

Spread.single(gui=True)

You don’t have to pass any other arguments to setting parameters since they’ll be overridden after the GUI is executed.

from Watermarkd import Spread

Spread.single(gui=True)
Single Function's GUI Component in Watermarkd

Watermarkd Usage: Batch Function with GUI

Usage with GUI in batch function is also simple and straightforward. It’s mostly overlapping with single function’s steps. Here are the main differences:

  • Pick a folder instead of a single image through the Browse button.
  • At the bottom file name will be used as a seed to generate multiple images with watermark. For instance, if you choose Work as file name, files will be saved as Work1.jpg, Work2.jpg, Work3.jpg etc.

Once submit is pressed all the inputs from the user get registered and watermarking process will start.

It can last anywhere between miliseconds to a couple of seconds per image depending on the resolution of the image. (For the very high resolutions you might need to allow 2-3 seconds per image which also depends on the availability of computation resources.)  After that time watermarked images will be created in the specified folder or default folder if none is specified.

Activate graphical user interface for bath watermarking a folder of images similar to the code in single() function’s case:

from Watermarkd import Spread

Spread.batch(gui=True)
Watermarkd batch function's GUI window

Further Steps with Watermarkd

As much as I’d love to see Watermarkd getting used by people with different backgrounds such as:

  • Photographers 
  • Bloggers
  • Entrepreneurs and Business Owners
  • Students
  • Teachers
  • Media Agencies
  • Artists, Illustrators

I’d also love to see it being checked out as a learning tool for Python packaging and Python coding in general. It has all the ingredients necessary to comprehend packaging in Python.

Besides packaging topics such as: Pypi repository publishing, Github hosting, licensing etc. It also has fundamental coding topics, but nothing too complicated to discourage an intermediate or even beginner coder, such as:

Additionally, it’s pretty simple to understand and demonstrates all the ingredients needed to publish a library on PyPI (Python Package Index), such as:

    • setup.py
    • requirements.txt
    • License
    • Readme.md
    • __init__.py
Every great coder was a beginner at some point. So, don’t be too shy. One step at a time you too can become great, and create great programs,  there is no doubt about it. Some helpful topics to discover can be:

Such topics open up whole new worlds for a programmer to progress towards, you can see them as paths you can take in your journey(Oftentimes you can combine these paths for a great product as well).

Final Thoughts

If you’re a beginner or intermediate programmer go ahead and create a Github account. Maybe create a trivial repository where you take some notes and save some files if you like, just to start getting familiar with the environment.

If you like Watermarkd or Holypython’s work in general, you’re welcome to visit our Github repos as well. You can read the Watermarkd.py source code along with other necessary files there (setup.py, requirements.txt, __init__.py etc.). 

As simple as it is, I hope Watermarkd library serves as a practical solution for people who might need watermarking and I’d love to see it serve educational purposes for coders and developers who never had a chance to explore packaging and publishing topics related to Python.

Thank you so much for visiting.

ps: I’d like to thank creators and contributors of Pillow the Friendly PIL Fork and PySimpleGUI libraries for creating such fantastic libraries and influencing further developments. Also, a huge thank you to Stack Overflow community for sharing so much expert level knowledge and being so kind.

GUI with Python: File Browser and Input Form (PySimpleGUI Part III)

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. 

GUI with Python: Checkboxes and Radio Buttons (PySimpleGUI Part II)

Previously we’ve demonstrated how to create a GUI layout, window, text and buttons with Python in the previous GUI tutorial. (PySimpleGUI Part I). We’ve also seen numerous ways to style them with builtin styles and themes as well as pick colors and adjust sizes for numerous items such as buttons, titles and text.

We’ve also discussed the benefits of jumping into GUI as a coder and that really can’t be emphasized enough.

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

Particularly PySimpleGUI is very very practical. It gets the job done and super simple and straightforward although there are more advanced, complex, complete, customizable and mission oriented GUI libraries out there such as:

  • Kivy (Mobile application oriented)
  • PySide 2
  • Dabo (A Database oriented wxPython repackage)
  • PyGUI
  • Libavg (Media Oriented Applications)

And it consist of features from some of the better known Python GUI libraries such as:

  • Python Tkinter
  • Remi
  • PyQt5
  • wxPython
Let’s continue discovering what we can achieve with PySimpleGUI.

Estimated Time

15 mins

Skill Level

Intermediate

Important Parameters

.CheckBox, .Radio
.Button, .Text, .T
.Window

Libraries

PySimpleGui

Part II: Checkboxes and Radio Buttons (w/ Implementation and Examples)

In this continuation tutorial let’s discover ways to create and read inputs from various very useful GUI items that were briefly mentioned in Part I. These are:

  • Checkboxes
  • Radio Buttons

As you will see these additions will multiply the functional possibilities of tools that can be built by orders of magnitude.

Also, a couple points can seem slightly confusing with the lack of examples and demonstrations but don’t worry we created a tutorial that makes everything clear at first sight and you’ll be able to hit the ground running.

Please note this part is not only about creating checkboxes or radio buttons but also about making them work. Passing key argument to the items will be crucial in this objective as you will see in the examples.

1- Checkbox Example with PySimpleGUI (Python Implementation)

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.Checkbox('My Checkbox', default=True)]

Now let’s create something more complete with it. Let’s start simple. Imagine a Hello World button like in the first tutorial but with a checkbox. If the checkbox is not checked nothing happens and if the checkbox is checked on the user interface, Hello World prints the message.

(A small note here, sometimes PySimple GUI doesn’t register first button presses upon startup so you might want to double press. I wasn’t able to troubleshoot or debug why this glitch happens.)

I’m just using sg.T(“”) as a means to create row margin space and also column margin space. Basically it’s to help center the content.

Otherwise this layout would be enough:

layout = [[sg.Button('Hello World',size=(20,4))],
          [sg.Checkbox('Print On:', default=True)]]

Here is the full code for a centered button with a checkbox which has default False state:

import PySimpleGUI as sg
layout = [[sg.T("")],[sg.T("        "), sg.Button('Hello World',size=(20,4))], [sg.T("")],
          [sg.T("                   "), sg.Checkbox('Print On:', default=True)]]

###Setting Window
window = sg.Window('Push my Buttons', layout, size=(300,200))

###Showing the Application, also GUI functions can be placed here.
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    
window.close()

So far so good. But this is just a pretty GUI. It won’t do anything because we didn’t define anything for it to do. It’s easy but this part is important. You can apply this knowledge to many other GUI items in PySimpleGUI.

Input value can be acquired by adding a key parameter inside items like this:

layout = [[sg.Button('Hello World',size=(20,4))],
          [sg.Checkbox('Print On:', default=False, key="-IN-")]]

When we read the window as:

event, values = window.read()

keys will be stored in the values.

Now, “-IN-“ is this checkbox’ key. We will be able to look up checkbox’ value with this key. Check this out:

This checkbox can particularly be read with:

values["-IN-"]

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif values["-IN-"] == True:
        print("Hello World")

This is likely the most confusing part and I hope it’s clear. If you need to brush your knowledge on topics you can visit these lessons: Python While Loops Lesson and Python Conditional Statements with If, Else, Elif.

Here is a full and functioning code that you can use, it will only print when the box is checked (True boolean state):

PySimpleGUI Checkbox (Checklist Box) Demonstration
import PySimpleGUI as sg
layout = [[sg.T("")],[sg.T("        "), sg.Button('Hello World',size=(20,4))], [sg.T("")],
          [sg.T("                   "), sg.Checkbox('Print On:', default=True, key="-IN-")]]

###Setting Window
window = sg.Window('Push my Buttons', layout, size=(300,200))

###Showing the Application, also GUI functions can be placed here.

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif values["-IN-"] == True:
        print("Hello World")
    
window.close()

2- Radio Button Example with PySimpleGUI

Radio buttons are other useful GUI items that offers options to the user. The main difference is you can select multiple radio buttons. It forces you to opt in for only one of the options in the same group.

Potentially a user may have to make decision like these with radio buttons on a graphical user interface:

Possible Radio Buttons:

  • Big | Small
  • Encrypted | Not encrypted
  • Attachment | No attachment
  • Receipt | No Receipt
  • Private | Public
  • Am | Fm | Longwave | Shortwave
[sg.Radio('Permission Granted', "RADIO1", default=False)],
[sg.Radio('Permission not Granted', "RADIO1", default=True)]

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.

PySimpleGUI Radio Button Demonstration
import PySimpleGUI as sg
layout = [[sg.T("")],[sg.T("        "), sg.Button('Hello World',size=(20,4))], [sg.T("")],
          [sg.T("         "), sg.Checkbox('Print On:', default=True, key="-IN-")],
          [sg.T("         "), sg.Radio('Permission Granted', "RADIO1", default=False, key="-IN2-")],
          [sg.T("         "), sg.Radio('Permission not Granted', "RADIO1", default=True)]]

###Setting Window
window = sg.Window('Push my Buttons', layout, size=(300,300))

###Showing the Application, also GUI functions can be placed here.

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif values["-IN-"] == True and values["-IN2-"] == True:
        print("Hello World")
    
window.close()

Themes (Prettify GUI real quick)

You can also apply predefined color schemes as demonstrated in the Python GUI Tutorial Part I.

This can be done using sg.theme() method in PySimpleGUI. Let’s create a couple of colorful versions for the simple GUI programs we’ve created.

It’s as simple as adding this code after importing the libraries:

sg.theme("DarkBlue15")

(For different theme names check out the first tutorial)

Here is the code, don’t forget to add the event loop, the part that starts with while True:

import PySimpleGUI as sg

sg.theme("DarkBlue15")
layout = [[sg.T("")],[sg.T("        "), sg.Button('Hello World',size=(20,4))], [sg.T("")],
          [sg.T("         "), sg.Checkbox('Print On:', default=True, key="-IN-")],
          [sg.T("         "), sg.Radio('Permission Granted', "RADIO1", default=False, key="-IN2-")],
          [sg.T("         "), sg.Radio('Permission not Granted', "RADIO1", default=True)]]

window = sg.Window('Push my Buttons', layout, size=(300,300))
Python GUI with Dark Blue Color Theme

I really like DarkBlue15, it’s got a “Bios”y look.

And here is Tan:

Python GUI with Tan Color Theme

And finally reddit is really nice with a minimalistic standard look with slightly enhanced color profile and DarkTeal2 theme also looks really sleek:

PySimpleGUI reddit Theme
PySimpleGUI DarkTeal2 Theme

Here are some more ideas to check out:

Black
TealMono
TanBlue
LightGreen1

PySimpleGUI’s themes are really heaven sent if you want to achieve some nice visual results without spending too much time. I feel like lots of programmers, coders, entrepreneurs, especially without the means to hire design team because they are in the beginning of their journey or they simply choose to perform solo fit in this group.

It really helps to get maximum visual results with minimum time and effort when you are on a tight budget time and resource wise.

Closing Thoughts (Summary and What's Next)

We have demonstrated checkboxes and radio buttons in PySimpleGUI which is a great Python GUI library that really packs a punch especially given its minimalist structure.

Also, this tutorial was about how to get input and how to use GUI input in the code. This is a crucial knowledge that adds many new dimensions to a beginner programmer’s toolset.

Imagine those game or app installation user interfaces. You could pretty much achieve any installation UI with the Python knowledge provided in Part I (buttons, text, theme, size, alignment settings) and Part II (checkboxes, radio buttons, reading user input) of Python GUI tutorial series.

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

Python Simple File Browser GUI with PySimpleGUI

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 II of Python PySimpleGUI GUI tutorial series.

Thank you for visiting!

Please share this post if you found it useful. 

How to Schedule Tasks with .py Files (Python): Manual and Automated

There are multiple ways to schedule a Python program, task, event or script in Windows Operating System.

In this Python tutorial we will demonstrate various different methods that can be helpful for scheduling tasks or events:

  • Manually creating a scheduled event (Windows Task Scheduler)
  • Automated Task Scheduling via Pywin32 library

How to Schedule Python w/ Windows Task Scheduler (Manual Way)

This is pretty simple to achieve but there are some details to consider.

  1. Write a Python program that works.
  2. Save your Python program as a .py file.
  3. Open Windows Task Scheduler

1- Let’s create a really simple Python program.

I’ll simply print Hello World! But also, I’ll do a little trick here by using time library as well.

If we don’t create a delay function program will run in a tiny fraction of a second and disappear so it will be hard to observe. So, let’s add a 10 second sleep time after the print function.

Estimated Time

15 mins

Skill Level

Upper-Intermediate

Modules

.Dispatch
.Connect, .GetFolder
.NewTask

Libraries

win32com, os
win32com.client

Tip Jar

Buy Us a Ko-Fi

Thank you! 😊🙏

import time
print("Hello World!")
time.sleep(10)

We have a simple but decent program for demonstration already. Let’s move on to saving file as .py step.

2- Saving a file as .py file is easy. One needs to simply navigate to file tab in any IDE.
From there, 

Saving .py file with Spyder IDE

Another way to create a .py file is simply using Notepad from Windows, especially when the code is this simple it’ll work like a charm.

However, there is something you gotta pay attention to:

You gotta make sure save as type: section of the window is at “All Files(*.*)” otherwise whatever you type Notepad will add .txt to the end of the file and you will end up with something like: test.py.txt.

We don’t want that, we want test.py only (Replace test with whatever name you want). So just make sure type is set to All Files like below.

Saving .py file with Notepad

3- Now, it’s time to schedule the application we created. Simply Navigate to Start of Windows and type Task Scheduler. Then, Go ahead and open the app.

Task Scheduler

3- Now, it’s time to schedule the application we created. Simply Navigate to Start of Windows and type Task Scheduler. Then, Go ahead and open the app.

Task Scheduler - Create Task

You’ll see Actions section on the right side. Click Create Task to create a new task.

A new window will pop up and you’ll need to take care of 3 things there. This is the final step. 3rd step is important to understand and get it right for the program to execute properly when it’s due.

  1. Give your task a name
  2. Choose a trigger (such as time or upon logging in etc.)
  3. Create new Action (Choose Python.exe and Program you created.)
So first step, as well as second step, is I believe self-explanatory. For trigger, just create new and maybe choose a one time trigger for a couple minutes later for demonstration. If your current time is 10:00pm you can try 10:05pm.

On the final step, when creating trigger 

  • program/script will be your Python.exe path
    • This part is usually wherever your Python is installed. If you have Anaconda it’s likely something like:
    • C:\Anaconda3\python.exe or D:\Anaconda3\python.exe
  • argument will be the path to the code you have saved as .py file.
    • This depends where you’ve saved your file. Path can be something like:
    • C\Users\ABC\Desktop\test.py

So, basically what’s happening here is that you’re scheduling Python.exe to run as a program and then you’re passing your own program, script, task, code or whatever you wanna call it as an argument to Python.exe.

Since, we have created a 10 second delay in the code. Hello World! will beautifully appear on the screen for 10 seconds. Plenty of time for you to feel accomplished.

Task Scheduler - Task is executed on time

As a practice, I recommend doing this whole operation by yourself after reading this Python tutorial. Also, for the first time you can save your code with print(“Hello World!”) only to observe the phenomenon that we’ve mentioned above. In that case your code will flash for a tiny moment and disappear before you have a chance to read it.

How to Automate Task Scheduling w/ Python (pywin32 library)

We can directly connect to Windows Task Scheduler from Python via pywin32 library. This can be very powerful if you want to finish everything from inside Python.

Another time it can be very useful is when your Python program has a GUI and you don’t want the user to go to Task Scheduler separately to schedule events. 

Think applications like 

  • alarm clock,
  • maintenance,
  • cleaning,
  • reminder,
  • update checker,
  • reporter,
  • email sender,
  • financial market checker,
  • database updater
  • etc. -anything that might make sense to schedule.

So, how are we going to achieve this noble goal? By using pywin32 library. Below, you can see an example that you can actually directly modify and implement. This application is consisted of 6 basic steps:

  1. Importing necessary libraries: win32com.client from pywin32 and  datetime for tracking or expressing time data.
  2. Creating a connection to the Task Scheduler Client: Also includes the handle for the new task.
  3. Creating the trigger: This is where we decide what kind of trigger we want for the task (Typically a specific time or event such as logging in)
  4. Creating the action: This is where we introduce our program to the Task Scheduler. Since this one will be a .py file, we need to pass 2 values, this is important to get right.
    • action.Path will be the path to python.exe
    • action.Argument will be the path to the .py file
  5. Additional parameters such as description will be passed.
  6. Our task is fully ready to be saved. This step will finalize the process and add the task to the Task Scheduler. (You may wanna close the Task Scheduler Window if it’s already opened manually to avoid any conflict although this script will still add the task which may not show up on the open window.)
#Import Libraries
import datetime as dt
import win32com.client
#Connection to Task Scheduler
task = win32com.client.Dispatch('Schedule.Service')
task.Connect()
root_folder = task.GetFolder('\\')
newtask = task.NewTask(0)
# Trigger
set_time=dt.datetime(2020,9,4,18,44,0,500000)
TASK_TRIGGER_TIME = 1
trigger = newtask.Triggers.Create(TASK_TRIGGER_TIME)
trigger.StartBoundary = set_time.isoformat()

set_time variable is used to define the exact time task is being scheduled to. So, you can adjust the first line accordingly.

Alternatively, you can schedule time to something like “5 minutes from now” or “2 hours from now” or “same time tomorrow”. Just refer to this code snippet for that:

set_time = dt.datetime.now() + dt.timedelta(minutes=1)

# Action
TASK_ACTION_EXEC = 0
action = newtask.Actions.Create(TASK_ACTION_EXEC)
action.ID = 'DO NOTHING'
action.Path = r'C:\Anaconda3\python.exe'
action.Arguments = r'C:\Users\ABC\Desktop\new3.py'

action.Path is the path to your python.exe file. If you have Anaconda3 installed it should be something like above, you might want to double check your Python or Anaconda installation.

action.Argument is the path to whatever .py file you’re trying to schedule.

Basically we’re passing the .py file as an argument to python.exe program. python.exe is the actual program being scheduled here and program (or task or code or event or script) in the .py file is being passed as an argument.

You can adjust the Task Description according to your task.

# Parameters
newtask.RegistrationInfo.Description = 'Python Task Test'
newtask.Settings.Enabled = True
newtask.Settings.StopIfGoingOnBatteries = False

Finally, task gets saved in this step, 

  • First argument in the .RegisterTaskDefinition() method is the name of the task. Here we’re using “PTT” (short for Python Task Test) as name, it can be anything you want.
  • Second argument here is newtask. This is the task we have been constructing (has action data, trigger data, description data etc.)
  • We also have username and password sections when needed (Possibly when saving a task for another user). In this case, these arguments are empty.
# Saving
TASK_CREATE_OR_UPDATE = 6
TASK_LOGON_NONE = 0
root_folder.RegisterTaskDefinition(
    'PTT',  # Python Task Test
    newtask,
    TASK_CREATE_OR_UPDATE,
    '',  # No user
    '',  # No password
    TASK_LOGON_NONE)

That’s all. This code should work from the get go with a few basic adjustments. You can find the full code on HolyPython Github Repository here.

If you’re interested in combining this knowledge with a GUI application you created with Python you can check out this tutorial about GUI applications with Python.

Creating GUI Programs w/ Python: Fast & Easy (PySimpleGUI PART I)

If you’re looking to take your coding journey to next level, or if you’re specifically looking for a leap into GUI, jackpot! I will share with you the nicest, coolest, most practical GUI solution for Python.

I really think GUI adds a new dimension to the code and the coding as a learning journey. This can help you step up your programming in a way that it offers so many new benefits directly and indirectly!:

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

  • Your code doesn’t look like some weird output that’d only be used in Matrix triology.
  • You can have your program used via:
    • radio buttons
    • checklists
    • menus
    • dropdown lists
    • value wheels
    • value bars etc.
  • You can actually call your code a program
  • You can tap into a new source of imagination since things start getting visual
  • You can decide on the level of GUI (you don’t have to get super visual, it’s up to you and your program)
  • More opportunities to have your code used by a wide range of people from different backgrounds.
  • Pretty graphs
  • Games
  • Monetization of your code / program / software (You can actually create a product or service that can be marketed and sold)

Estimated Time

15 mins

Skill Level

Intermediate

Important Parameters

.Button, .Window
.Text, .T, .theme

Libraries

PySimpleGui

GUI is a huge step forward in anyone’s coding journey.

I think if we consider a cost/benefit ratio for GUI methods where cost is the learning effort and time and benefit is the potential outcome opportunities, I must say ratio is very very high.

GUI adds a whole new dimension to coding that enables you to create buttons, menus, lists, checklists, messages, boxes, layout design etc. This obviously makes your code actually usable by a marginally larger demographics but I’d like to argue that benefits are even bigger than just other people being able to use your code.

When you start creating GUI applications, you might start to realize that you’re tapping into a new creativity resource with that visual experience. Albert Einstein says: Imagination is everything. GUI sort of boosts imagination and lets you get hand-onsy with code.

Now historically, GUI also had limitations and there were also limited amount of libraries. This could make GUI learning curve pretty steep for Pythonistas.

This doesn’t have to be the case. In this article We’re going to share with you the most straight-forward, practical GUI technology that you can start implementing right away without losing your precious hair.

Let’s get started.

Simple GUI Example (Getting Started)

Let’s create a layout and a button in it. We’ll do this in 4 baby steps:

  • We’re gonna import the necessary library
  • We’ll create a layout in list format with brackets: [ ]
  • We’ll use sg.Button() method and put it inside the layout.
  • Then we’ll create a window using sg.Window() which takes
    1. a title string
    2. layout object

1- Import the PySimpleGUI library:

If you don’t have PySimpleGUI library you can simple install it by executing the following command in Anaconda Command Prompt (or Command Prompt):

pip install pysimplegui

import PySimpleGUI as sg

2- Create a layout with a button in it.

layout = [[sg.Button('Hello World')]]

3- Create the window with a title and the layout we created earlier:

window = sg.Window('Push my Buttons', layout)

4- Reading the window to make it show up:

event, values = window.read()
First GUI Application

You’ll get a window like this. Now, we’ve already created the first GUI application. Let’s build up the tutorial for a few more interesting points.

GUI Size Settings (Layout Size, Button Size, Font Size etc.)

You can simply add tuples of size parameters to both the sg.Button and sg.Window.
It works so: size(width, height)

Here is the full code so far with a couple of size parameters added:

import PySimpleGUI as sg
layout  = [[sg.Button('Hello World', size=(20,4))]]
window = sg.Window('Push my Buttons', layout, size=(200,150))
event, values = window.read()
First GUI Application

Boom! Our GUI window is instantly starting to look better. But there are more cool tricks to check out.

GUI Alignment Tricks (Row Alignment, Column Alignment)

You can simply add sg.T or sg.Text methods to add a text or add blank strings to move the buttons Left and Right:

layout = [[sg.Text("Primary Button: "), sg.Button('Hello World',size=(20,4))]]
window = sg.Window('Bunch of Buttons', layout, size=(270,100))
PySimpleGUI Button Horizontal Alignment

It looks like this.

So, here is the trick, inside the same bracket we’re altering the same row. Create new brackets and you’ll be creating new rows which can be used to alter column alignment. Let’s use sg.T this time and a string with blanks to create space above the button:

Note: Also pay attention to the windows size we’re changing that to create a more suitable window for the layout.

layout = [[sg.T("")], [sg.Button('Hello World',size=(20,4))]]
window = sg.Window('Push my Buttons', layout, size=(210,150))
PySimpleGUI Button Vertical Alignment

Now it looks like this. Including the text inside a new bracket created a new row above the button.

Themes (Prettify GUI real quick)

PySimpleGUI has great color themes that you can apply to your program to make things a little more colorful (or sometimes less)

These theme colors are really well prepared and makes styling so much easier.

We will use sg.theme() method to implement various colors to the GUI window.

I find reddit color scheme really sleek. Let’s take a look at that:

import PySimpleGUI as sg
sg.theme('Reddit')
layout = [[sg.Text("Primary Button: "), sg.Button('Hello World',size=(20,4))]]
window = sg.Window('Push my Buttons', layout, size=(270,100))
event, values = window.read()
PySimpleGUI Reddit Theme

Here is a look at LightYellow, DarkBlue15, Tan, DarkTeal2, Topango, LightBrown5.

PySimpleGUI LightYellow Theme
PySimpleGUI DarkBlue15 Theme
PySimpleGUI Tan Theme
PySimpleGUI DarkTeal2 Theme
PySimpleGUI Topango Theme
PySimpleGUI LightBrown5 Theme

Here are some more ideas to check out:

Black
TealMono
TanBlue
LightGreen1
LightGreen2
LightGreen3
LightGreen4
DarkBlue15
Tan
SystemDefault
LightBlue5
LightBrown

DarkPurple
DarkGreen
LightPurple
LightGrey
Green
Dark
BrownBlue
BrightColors
BlueMono
BluePurple
DarkRed
DarkBlack

You can check out all the color themes here.

How to tie buttons to functions? (Action time)

Now, if you’re creating buttons you’ll likely want them to execute something. That’s the whole point right. We can simply create user defined functions or map Python’s builtin functions to the buttons we create with the PySimpleGUI library.

So, mapping buttons to functions is not that complicated. You just need some basic loop knowledge in Python.
Please feel free to these materials if you need to polish your For Loop and While Loop knowledge.

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    elif event == 'Hello World!':
        print("Hello World!")

So what’s going on in this code snippet?

  • Firstly, everything is structured inside an infinite while loop. This way GUI interface is continuously monitored and executions are carried out when needed.
  • GUI windows is being monitored with .read() method. This means every time a button is pressed or a selection is made those values can be interpreted by the program.
  • if statement ensures that program is closed when close button is pressed. This is achieved by break statement. If you need a primer on that we have a great lesson focusing on break statement and its cousin try/except statement can be useful as well.
  • elif statements manage each action that needs to be done when event equals buttons name. This is stated as:
    elif event == "Hello World!":

Closing Thoughts (Conclusion)

That’s about it. Now, regarding a GUI application you know how to create these:

  • layout,
  • window,
  • buttons,
  • text(s),
In addition you know how to:
  • resize GUI window, button and text
  • align GUI objects vertically and horizontally
  • spice up the color scheme with PySimpleGUI themes
  • read from the GUI application
  • and map buttons to functions or various code.

You can apply this knowledge to create multiple buttons and text as well as other interesting object that’s usually included in software such as:

  • sliders
  • radio buttons
  • checklist buttons
  • dropdown menus
  • forms etc.
Here is a simple application with multiple buttons that prints a unique message on the console when each button is pressed.
PySimpleGUI Topango Theme

And here is the full code:

import PySimpleGUI as sg
sg.theme('LightYellow')

layout  = [[sg.T("")],[sg.Button('Hello World!',size=(20,4))],[sg.Text("  ")],
[sg.Button('Winter Olympics 2022 (Beijing)'), sg.Button('Summer Olympics 2021 (Tokyo)')],[sg.Text(" ")],
[sg.Button('Fifa World Cup 2022 (Qatar)'), sg.T(" "*2),sg.Button('Tour de France')]]

window = sg.Window('Bunch of Buttons', layout, size=(420,250))
event, values = window.read()

##########Button Functions##########
while True:             # Event Loop
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    elif event == 'Hello World!':
        print("Hello World!")      # call the "Callback" function
    elif event == 'Winter Olympics 2022 (Beijing)':
        print("Winter Olympics 2022 (Beijing)")
    elif event == 'Summer Olympics 2021 (Tokyo)':
        print("Summer Olympics 2021 (Tokyo)")
    elif event == 'Tour de France':
        print("Tour de France")
    elif event == 'Fifa World Cup 2022 (Qatar)':
        print("Fifa World Cup 2022 (Qatar)")

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

I’m so happy to create this tutorial because it can really help people from all backgrounds step up their programming skills and outcomes as a result of it. It also takes 5-10 minutes to learn and maybe a couple hours to master. Then you have a whole new skill-set to make use of your basic programming skills.

This was a simple GUI tutorial for Python using PySimpleGUI library.

You can also check out this tutorial about Task Scheduling with Python’s .py files which goes hand in hand with GUI applications sometimes.

Please share this post if you found it useful. Thank you!