2020 - Updates are in Progress

It's been a little while getting back around to the Cookbook. As a result, some of the information was using older design patterns and some better examples need to be included. There have been about 1/3 of the changes made so far that need to get made, so be patient.

The PySimpleGUI Cookbook

Welcome to the PySimpleGUI Cookbook! It's provided as but one component of a larger documentation effort for the PySimpleGUI package. It's purpose is to give you a jump start.
You'll find that starting with a Recipe will give you a big jump-start on creating your custom GUI. Copy and paste one of these Recipes and modify it to match your requirements. Study them to get an idea of some design patterns to follow.

This document is not a replacement for the main documentation at http://www.PySimpleGUI.org. If you're looking for answers, they're most likely there in the detailed explanations and call defintions. That document is updated much more frequently than this one.

See the main doc on installation. Typically it's pip install pysimplegui to install.

The "Demo Programs" Are Also Recipes

If you like this Cookbook, then you'll LOVE the 200 sample programs that are just like these. You'll find them in the GitHub at http://Demos.PySimpleGUI.com. They are located in the folder DemoPrograms and there is also a Demo Programs folder for each of the PySimpleGUI ports.

These programs are updated frequently, much more so than this Cookbook document. It's there that you'll find the largest potential for a big jump-start on your project.

So, for example, if you're trying to use the Graph Element to create a line graph, check out the demo programs... there are 8 different demos for the Graph Element alone.

Trinket, the Online PySimpleGUI Cookbook

More and more the recipes are moving online, away from this document and onto Trinket. http://Trinket.PySimpleGUI.org

You'll find a number of "recipes" running on Trinket. The PySimpleGUI Trinket Demo Programs are often accompanied by explanatory text. Because it's an actively used educational capability, you'll find newer PySimpleGUI features demonstrated there.

The advantage to "live", online PySimpleGUI demos is that you can examine the source code, run it, and see the GUI in your browser window, without installing anything on your local machine. No Python, no PySimpleGUI, only your browser is needed to get going.

The PySimpleGUI repl.it repository is also used, but it doesn't provide the same kind of capability to provide some explanatory text and screenshots with the examples. It does, however, automatically install the latest version of PySimpleGUI for many of the examples. It also enables the demo programs to access any package that can be pip installed. Trinket does not have this more expansive capability. Some older demos are located there. You can run PySimpleGUIWeb demos using Repl.it.

Cookbook Purpose

A quick explanation about this document. The PySimpleGUI Cookbook is meant to get you started quickly. But that's only part of the purpose. The other, probably most important one, is coding conventions. The more of these examples and the programs you see in the Demo Programs section on the GitHub, the more familiar certain patterns will emerge.

It's through the Cookbook and the Demo Programs that new PySimpleGUI constructs and naming conventions are "rolled out" to the user community. If you are brand new to PySimpleGUI, then you're getting your foundation here. That foundation changes over time as the package improves. The old code still runs, but as more features are developed and better practices are discovered, you'll want to be using newer examples and coding conventions.

PEP8 names are a really good example. Previously many of the method names for the Elements were done with CamelCase which is not a PEP8 compliant way of naming those functions. They should have been snake_case. Now that a complete set of PEP8 bindings is available, the method names are being changed here, in the primary documentation and in the demo programs. window.Read() became window.read(). It's better that you see examples using the newer windows.read() names.

In short, it's brainwashing you to program PySimpleGUI a certain way. The effect is that one person has no problem picking up the code from another PySimpleGUI programmer and recognizing it. If you stick with variable names shown here, like many other PySimpleGUI users have, then you'll understand other people's code (and the demos too) quicker. So far, the coding conventions have been used by most all users. It's improved efficiency for everyone.

Keys

Keys are an extremely important concept for you to understand. They are the labels/tags/names/identifiers you give Elements. They are a way for you to communicate about a specific element with the PySimpleGUI API calls.

Keys are used to:

inform you when one of them generates an event

change an element's value or settings

communicate their value when performing a window.read()

Important - while they are shown as strings in many examples, they can be ANYTHING (ints, tuples, lists, objects, ....)

Keys are specified when you create an element using the key keyword parameter. They are used to "find elements" so that you can perform actions on them.

GETTING STARTED - Copy these design patterns!

All of your PySimpleGUI programs will utilize one of these 2 design patterns depending on the type of window you're implementing. The two types of windows are:

One-shot

Persistent

The One-shot window is one that pops up, collects some data, and then disappears. It is more or less a 'form' meant to quickly grab some information and then be closed.

The Persistent window is one that sticks around. With these programs, you loop, reading and processing "events" such as button clicks. It's more like a typical Windows/Mac/Linux program.

If you are writing a "typical Windows program" where the window stays open while you collect multiple button clicks and input values, then you'll want Recipe Pattern 2B.

Recipe - Pattern 1A - "One-shot Window" - (The Simplest Pattern)

This will be the most common pattern you'll follow if you are not using an "event loop" (not reading the window multiple times). The window is read and then closed.

When you "read" a window, you are returned a tuple consisting of an event and a dictionary of values.

Theevent is what caused the read to return. It could be a button press, some text clicked, a list item chosen, etc, or None if the user closes the window using the X.

The values is a dictionary of values of all the input-style elements. Dictionaries use keys to define entries. If your elements do not specificy a key, one is provided for you. These auto-numbered keys are ints starting at zero.

This design pattern does not specify a key for the InputText element, so its key will be auto-numbered and is zero in this case. Thus the design pattern can get the value of whatever was input by referencing values[0]

The important part of this bit of code is close=True. This is the parameter that instructs PySimpleGUI to close the window just before the read returns.

This is a single line of code, broken up to make reading the window layout easier. It will display a window, let the user enter a value, click a button and then the window will close and execution will be returned to you with the variables event and values being returned.

Notice use of Element name "Shortcuts" (uses B rather than Button, T instead of Text, In rather than InputText, etc.). These shortcuts are fantastic to use when you have complex layouts. Being able to "see" your entire window's definition on a single screen of code has huge benefits. It's another tool to help you achieve simple code.

The more advanced/typical GUI programs operate with the window remaining visible on the screen. Input values are collected, but rather than closing the window, it is kept visible acting as a way to both input and output information. In other words, a typical Window, Mac or Linux window.

Let this sink in for a moment.... in 10 lines of Python code, you can display and interact with your own custom GUI window. You are writing "real GUI code" (as one user put it) that will look and act like other windows you're used to using daily.

This code will present a window and will print values until the user clicks the exit button or closes window using an X.

The first thing printed is the "event" which in this program is the buttons. The next thing printed is the values variable that holds the dictionary of return values from the read. This dictionary has only 1 entry. The "key" for the entry is '-IN-' and matches the key passed into the Input element creation on this line of code:

[sg.Input(key='-IN-')],

If the window was close using the X, then the output of the code will be:

None {'-IN-': None}

The event returned from the read is set to None and so are the input fields in the window. This None event is super-important to check for. It must be detected in your windows or else you'll be trying to work with a window that's been destroyed and your code will crash. This is why you will find this check after everywindow.read() call you'll find in sample PySimpleGUI code.

In some cirsumstances when a window is closed with an X, both of the return values from window.read() will be None. This is why it's important to check for event is None before attempting to access anything in the values variable.

This is a slightly more complex, but more realistic version that reads input from the user and displays that input as text in the window. Your program is likely to be doing both of those activities so this pattern will likely be your starting point.

Do not worry yet what all of these statements mean. Just copy the template so you can start to experiment and discover how PySimpleGUI programs work.

To modify an Element in a window, you call its update method. This is done in 2 steps. First you lookup the element, then you call that element's update method.

The way we're achieving output here is by changing a Text Element with this statement:

window['-OUTPUT-'].update(values['-IN-'])

window['-OUTPUT-'] returns the element that has the key '-OUTPUT-'. Then the update method for that element is called so that the value of the Text Element is modified.

Note - if you need to interact with elements prior to calling window.read() you will need to "finalize" your window first.

Inside your event loop

For persistent windows, after creating the window, you have an event loop that runs until you exit the window. Inside this loop you will read values that are returned from reading the window and you'll operate on elements in your window. To operate on elements, you look them up and call their method functions such as update.

Old Style Element Lookups - FindElement

The original / old-style way of looking up elements using their key was to call window.FindElement or the shortened window.Element, passing in the element's key.

These 3 lines of code do the same thing. The first line is the currently accepted way of performing this lookup operation and what you'll find in all of the current demos.

Element Operations

Once you lookup an element, the most often performed operation is update. There are other element methods you can call such as set_tooltip(). You'll find the list of operations available for each element in the call summary at the end of the main documentation.

To call any of these other methods, you do the element lookup, then add on the call such as this call to set_tooltip.

window[my_key].set_tooltip('New Tooltip')

Exiting a Window

For persistent windows, you will find this if statement immediately following every window.read call you'll find in this document and likely all of the demo programs:

if event in (None, 'Quit'):
break

This is your user's "way out". Always give a way out to your user or else they will be using task manager or something else, all the while cursing you.

Beginners to Python may not understand this statement and it's important to understand it so that you don't simply ignore it because you don't understand the syntax.

The if statment is identical to this if statement:

if event is None or event == 'Quit':
break

The event in (None, 'Quit') simply means is the value of the event variable in the list of choices shown, in this case None or Quit. If so, then break out of the Event Loop and likely exit the program when that happens for simple programs.

You may find 'Exit' instead of 'Quit' in some programs. Or may find only None is checked. Exit & Quit in this case refer to a Quit/Exit button being clicked. If your program doesn't have one, then you don't need to include it.

Close Your Windows

When you're done with your window, close it.

window.close()

The reason is that for some ports, like PySimpleGUIWeb, you cannot exit the program unless the window is closed. It's nice to clean up after yourself too.

Coding Conventions

By following some simple coding conventions you'll be able to copy / paste demo program code into your code with minimal or no modifications. Your code will be understandable by other PySimpleGUI programmers as well.

The primary suggested conventions are:

import PySimpleGUI as sg

Name your Window window

Name the return values from reading your window event and values

Name your layout layout

Use window[key] to lookup elements

For keys that are strings, follow this pattern '-KEY-'

Of course you don't have to follow any of these. They're suggestions, but if you do follow them, your code is a lot easier to understand by someone else.

Coding Tips

A few tips that have worked well for others. In the same spirit as the coding conventions, these a few observations that may speed up your development or make it easier for others to understand your code. They're guidelines / tips / suggestions / ideas... meant to help you.

Stay simple at every opportunity

Read or search the documentation (http://www.PySimpleGUI.org)

Use the coding conventions outlined above

Write compact layouts

Use "user defined elements" when you find yourself repeating parameters many times (functions that return elements)

Use PySimpleGUI constructs rather than other GUI frameworks' constructs

Use reasonable timeout values (as large of non-zero values as possible... be a good CPU citizen)

Do not try to make any PySimpleGUI call from a thread

Close your windows before exiting

Make linear event loops

Use the values dictionary rather than Element.get methods

Look through Demo Programs for more tips / techniques (http://Demos.PySimpleGUI.org)

Most of these are self-explanatory or will be understood as you learn more about PySimpleGUI. You won't now what a timeout value is at this point, but if/when you do use reads with timeouts, then you'll understand the tip.

A little more detail on a few of them that aren't obvious.

Write compact layouts

Try to keep your layout definitions to a single screen of code. Don't put every parameter on a new line. Don't add tons of whitespace.

If you've got a lot of elements, use the shortcut names (e.g. using sg.B rather than sg.Button saves 5 characters per button in your layout).

The idea here to be able to see your entire window in your code without having to scroll.

Use PySimpleGUI constructs

PySimpleGUI programs were not designed using the same OOP design as the other Python GUI frameworks. Trying to force fit them into an OOP design doesn't buy anything other then lots of self. scattered in your code, more complexity, and possibly more confusion

Of course your overall design can be OOP.

The point is that there is no concept of an "App" or a never-ending event loop or callback functions. PySimpleGUI is different than tkinter and Qt. Trying to code in that style is likely to not result in success. If you're writing a subclass for Window as a starting point, it's highly likely you're doing something wrong.

Themes - Window "Beautification"

"Beautiful windows" don't just happen, but coloring your window can be accomplished with 1 line of code.

One complaint about tkinter that is often heard is how "ugly" it looks. You can do something about that by using PySimpleGUI themes.

sg.theme('Dark Green 5')

A call to theme will set the colors to be used when creating windows. It sets text color, background color, input field colors, button color,.... 13 different settings are changed.

The default theme is "Dark Blue 3"

Look and Feel Theme Explosion

There are currently 140 themes to choose from (in April 2020, maybe more by the time you read this)

To see the above preview for your version of PySimpleGUI, make this call to generate a preview of all available themes:

sg.theme_previewer()

Even windows that are created for you, such as popups, will use the color settings you specify. And, you can change them at any point, even mid-way through defining a window layout.

This one line of code helps, but it's not the only thing that is going to make your window attractive.

Theme Name Format

You can look at the table of available themes to get the name of a theme you want to try, or you can "guess" at one using this formula:

<"Dark" | "Light"> <Color> [#]

Where Color is one of these:

Black, Blue, Green, Teal, Brown, Yellow, Gray, Purple

The # is optional and is used when there is more than 1 choice for a color. For example, for "Dark Blue" there are 12 different themes (Dark Blue, and Dark Blue 1-11). These colors specify the rough color of the background. These can vary wildly so you'll have to try them out to see what you like the best.

Recipe - Built-in Theme Viewer

If you want to see a window on your system like the above theme preview screenshot, then make this call and you'll see the same window:

import PySimpleGUI as sg
sg.preview_all_look_and_feel_themes()

Specifying and Getting Theme Names

In addition to getting all of these new themes, the format of the string used to specify them got "fuzzy". You no longer have to specify the exact string shown in the preview. Now you can add spaces, change the case, even move words around and you'll still get the correct theme.

For example the theme "DarkBrown2" can be specified also as "Dark Brown 2".

If you can't remember the names and get it wrong, you'll get a text list of the available choices printed on your console.

You can also get the list of theme names by calling theme_list

import PySimpleGUI as sg
theme_name_list = sg.theme_list()

If you guess incorrectly, then you'll be treated to a random theme instead of some hard coded default. You were calling theme to get more color, in theory, so instead of giving you a gray window, you'll get a randomly chosen theme (and you'll get the name of this theme printed on the console). It's a great way to discover new color combinations via a mistake.

Recipe - Theme Browser

This Recipe is a "Theme Browser" that enables you to see the different color schemes.

You're first shown this window that lists all of the available "Theme" settings. This window was created after the Theme were set to "Dark Brown".

If you click on an item in the list, you will immediately get a popup window that is created using the new Theme.

import PySimpleGUI as sg
"""
Allows you to "browse" through the Theme settings. Click on one and you'll see a
Popup window using the color scheme you chose. It's a simple little program that also demonstrates
how snappy a GUI can feel if you enable an element's events rather than waiting on a button click.
In this program, as soon as a listbox entry is clicked, the read returns.
"""
sg.theme('Dark Brown')
layout = [[sg.Text('Theme Browser')],
[sg.Text('Click a Theme color to see demo window')],
[sg.Listbox(values=sg.theme_list(), size=(20, 12), key='-LIST-', enable_events=True)],
[sg.Button('Exit')]]
window = sg.Window('Theme Browser', layout)
while True: # Event Loop
event, values = window.read()
if event in (None, 'Exit'):
break
sg.theme(values['-LIST-'][0])
sg.popup_get_text('This is {}'.format(values['-LIST-'][0]))
window.close()

Making Changes to Themes & Adding Your Own Themes

Modifying and creating your own theme is not difficult.

The Theme definitions are stored in a dictionary. The underlying dictionary can be directly accessed via the variable LOOK_AND_FEEL_TABLE.

As you can see, a single entry in the Look and Feel dictionary is itself a dictionary.

Recipe - Modifying an existing Theme

Let's say you like the LightGreeen3 Theme, except you would like for the buttons to have black text instead of white. You can change this by modifying the theme at runtime.

Normal use of theme calls is to retrieve a theme's setting such as the background color. The functions used to retrieve a theme setting can also be used to modify the setting by passing in the new setting as a parameter.

Calling theme_background_color() returns the background color currently in use. Passing in the color 'blue' as the parameter, theme_background_color('blue'), will change the background color for future windows you create to blue.

Recipe - Adding Your Own Color Theme

The great thing about these themes is that you set it onces and all future Elements will use the new settings. If you're adding the same colors in your element definitions over and over then perhaps making your own theme is in order.

Let's say that you need to match a logo's green color and you've come up with matching other colors to go with it. To add the new theme to the standard themes this code will do it:

More Ways to "Dress Up Your Windows"

In addition to color there are a several of other ways to potentially make your window more attractive. A few easy ones include:

Remove the titlebar

Make your window semi-transparent (change opacity)

Replace normal buttons with graphics

You can use a combination of these 3 settings to create windows that look like Rainmeter style desktop-widgets.

This window demonstrates these settings. As you can see, there is text showing through the background of the window. This is because the "Alpha Channel" was set to a semi-transparent setting. There is no titlebar going across the window and there is a little red X in the upper corner, resumably to close the window.

Recipe Removing the Titlebar & Making Semi-Transparent

Both of these can be set when you create your window. These 2 parameters are all you need - no_titlebar and alpha_channel.

When creating a window without a titlebar you create a problem where the user is unable to move your window as they have no titlebar to grab and drag. Another parameter to the window creation will fix this problem - grab_anywhere. When True, this parameter allows the user to move the window by clicking anywhere within the window and dragging it, just as if they clicked the titlebar. Some PySimpleGUI ports allow you to click on input fields and drag, others require you to grab a spot on the background of the window. Note - you do not have to remove the titlebar in order to use grab_anywhere

To make your window semi-transpaerent (change the opacity) use ghe alhpa_channel parameter when you create the window. The setting is a float with valid values from 0 to 1.

To create a window like the one above, your window creation call would look something like:

Recipe - Replacing a Button with a Graphic

In PySimpleGUI you can use PNG and GIF image files as buttons. You can also encode those files into Base64 strings and put them directly into your code.

It's a 4 step process to make a button using a graphic

Find your PNG or GIF graphic

Convert your graphic into a Base64 byte string

Add Base64 string to your code as a variable

Specify the Base64 string as the image to use when creating your button

Step 1 - Find your graphic

There are a LOT of places for you to find your graphics. This page lists a number of ways to search for what you need. Bing also has a great image search tool that you can filter your results on to get a list of PNG files (choose "Transparent" using their "filter" on the page.)

I chose this one from the list:
http://icons.iconarchive.com/icons/iconarchive/red-orb-alphabet/256/Letter-X-icon.png

You can download your image or get a copy of the link to it.

Step 2 - Convert to Base64

One of the demo programs provided on the PySimpleGUI GitHub is called "Demo_Base64_Image_Encoder.py". This program will convert all of the images in a folder and write the encoded data to a file named output.py.

Another demo program, "Demo_Base64_Single_Image_Encoder.py" will convert the input file to a base64 string and place the string onto the clipboard. Paste the result into your code and assign it to a variable.

You can also use an online conversion tool such as https://base64.guru/converter/encode/image

On that page I chose to use the "Remote URL" (see above), pasted it into the input box and clicked "Encode image to Base64". Under the encode button is an area labeled "Base64". If your conversion was successful, you'll see it filled with data like shown here:

Step 3 - Make Base64 String Variable

Select all of the data in the Base64 box and paste into your code by making a variable that is equal to a byte-string.

red_x_base64 = b''

Paste the long data you got from the webpage inside the quotes after the b.

You can also copy and paste the byte string from the output.py file if you used the demo program or paste the string created using the single file encoder demo program.

Step 4 - Use Base64 Variable to Make Your Button

This is the Button Element that is added to the layout to create the Red X Button graphic.

You need to set the background color for your button to be the same as the background the button is being placed on if you want it to appear invisible.

When working with PNG/GIF files as button images the background you choose for the button matters. It should match the background of whatever it is being placed upon. If you are using the standard "themes" interfaces to build your windows, then the color of the background can be found by calling theme_background_color(). Buttons have 2 colors so be sure and pass in TWO color values when specifying buttons (text color, background color).

Remember how keys are key to understanding PySimpleGUI elements? Well, they are, so now you know.

If you do not specify a key and the element is an input element, a key will be provided for you in the form of an integer, starting numbering with zero. If you don't specify any keys, it will appear as if the values returned to you are being returned as a list because the keys are sequential ints.

This example has no keys specified. The 3 input fields will have keys 0, 1, 2. Your first input element will be accessed as values[0], just like a list would look.

Recipe - Add GUI to Front-End of Script

Quickly add a GUI allowing the user to browse for a filename if a filename is not supplied on the command line using this simple GUI. It's the best of both worlds. If you want command line, you can use it. If you don't specify, then the GUI will fire up.

If you really want to compress your 1-line of GUI code, you can directly access just the entered data by using this single-line-of-code solution. Dunno if it's the safest way to go, but it's certainly the most compact. Single line GUIs are fun when you can get away with them.

Use enable_events to instantly get events

That was simple enough. But maybe you're impatient and don't want to have to cick "Ok". Maybe you don't want an OK button at all. If that's you, then you'll like the enable_events parameter that is available for nearly all elements. Setting enable_events means that like button presses, when that element is interacted with (e.g. clicked on, a character entered into) then an event is immediately generated causing your window.read() call to return.

If the previous example were changed such that the OK button is removed and the enable_events parameter is added, then the code and window appear like this:

You won't need to click the OK button anymore because as soon as you make the selection in the listbox the read() call returns and the popup will be displayed as before.

This second example code could be used with the OK button. It doesn't matter what event caused the window.read() to return. The important thing is whether or not a valid selection was made. The check for event == 'Ok' is actually not needed.

Recipe - Input Validation

Sometimes you want to restrict what a use can input into a field. Maybe you have a zipcode field and want to make sure only numbers are entered and it's no longer than 5 digits.

Perhaps you need a floating point number and only want to allow 0-9, ., and -. One way restrict the user's input to only those characters is to get an event any time the user inputs a character and if the character isn't a valid one, remove it.

You've already seen (above) that to get an event immediate when an element is interacted with in some way you set the enable_events parameter.

import PySimpleGUI as sg
"""
Restrict the characters allowed in an input element to digits and . or -
Accomplished by removing last character input if not a valid character
"""
layout = [ [sg.Text('Input only floating point numbers')],
[sg.Input(key='-IN-', enable_events=True)],
[sg.Button('Exit')] ]
window = sg.Window('Floating point input validation', layout)
while True:
event, values = window.read()
if event in (None, 'Exit'):
break
# if last character in input element is invalid, remove it
if event == '-IN-' and values['-IN-'] and values['-IN-'][-1] not in ('0123456789.-'):
window['-IN-'].update(values['-IN-'][:-1])
window.close()

This code only allows entry of the correct characters.

Note that this example does not fully validate that the entry is a valid floating point number, but rather that it has the correct characters.

If you wanted to take it a step further and verify that the entry is actually a valid floating point number, then you can change the "if" statement to test for valid floating point number.

import PySimpleGUI as sg
"""
Restrict the characters allowed in an input element to digits and . or -
Accomplished by removing last character input if not a valid character
"""
layout = [ [sg.Text('Input only floating point numbers')],
[sg.Input(key='-IN-', enable_events=True)],
[sg.Button('Exit')] ]
window = sg.Window('Floating point input validation', layout)
while True:
event, values = window.read()
if event in (None, 'Exit'):
break
# if last character in input element is invalid, remove it
if event == '-IN-' and values['-IN-']:
try:
in_as_float = float(values['-IN-'])
except:
if len(values['-IN-']) == 1 and values['-IN-'][0] == '-':
continue
window['-IN-'].update(values['-IN-'][:-1])
window.close()

Recipe - Printing

Outputting text is a very common operation in programming. Your first Python program may have been

print('Hello World')

But in the world of GUIs where do "prints" fit in? Well, lots of places! Of course you can still use the normal print statement. It will output to StdOut (standard out) which is normally the shell where the program was launched from.

Prining to the console becomes a problem however when you launch using pythonw on Windows or if you launch your program in some other way that doesn't have a console. With PySimpleGUI you have many options available to you so fear not.

These Recipes explore how to retain prints already in your code. Let's say your code was written for a console and you want to migrate over to a GUI. Maybe there are so many print statements that you don't want to modify every one of them individually.

The various forms of "print" you'll be introduced to all support the sep and end parameters that you find on normal print statements.

Recipe - #1/3 Printing to Debug Window

The debug window acts like a virtual console. There are 2 operating modes for the debug window. One re-routes stdout to the window, the other does not.

Print - Print to the Debug Window

The functions Print, eprint, EasyPrint all refer to the same funtion. There is no difference whic hyou use as they point to identical code. The one you'll see used in Demo Programs is Print.

One method for routing your print statements to the debuyg window is to reassign the print keyword to be the PySimpleGUI function Print. This can be done through simple assignment.

print = sg.Print

You can also remap stdout to the debug window by calling Print with the parameter do_not_reroute_stdout = False. This will reroute all of your print statements out to the debug window.

import PySimpleGUI as sg
sg.Print('Re-routing the stdout', do_not_reroute_stdout=False)
print('This is a normal print that has been re-routed.')

While both print and sg.Print will output text to your Debug Window.

Printing in color is only operational if you do not reroute stdout to the debug window.

If color printing is important, then don't reroute your stdout to the debug window. Only use calls to Print without any change to the stdout settings and you'll be able to print in color.

import PySimpleGUI as sg
sg.Print('This text is white on a green background', text_color='white', background_color='green', font='Courier 10')
sg.Print('The first call sets some window settings like font that cannot be changed')
sg.Print('This is plain text just like a print would display')
sg.Print('White on Red', background_color='red', text_color='white')
sg.Print('The other print', 'parms work', 'such as sep', sep=',')
sg.Print('To not extend a colored line use the "end" parm', background_color='blue', text_color='white', end='')
sg.Print('\nThis line has no color.')

Recipe - #2/3 Print to Output Element

If you want to re-route your standard out to your window, then placing an Output Element in your layout will do just that. When you call "print", your text will be routed to that Output Element. Note you can only have 1 of these in your layout because there's only 1 stdout.

Of all of the "print" techniques, this is the best to use if you cannot change your print statements. The Output element is the best choice if your prints are in another module that you don't have control over such that "redefining / reassigning" what print does isn't a possibility.

This layout with an Output element shows the results of a few clicks of the Go Button.

Recipe - #3/3 Print to Multiline Element

Beginning in 4.18.0 you can "print" to any Multiline Element in your layouts. The Multiline.print method acts similar to the Print function described earlier. It has the normal print parameters sep & end and also has color options. It's like a super-charged print statement.

"Converting" expring print statements to output to a Multiline Element can be done by either

Adding the Multiline element to the print statment so that it's calling the Multiline.print method

Redefining print

3A Appending Element to print Statement to print to Multiline

Let's try the first option, adding the element onto the front of an existing print statement as well as using the color parameters.

The most basic form of converting your exiting print into a Multline based print is to add the same element-lookup code that you would use when calling an element's update method. Generically, that conversion looks like this:

print('Testing 1 2 3')

If our Multiline's key is '-ML-' then the expression to look the element up is:

window['-ML-']

Combing the two transforms the original print to a Multline element print:

window['-ML-'].print('Testing 1 2 3')

Because we're using these Multilne elements as output only elements, we don't want to have their contents returned in the values dictionary when we call window.read(). To make any element not be included in the values dictionary, add the constant WRITE_ONLY_KEY onto the end of your key. This would change our previous example to:

window['-ML-'+sg.WRITE_ONLY_KEY].print('Testing 1 2 3')

When you define the multiline element in your layout, its key will need to have this suffix added too.

Combining all of this information into a full-program we arrive at this Recipe:

There are a number of tricks and techniques burried in this Recpie so study it closely as there are a lot of options being used.

3B Redefining print to Print to Multiline

If you want to use the Multline element as the destination for your print, but you don't want to go through your code and modify every print statement by adding an element lookup, then you can simply redefine your call to print to either be a function that adds that multline element onto the print for you or a lambda expression if you want to make it a single line of code. Yes, it's not suggested to use a lambda expression by assignment to a vairable, but sometimes it may be easier to understand. Find the right balanace for you and ryour projct.

Recipe - Save and Load Program Settings

Some programs, in particular Desktop Widget like Rainmeter-style prorams, need to retain "state" or some series of settings.

This program is a tad large for a Cookbook, but it's a commmon enough feature to go ahead and include. Besides, it may give you some ideas.

The idea here is that your program's settings are stored in a dictionary. This dictionary is then written to disk and loaded from disk.

One type of program where this kind of feature is a requirement is when yuou make "rainmeter" tyle Desktop Widgets. These little programs almost always need to store some kind of state.... everything from the transprency of the widget to the zip code your program uses to look up the weather.

The architecture is quite simple. You keep your settings ina dictionary. Your GUI settings window modifies the dictionary and eventually it's written to disk so that the next time you run the probgram you don't have to set up everyihng that's been saved previously.

The package used to save / load that data is the JSON package. It makes writing and reading Python dictionaries downright trivial. I use it as a simplified database. You can also hand edit these files easily.

The portions of this Recipe you'll need to modify to integrate into your code will be:

the default settings at the top

the mapping table to/from settings keys to element keys

the settings filename

the settings window

replace the "main" program with yours

The simple main program is there to trigger the change settings event:

The more important window in this program is the settings window

You'll be converting back and forth between the settings file contents and the values that come out of reading the settings GUI window.

Notice how creation of the window is done is a separate function in this Recipe so that you get a "fresh" layout every time the window is created. It's critical that you do not try to re-use elements.

If you're considering allowing the user to change your program's theme, then this is an excellent way to do that. All that has to be done is to close your window when a new theme is chosen.

Recipe - Get 2 Files By Browsing

Sometimes you just need to get a couple of filenames. Browse to get 2 file names that can be then compared. By using Input elements the user can either use the Browse button to browse to select a file or they can paste the filename into the input element directly.

This pattern is really good any time you've got a file or folder to get from the user. By pairing an Input element with a browse button, you give the user the ability to do a quick paste if they've already got the path on the clipboard or they can click "Browse" and browse to get the filename/foldername.

Recipe - Get Filename With No Input Display. Returns when file selected

There are times when you don't want to display the file that's chosen and you want the program to start when the user chooses a file. One way of doing this is to hide the input field that's filled in by the "Browse Button". By enabling events for the input field, you'll get an event when that field is filled in.

Nearly All Elements with Color Theme, Menus, (The Everything Bagel)

Example of nearly all of the Elements in a single window. Uses a customized color scheme, lots of Elements, default values, Columns, Frames with colored text, tooltips, file browsing. There are at least 13 different Elements used.

Before scrolling down to the code, guess how many lines of Python code were required to create this custom layout window.

35 lines of code

That's what the window definition, creation, display and get values ultimately ended up being when you remove the blank lines above. Try displaying 13 seperate "GUI Widgets" in any of the GUI frameworks. There's $20 waiting for the person that can code up the same window in under 35 lines of Python code using tkinter, WxPython, or Qt. For compactness, it's difficult to beat PySimpleGUI simply because the PySimpleGUI code is running a ton of "boilerplate" code on your behalf.

Asynchronous Window With Periodic Update

Sync Versus Async Mode

It's possible, and even easy, to run your PySimpleGUI program in an "asynchronous" way.

What does that even mean?

There are 2 modes sync and async. When running normally (synchronous), calls are made into the GUI stay in the GUI until something happens. You call window.read() and wait for a button or some event that causes the read to return.

With async calls, you wait for an event for a certain amount of time and then you return after that amount of time if there's no event. You don't wait forever for a new event.

When running asynchronously, you are giving the illusion that multiple things are happening at the same time when in fact they are interwoven.

It means your program doesn't "block" or stop running while the user is interacting with the window. Your program continues to run and does things while the user is fiddling around.

The critical part of these async windows is to ensure that you are calling either read or refresh often enough. Just because your code is running doesn't mean you can ignore the GUI. We've all experienced what happens when a GUI program "locks up". We're shown this lovely window.

This happens when the GUI subsystem isn't given an opportunity to run for a long time. Adding a sleep to your event loop will cause one of these to pop up pretty quickly.

We can "cheat" a little though. Rather than being stuck inside the GUI code, we get control back, do a little bit of work, and then jump back into the GUI code. If this is done quickly enough, you don't get the ugly little "not responding" window.

Async Uses - Polling

Use this design pattern for projects that need to poll or output something on a regular basis. In this case, we're indicating we want a timeout=10 on our window.read call. This will cause the Read call to return a "timeout key" as the event every 10 milliseconds has passed without some GUI thing happening first (like the user clicking a button). The timeout key is PySimpleGUI.TIMEOUT_KEY usually written as sg.TIMEOUT_KEY in normal PySimpleGUI code.

Use caution when using windows with a timeout. You should rarely* need to use a timeout=0. A zero value is a truly non-blocking call, so try not to abuse this design pattern. You shouldn't use a timeout of zero unless you're a realtime application and you know what you're doing. A zero value will consume 100% of the CPU core your code is running on. Abuse it an bad things will*** happen.

A note about timers... this is not a good design for a stopwatch as it can very easily drift. This would never pass for a good solution in a bit of commercial code. For better accuracy always get the actual time from a reputable source, like the operating system. Use that as what you use to measure and display the time.

The focus parameter for the Button causes the window to start with that button having focus. This will allow you to press the return key or spacebar to control the button.

Callback Function Simulation

The architecture of some programs works better with button callbacks instead of handling in-line. While button callbacks are part of the PySimpleGUI implementation, they are not directly exposed to the caller. The way to get the same result as callbacks is to simulate them with a recipe like this one.

OneLineProgressMeter

This recipe shows just how easy it is to add a progress meter to your code.

import PySimpleGUI as sg
sg.theme('Dark Blue 8')
for i in range(1000): # this is your "work loop" that you want to monitor
sg.OneLineProgressMeter('One Line Meter Example', i + 1, 1000, 'key')

Unlike other progress meter Python packages, PySimpleGUI's one-line-progress-meter is 1 line of code, not 2. Historicly you would setup the meter outside your work loop and then update that meter inside of your loop. With PySimpleGUI you do not need to setup the meter outside the loop. You only need to add the line of code to update the meter insdie of your loop.

Minesweeper-style Grid of Buttons

There are a number of applications built using a GUI that involve a grid of buttons. The games Minesweeper and Battleship can both be thought of as a grid of buttons.

Here is the code for the above window

import PySimpleGUIWeb as sg
from random import randint
MAX_ROWS = MAX_COL = 10
board = [[randint(0,1) for j in range(MAX_COL)] for i in range(MAX_ROWS)]
layout = [[sg.Button('?', size=(4, 2), key=(i,j), pad=(0,0)) for j in range(MAX_COL)] for i in range(MAX_ROWS)]
window = sg.Window('Minesweeper', layout)
while True:
event, values = window.read()
if event in (None, 'Exit'):
break
# window[(row, col)].update('New text') # To change a button's text, use this pattern
# For this example, change the text of the button to the board's value and turn color black
window[event].update(board[event[0]][event[1]], button_color=('white','black'))
window.close()

The most important thing for you to learn from this recipe is that keys and events can be any type, not just strings.

Thinking about this grid of buttons, doesn't it make the most sense for you to get row, column information when a button is pressed. Well, that's exactly what setting your keys for these buttons to be tuples does for you. It gives you the abilty to read events and finding the button row and column, and it makes updating text or color of buttons using a row, column designation.

This program also runs on PySimpleGUIWeb really well. Change the import to PySimpleGUIWeb and you'll see this in your web browser (assuming you've installed PySimpleGUIWeb)

Button Graphics (Media Player)

Buttons can have PNG of GIF images on them. This Media Player recipe requires 4 images in order to function correctly. The background is set to the same color as the button background so that they blend together.

Script Launcher - Persistent Window

This Window doesn't close after button clicks. To achieve this the buttons are specified as sg.Button instead of sg.Button. The exception to this is the EXIT button. Clicking it will close the window. This program will run commands and display the output in the scrollable window.

Multiple Columns

A Column is required when you have a tall element to the left of smaller elements.

In this example, there is a Listbox on the left that is 3 rows high. To the right of it are 3 single rows of text and input. These 3 rows are in a Column Element.

To make it easier to see the Column in the window, the Column background has been shaded blue. The code is wordier than normal due to the blue shading. Each element in the column needs to have the color set to match blue background.

While it's fun to scribble on a Canvas Widget, try Graph Element makes it a downright pleasant experience. You do not have to worry about the tkinter coordinate system and can instead work in your own coordinate system.

Keypad Touchscreen Entry - Input Element Update

This Recipe implements a Raspberry Pi touchscreen based keypad entry. As the digits are entered using the buttons, the Input Element above it is updated with the input digits.
There are a number of features used in this Recipe including: Default Element Size auto_size_buttons Button Dictionary Return values
* Update of Elements in window (Input, Text)

Matplotlib Window With GUI Window

There are 2 ways to use PySimpleGUI with Matplotlib. Both use the standard tkinter based Matplotlib.

The simplest is when both the interactive Matplotlib window and a PySimpleGUI window are running at the same time.

First the PySimpleGUI window appears giving you 3 options.

Clicking "Plot" will create the Matplotlib window

You can click the "Popup" button in the PySimpleGUI window and you'll see a popup window, proving the your GUI is still alive and operational.

import PySimpleGUI as sg
import matplotlib.pyplot as plt
"""
Simultaneous PySimpleGUI Window AND a Matplotlib Interactive Window
A number of people have requested the ability to run a normal PySimpleGUI window that
launches a MatplotLib window that is interactive with the usual Matplotlib controls.
It turns out to be a rather simple thing to do. The secret is to add parameter block=False to plt.show()
"""
def draw_plot():
plt.plot([0.1, 0.2, 0.5, 0.7])
plt.show(block=False)
layout = [[sg.Button('Plot'), sg.Cancel(), sg.Button('Popup')]]
window = sg.Window('Have some Matplotlib....', layout)
while True:
event, values = window.read()
if event in (None, 'Cancel'):
break
elif event == 'Plot':
draw_plot()
elif event == 'Popup':
sg.popup('Yes, your application is still running')
window.close()

Animated Matplotlib Graph

Use the Canvas Element to create an animated graph. The code is a bit tricky to follow, but if you know Matplotlib then this recipe shouldn't be too difficult to copy and modify.

Tight Layout with Button States

Saw this example layout written in tkinter and liked it so much I duplicated the interface. It's "tight", clean, and has a nice dark look and feel.

This Recipe also contains code that implements the button interactions so that you'll have a template to build from.

In other GUI frameworks this program would be most likely "event driven" with callback functions being used to communicate button events. The "event loop" would be handled by the GUI engine. If code already existed that used a call-back mechanism, the loop in the example code below could simply call these callback functions directly based on the button text it receives in the window.read call.

Password Protection For Scripts

You get 2 scripts in one.

Use the upper half to generate your hash code. Then paste it into the code in the lower half. Copy and paste lower 1/2 into your code to get password protection for your script without putting the password into your source code.

At the moment I'm using the technique that involves wscript and a script named RunNHide.vbs. They are working beautifully. I'm using a hotkey program and launch by using this script with the command "python.exe insert_program_here.py". I guess the next widget should be one that shows all the programs launched this way so you can kill any bad ones. If you don't properly catch the exit button on your window then your while loop is going to keep on working while your window is no longer there so be careful in your code to always have exit explicitly handled.

Floating toolbar

This is a cool one! (Sorry about the code pastes... I'm working in it)

Impress your friends at what a tool-wizard you are by popping a custom toolbar that you keep in the corner of your screen. It stays on top of all your other windows.

You can easily change colors to match your background by changing a couple of parameters in the code.

Desktop Floating Widget - Timer

This is a little widget you can leave running on your desktop. Will hopefully see more of these for things like checking email, checking server pings, displaying system information, dashboards, etc
.
Much of the code is handling the button states in a fancy way. It could be much simpler if you don't change the button text based on state.

Menus

Menus are nothing more than buttons that live in a menu-bar. When you click on a menu item, you get back a "button" with that menu item's text, just as you would had that text been on a button.

Menu's are defined separately from the GUI window. To add one to your window, simply insert sg.Menu(menu_layout). The menu definition is a list of menu choices and submenus. They are a list of lists. Copy the Recipe and play with it. You'll eventually get when you're looking for.

If you double click the dashed line at the top of the list of choices, that menu will tear off and become a floating toolbar. How cool! To enable this feature, set the parameter tearoff=True in your call to sg.Menu()

Tabs

Tabs bring not only an extra level of sophistication to your window layout, they give you extra room to add more elements. Tabs are one of the 3 container Elements, Elements that hold or contain other Elements. The other two are the Column and Frame Elements.

Creating a Windows .EXE File

It's possible to create a single .EXE file that can be distributed to Windows users. There is no requirement to install the Python interpreter on the PC you wish to run it on. Everything it needs is in the one EXE file, assuming you're running a somewhat up to date version of Windows.

Installation of the packages, you'll need to install PySimpleGUI and PyInstaller (you need to install only once)

pip install PySimpleGUI
pip install PyInstaller

To create your EXE file from your program that uses PySimpleGUI, my_program.py, enter this command in your Windows command prompt:

pyinstaller -wF my_program.py

You will be left with a single file, my_program.exe, located in a folder named dist under the folder where you executed the pyinstaller command.

That's all... Run your my_program.exe file on the Windows machine of your choosing.

"It's just that easy."

(famous last words that screw up just about anything being referenced)

Your EXE file should run without creating a "shell window". Only the GUI window should show up on your taskbar.