PyCharm 2024.2 Help

Search for usages.

When you write or edit code, you might come across a code element that you want to change or delete. Before you make the changes, it is a good practice to see where the code element is used and how it affects the application. With the Find Usages actions you can search for the references of your code element throughout the whole codebase.

You can manage the search process, and search only in a single file, extend your search to the whole project, or create a certain search scope. Moreover, you can configure the color of the usages highlighting or disable the automatic highlighting of usages altogether.

Search for usages in a file

In the editor, click an element you want to find; PyCharm automatically highlights all found usages in the file. If the highlighting of usages is disabled, press Ctrl+Shift+F7 to highlight all usages in the file.

Highlight usages in file

To find a text string , select it in the editor, go to Edit | Find Usages | Find Usages in File Ctrl+F7 . PyCharm selects all the usage occurrences in the file.

Highlighted symbols in a file

Use the F3 and Shift+F3 shortcuts to navigate between highlighted symbols.

Search for usages in a project

Select a symbol for which you want to find usages, right-click the symbol, and select Find Usages from its context menu or press Alt+F7 .

Check the results in the Find tool window.

PyCharm analyzes search results, detects the most common usage patterns, and categorizes all found usages into groups based on their structural similarity. These usage clusters appear in the Preview tab.

You can select any group node from the list and click Show similar usages to look through the results.

To disable this functionality, unselect the Enable similar usages clustering in Find Usages view in the advanced settings .

While in the Find tool window, you can also use the Preview area to check the places where the usages were found, to see a call hierarchy for methods, data flow for fields, and so on.

Find tool window preview area

Preview source code for found usages

You have several options to see the code source for the usages found.

As an alternative, you can select Jump to Source if you invoke the context menu on a usage found or Show in Split . In this case, the file with the result usage is opened in the editor.

Show usages in a separate window

You can view usages of the selected symbol in a separate window that you can move to different parts of your screen and use for quick navigation.

In the editor, select a symbol for which you want to see the usages.

Go to Edit | Find Usages | Show Usages Ctrl+Alt+F7 .

Show Usages popup

The usages window shows the current scope and total count of usages. If you want to quickly switch to the default scope, press Ctrl+Alt+F7 .

If the search results have too many entries, then PyCharm shows the first hundred usages found and the more usages option on the bottom of the window which you can click to display another hundred usages, and so on until the search is finished.

Use filters on the top of the window to show or hide the certain search entries.

View recent usages search results

PyCharm remembers your Find Usages results, so you don't need to run the action again.

In the main menu, go to Edit | Find Usages | Recent Find Usages and then select the usage query.

Manage the scope of Find Usages

Sometimes, you might want to find usages only in certain files or libraries of your project.

Press Ctrl+Alt+Shift+F7 to open the Find Usages dialog.

In the Find Usages dialog, in the Scope field, select a scope for your search. For example, you can search for usages only in Open Files or only Project Test Files .

Find Usages dialog (Change Scope)

If PyCharm doesn't return any results, it will display a message suggesting that you opt for more options.

No usages found popup

You can follow the link or press Ctrl+Alt+Shift+F7 to open the Find Usages dialog again and set a new scope for your search.

Disable automatic highlighting of usages

When you place the caret at a symbol, the IDE highlights all usages of this symbol in the current file.

If necessary, you can disable the automatic highlighting.

Press Ctrl+Alt+S to open settings and then select Editor | Code Editing .

Clear the Usages of element at caret checkbox in the Highlight on Caret Movement section.

When automatic highlighting is disabled, and you want to highlight usages of a symbol in the current file, select this symbol and press Ctrl+Shift+F7 . This will highlight all usages of the symbol in the current file.

Change the background color of the highlighted usages

In the Settings dialog ( Ctrl+Alt+S ) , go to Editor | Color Scheme | General .

From the options on the right, open the Code node and select Identifier under caret .

In the Background field, specify the color you need and save the changes.

  • FreeSimpleGUI
  • Call reference

The PySimpleGUI Cookbook

Constantly being updated, the "demo programs" are also "recipes", trinket, the online pysimplegui cookbook.

  • Repl.it... another online resource

Cookbook Purpose

Getting started - copy these design patterns, recipe - pattern 1a - "one-shot window" - (the simplest pattern), recipe - pattern 1b - "one-shot window" - (self-closing, single line), recipe - pattern 2a - persistent window (multiple reads using an event loop), inside your event loop, close your windows, coding tips, demo program & project browser features, downloading the pysimplegui demo programs, setup the demo browser, more details on settings, window sections, verbose mode, "open folder" feature, adding the menu, look and feel theme explosion, recipe - built-in theme viewer, people / visitors love pictures, the github issue technique, the image hosted elsehwere technique, making changes to themes & adding your own themes, recipe - modifying an existing theme, more ways to "dress up your windows", recipe removing the titlebar & making semi-transparent, recipe - replacing a button with a graphic, recipe - 1 shot window - simple data entry - return values - auto numbered, recipe - add gui to front-end of script, recipe - the popup_get_file version of add gui to front-end of script, recipe - function and aliases, use enable_events to instantly get events, recipe - input validation, recipe - positioning windows on a multi-monitor setup (tkinter version of pysimplegui only), justification, alignment - single rows, alignment - vpush, single line inputs, push your input rows, push everything - element_justification='r', recipe printing - #1/4 printing to debug window, recipe printing - #2/4 print to output element, recipe printing - #3/4 print to multiline element, recipe printing - #4a/4 using cprint function (color printing) to print to multiline, the aliasing shortcut trick, recipe printing - #4b/4 using cprint with multiline parameters (pysimplegui version 4.25.0+), a simple save filename example, recipe - get 2 files by browsing, recipe - get filename with no input display. returns when file selected, pysimplegui window.perform_long_operation, the thread-based solution, use with buttons, recipe - collapsible sections (visible / invisible elements), recipe multiple windows - read_all_windows, recipe - all elements (the everything bagel... 2022-style), the debug print window.

  • Use the wait/ blocking parameter!

Example Program With Exception

Example with exception handling added, adding traceback and editing capabilities, asynchronous window with periodic update, recipe - callback function simulation, cancelling - user generated, cancelling - program generated, other parameters, recipe - minesweeper-style grid of buttons, recipe - button graphics (media player), recipe - script launcher - exec apis, recipe- launch a program with a button, recipe - machine learning gui, recipe - custom progress meter / progress bar, recipe - multiple columns, recipe - persistent window with text element updates, recipe - one element updating another - compound elements, tkinter canvas widget, graph element - drawing circle, rectangle, etc, objects, keypad touchscreen entry - input element update, matplotlib window with gui window, animated matplotlib graph, tight layout with button states, password protection for scripts, desktop floating toolbar, desktop floating widget - timer, desktop floating widget - cpu utilization, graphing with graph element, creating a windows .exe file, author & owner.

Welcome to the PySimpleGUI Cookbook! It's provided as but one component of a larger documentation effort for the PySimpleGUI package. Its 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 the detailed call reference. That document is updated much more frequently than this one.

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

Because PySimpleGUI is an active project, new capabilities are being added frequently, and the recommended method for doing operations evolves over time, that means this Cookbook also changes over time. However, the speed the Cookbook gets updated will, by definition, lag behind the code changes.

*The Demo Programs are going to be the most up to date examples * for you, but even those get out of date. It's an imperfect world, but let's make the most of what we've got.

If you like this Cookbook, then you'll LOVE the 300 sample programs that are just like these. You'll find them in the GitHub at https://github.com/spyoungtech/FreeSimpleGUI/tree/main/DemoPrograms. 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.

These short Demo Programs fall into 3 categories:

  • Demonstrate a particular Element
  • Integration with another package (e.g. Matplotlib, OpenCV, etc)
  • Provide added functionality - more complex element combinations or extensions to elements

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.

Because there are so many Demo Programs, there is a "Demo Program Browser". There is a Recipe in this Cookbook on how to download the Demo Programs and run the Demo Program Browser.

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.

Repl.it ... another online resource

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.

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 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 FreeSimpleGUI 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, objects). Anything EXCEPT Lists . Lists are not valid Keys because in Python lists are not hashable and thus cannot be used as keys in dictionaries. Tuples, however, can.

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.

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:

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.

SNAG-0682

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 .

The event is what caused the read to return. It could be a button press, some text clicked, a list item chosen, etc, or WIN_CLOSED 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]

If you want to use a key instead of an auto-generated key:

For a much more compact window, it's possible to create, display, read, and close a window in a single line of code.

The important part of this bit of code is close=True . This is the parameter that instructs FreeSimpleGUI 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.

image

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.

Here is some sample output from this code:

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:

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

The event returned from the read is set to None (the variable WIN_CLOSED ) 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 every window.read() call you'll find in sample FreeSimpleGUI 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.

Recipe - Pattern 2B - Persistent window (multiple reads using an event loop + updates data in window)

image

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-'] 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. Be sure you have supplied a size that is large enough to display your output. If the size is too small, the output will be truncated.

There are two important concepts when updating elements!

  • If you need to interact with elements prior to calling window.read() you will need to "finalize" your window first using the finalize parameter when you create your Window . "Interacting" means calling that element's methods such as update , expand , draw_line , etc.
  • Your change will not be visible in the window until you either: A. Call window.read() again B. Call window.refresh()

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 .

Operations on elements will not appear in your window immediately. If you wish for them to appear immediately, prior to your next window.read() call, you must call window.refresh() . A call to read or refresh causes your changes to be displayed.

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:

or this version which is easier for beginners to understand. They perfect exactly the same check.

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 statement is identical to this if statement:

The event in (sg.WIN_CLOSED, 'Quit') simply means is the value of the event variable in the list of choices shown, in this case WIN_CLOSED 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 WIN_CLOSED 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.

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

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 FreeSimpleGUI 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.

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.

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.

Recipe - The Demo Browser

There are so many demo programs that a way of quickly searching them was needed. There is the "Demo Programs Browser" that makes finding, editing and running Demo Programs easier.

The "PySimpleGUI Demo Program & Project Browser" makes searching for and searching inside of the PySimpleGUI Demo Programs easier. You can also use this program with any folder of Python programs. They don't have to be PySimpleGUI programs or PySimpleGUI releated.

Some of the features this program provides are: * Displays your project tree as a single list of files * "Filtering" of the files - searches by filename * "Find" files - searches inside of your list of files * Opening files using the editor of your choice * Executing the files * Easy editing of the Browser Program itself using the "Edit Me" button

Jump Start! Get the Demo Programs & Demo Browser

The over 300 Demo Programs will give you a jump-start and provide many design patterns for you to learn how to use PySimpleGUI and how to integrate PySimpleGUI with other packages. By far the best way to experience these demos is using the Demo Browser. This tool enables you to search, edit and run the Demo Programs.

To get them installed quickly along with the Demo Browser, use pip to install psgdemos :

python -m pip install psgdemos

or if you're in Linux, Mac, etc, that uses python3 instead of python to launch Python:

python3 -m pip install psgdemos

Once installed, launch the demo browser by typing psgdemos from the command line"

SNAG-1543

Download the Repo and Demos

If you chose not to pip install the psgdemos package, then you can download the PySimpleGUI Repo from GitHub and run the Demo Browser.

Follow these instructions to download the repo and demos:

  • Go to http://www.PySimpleGUI.com (the PySimpleGUI GitHub)

download

  • Unzip the downloaded zip and place the folder DemoPrograms somewhere on your local disk drive that you have write access

Once you've got your Demo Programs folder set up on your local computer:

  • Run the program Browser_START_HERE_Demo_Programs_Browser.py that is in the folder you unzipped

When you first run the Demo Browser, it will probably look something like this:

download

To change the settings:

  • Click the "Settings" button

Click the "Settings" button. You'll see a window like this one:

download

I've changed the theme to be "DarkGrey13" and checked "Use Advanced Interface". I know a number of users like "Dark Themes" so let's use a "dark grey 13" theme for this recipe and enable the advanced features.

After clicking OK the window changes to:

download

  • Fill in the input fields labelled Path to Demos and Editor Program
  • Path to Demos - Defaults to the location of the Demo when you run it the first time. You can leave unchanged if this program is going to remain with the other demos. Use an absolute path.
  • Windows - it's not an EXE but a batch file. It will look something like this: C:\Program Files\JetBrains\PyCharm Community Edition 2020.3\bin\pycharm.bat
  • Linux - it's a bit trickier. It may resemble something like this: /home/mike/.local/share/JetBrains/Toolbox/apps/PyCharm-C/ch-0/202.8194.15/bin/pycharm.sh
  • Mac - I dunno yet.... there's an open Issue on GitHub asking for help from Mac user
  • Windows - Something along the lines of C:\Program Files\NotePad++\notepad++.exe
  • Windows - c:\windows\notepad
  • Linux - /usr/bin/notepad
  • Assuming your editor is invoked using "editor filename" when you can use any editor you wish by filling in the "Editor Program" field with a path to the editor executable

NOTE - if you want to be able to use the Edit button to open to a specific line number, then you will need to setup the editor in the PySimpleGUI Global Settings. You can access the PySimpleGUI Global Settings from Test Harness by calling sg.main() . There is a button labelled "Global Settings". There is already a lot of duplication of settings happening between this browser and the PySimpleGUI global settings. Once you've got the global settings made, then you don't need to make any chnages to the seettings in the browser program. You can leave them all blank and the settings will come from the PySimpleGUI global settings.

These are some of the important part of the window that are not as obvious as other parts.

download

Verbose mode will show you the full matching line from the file. This is handy for when you're looking for a specific way something is used.

By default the Verbose mode is turned off. This is because search results are updated in realtime as you type characters. If your project tree is large then your verbose output will be very very large as you type the first few characters of your search.

The best way to use the Verbose feature is to perform the search with it turned off. Once you get the list of files from your search, then click verbose to see the more detailed view of the results.

In this example, I've searched for the demos that use the Graph element. Searching for "sg.Image(" will return the demos that make this element.

download

If I then uncheck the "Show onlyu first match in file" then I can see when multiple matches are found in a file.

download

In verbose mode and all matches are shown, when a file is selected from the list and the "Edit" button is clicked, then another window will show you the list of lines that matched and allows you to click on the line to be taken to. Selecting a line will open your editor to that line.

download

NOTE - this feature is 99% complete! The lines shwon in the "Open Editor" window don't yet show the code that is contained on each of those lines. Comoing VERY SOON!

If you have an explorer program specified in the settings or in the PySimpleGUI Global Settings, then choosing a file and clocking the "Open Folder" button will launch the file browser that you've specified and open the folder that the file is contained in.

Recipe - A Simple & Standard Right Click Menu

You'll find that many/most of the PySimpleGUI Demo Programs that are newer have a standard right click menu added to them with these 3 items:

There are several pre-defined right-click menus included with PySimpleGUI. To get the one that includes these 3 options, add this parameter to your Window creation call.

If you right click your Window, you'll see a menu that looks something like this:

image

In the PySimpleGUI code, the constant MENU_RIGHT_CLICK_EDITME_VER_EXIT makes this menu definition:

When you're developing your code and even after it's done, sometimes you'll see something while the code is running that triggers you to want to make a change. Maybe it's a bug fix, a mispelling (sic), or a new feature idea.

The problem you face now is.... where's the source code?

The Edit Me item launches the editor you've specified in the PySimpleGUI Global Settings and opens the file in that editor.

2 mouse clicks and you're editing your code.

In order for this feature to work, you'll need to add these 2 lines to your event loop:

You don't need to modify them. Just add them as they are to your PySimpleGUI programs

This is another runtime question that is often handy to know without having to look - "What version of PySimpleGUI, Python and tkinter is this running again?"

To add this feature, add these 2 lines to your event loop:

You'll see something like this:

image

This one is easy. It's particularly good for "Desktop Widgets" that have no titlebar and thus have no "X" to click to exit the program. If your event loop already has a change for the event "Exit" then you don't need to do anything to get this feature.

Recipe - No Console Launching

You've just coded up your nice GUI, ready for that "Windows experience".... you double click your .py file in Windows explorer and up comes 2 windows, a console and your GUI Window.

If you're ready for a more Windows-like experience for you and your users, then these steps should get you there.

There are a couple of simple tricks needed.

Rename Your .py to .pyw

  • Rename your .py file to .pyw
  • Launch it using pythonw.exe instead of python.exe

When you right click on your .pyw file, you'll want to associate it with pythonw.exe if that's not already been done by Python for you when it was installed.

Right click your .pyw file and choose "Properties"

You'll see a window like this which will tell you what will open the file if you double click it. You can click the "Change..." button to change what opens the file.

image

Make A Shortcut

You've learned how to use explorer to double-click and launch your GUI window without a console. Let's go 1 step further.

If you were to simply drag your .pyw file to your taskbar to "pin" it for quick launching, unfortunately that doesn't work. It'll try and launch Python instead.

What we're going to do is make an icon/shortcut to your python program that you can place anywhere AND you can also pin it to your taskbar.

To make a shortcut, right click your .pyw file and choose "Create Shortcut". It's near the end of the list of right click options

image

My program is called Demo_Desktop_Widget_Launcher_Bar.pyw . After I created the shortcut, a file named Demo_Desktop_Widget_Launcher_Bar.pyw - Shortcut was created in the same folder.

You should now do these 2 operations on that shortcut 1. Rename it something that looks like any other program 2. Choose an icon for your shortcut. On windows, this needs to be a .ICO file 3. Set a specific program that opens it (your pythonw.exe file)

I named my shortcut "Launcher".

Because I wanted the 3.9 version of Python to open this specific program, I added pythonw.exe part to the target field in the properties. After the pythonw.exe add your full path to your .pyw file. If there are any spaces, put "" around it. It should look something like this:

image

In my folder with my program, I now see the shortcut with the icon I chose earlier

image

Double-clicking this icon will start your .pyw file without a console. It will look "like a real windows program"

Pin Your Shortcut

If you want to be able to quickly launch your program, you can "pin" your shortcut to your taskbar. To do this, you can drag and drop the icon onto the taskbar. Or, you can right click the icon and choose "pin to taskbar".

After pinning it, I see this as my taskbar. The launcher icon is there ready to be clicked. When I click it, the program runs without any console windows.

image

This particular .pyw file is the Demo Launcher Bar. Clicking the icon launches this launcher.

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.

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"

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

SNAG-0620

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

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.

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:

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

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 - Post your screen-shots (PLEASE!)

This is an odd recipe, but it's an important one and has nothing to do with your coding FreeSimpleGUI code. Instead is has to do with modifying youre readme.md file on your GitHub so you can share with the world your creation. Doon't be shy. We all stated with "hello world" and your first GUI is likely to be primitive, but it's very important you post it any way.

In case you've not noticed, you, the now fancy Python GUI programmer that you are, are a rare person in the Python world. The VAST majority of Python projects posted on GitHub do not contain a GUI. This GUI thing is kinda new and novel for Python pbeginning rogrammers.

They don't have to be what you consider to be "pretty pictures" or of a "compex GUI". GUIs from beginners should be shown as proudly developed creations you've completed or are in the process of completion.

Your GitHub visitors may never have made a GUI and need to see a beginner GUI just as much as they need to see more complex GUIs. It gives them a target. It shows them someone they may be able to achieve.

This is one of the easiest / laziest / quickest ways of adding a screenshot to your Readme.md and this post on your project's main page.

Here'show you do it:

  • Open a "Screenshots" Issue somehwere in GitHub. It sdoesn't matter which project you open it under.
  • Copy and paste your image into the Issue's comment section. OR Drag and drop your image info the comment section. OR click the upload diaload box by clickin at the bottom on the words "Attach files by dragging & dropping, selecting or pasting them.
  • A line of code will be inserted when you add a the image to your GitHub Issue's comment. The line of code will resemble this:
  • Copy the line of code that is created in the comment. You can see this line when in the "Write" mode for the Issue.. If you want to see how it'll look, switch to the preview tab.
  • Paste the line of code from the Issue Comment into your readme.md file located in your mtop-level FirHub folder

Note, if you simply copy the link to the image that's created, in your readme.md file you will see only the link. The image will not be embedded into the page, only the link will be shown The thing you paste into your readme needs to have this format, theat starts with ![filename] .

Pasting the above line directly into this Cookbook resulted in this Weahter Widget posted::

image

The same technique is used as above, except in the line of code, you'll insert the URL of your image where every that may be inside the ( )

![image](http://YourLinkToYourImage.jpg)

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".

image

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

SNAG-0549

Modifying and creating your own theme is not difficult, but tricky so start with something and modify it carefully.

The tkinter port has the theme_add_new function that will add a new dictionary entry into the table with the name you provide. It takes 2 parameters - the theme name and the dictionary entry.

The manual way to add a dictionary entry is as follows....

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

A single entry in this dictionary has this format (copy this code):

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

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.

Produces these 2 windows

image

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:

image

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.

image

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:

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.)

Here's the search results for "red x icon" using Bing with a filter.

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.

Both are in the Demos folder (Demos.PySimpleGUI.org)

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.

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.

This is the window the code below creates using a button graphic.

image

You can run similar code online on Trinket

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.

SNAG-0550

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.

Why recreate the wheel? There's a Popup function that will get a Filename for you. This is a single-line GUI:

Shows this window and returns the results from the user interaction with it.

image

The entire Popup based solution for this get filename example is:

How about a GUI and traditional CLI argument in 1 line of code?

This is related to the topic of "User Defined Elements" if you care to go look it up.

If you're using PyCharm, this technique works particuarly well because the DocStrings continue to work even after you have created aliases.

Aliases are used a LOT in PySimpleGUI. You'll find that nearly all of the Elements have multiple names that can be used for them. Text Elements can be specified as Text , Txt , and T . This allows you to write really compact code.

You can make your own aliases too. The advantage of you making your own is that they will be in your own name space and thus will not have the typical sg. in front of them.

Let's use the cprint function as an example.

Normally you'll call this function like this:

If you have a lot of these in your program, it won't get too long until you're tired of typing sg.cprint , so, why not make it super easy on yourself and type cp instead. Here's all you have to do.

Running these 2 calls produced these 2 lines of text in a Multiline element

image

IF you're using PyCharm and press Control+Q with your cursor over the cp , you'll see the documentation brought up for the cprint call:

image

Feel free to experiment. Even renaming elements will save you the hassle of typing in the sg. portion. Then again, so will importing the invdividual elements.

Recipe - Highly Responsive Inputs

Sometimes it's desireable to begin processing input information when a user makes a selection rather than requiring the user to click an OK button.

Let's say you've got a listbox of entries and a user can select an item from it.

image

When you choose a color and click OK, a popup like this one is shown:

image

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:

image

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.

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.

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.

On the Windows operating system, it's possible to create your window on monitors other than your primary display. Think of your primary display as a single quadrant in a larger space of display area. The upper left corner of your primary display is (0,0).

If you wish to locate / create a window on the monitor to the LEFT of your primary monitor, then set the X value to a negative value. This causes the window to be created on the monitor to the left. If you set your X value to be larger than the width of your primary monitor, then you window will be created on the monitor that is located to the RIGHT of your primary monitor.]

I don't know if this technique works on Linux, but it's working great on Windows. This technique has been tried on a 4-monitor setup and it worked as you would expect.

To use this feature, rather than using the default window location of "centered on your primary screen", set the location parameter in your Window creation to be the location you wish the window to be created.

Setting the parameter location=(-500,330) in my Window call, set the location of the window on my left hand monitor.

Experimenting is the best way to get a handle on how your system responds.

It would be great to know if this works on Linux and the Mac.

This code is from a Demo Program named Demo_Window_Location_Finder.py and will help you located the x,y position on your monitors. Grab the yellow square with your mouse to move the tool around your screen. The 4 arrows point to the direction indicated

image

Recipe - Element Justification and Alignment

There are 2 terms used in PySimpleGUI regarding positioning: * Justification - Positioning on the horizontal axis (left, center, right) * Alignment - Positioning on the vertical axis (top, middle, bottom)

Justification of elements can be accomplished using 2 methods. 1. Use a Column Element with the element_justification parameter 2. Use the Push element

The Push was added in 2021 to the tkinter port. The PySimpleGUIQt port already has an element called Stretch that works in a similar way. You could say that Push is an alias for Stretch , even though Stretch wasn't a tkinter element previously.

The way to think about Push elements is to think of them a an element that "repels" or pushes around other elements. The Push works on a row by row basis. Each row that you want the Push to impact will need to have one or more Push elements on that row.

Normally, each row is left justified in PySimpleGUI (unless you've set a parameter in the Window object or the row is in a Column element that has a setting that impacts justification.

Think of the sides of a window as a wall that cannot move. Elements can move, but the side-walls cannot. If you place a Push element on the left side of another element, then it will "push" the element to the right. If you place a Push on the right side, then it will "push" the element to the left. If you use TWO Push elements and place one on each side of an element, then the element will be centered.

This recipe demonstrates using a Push element to create rows that have different justification happening on each row.

The first row of the layout is 50 chars so that the window will be wide enough that each row's justification will have some room to move around.

The second row doesn't need a Push element in order for the element to be left justified. However, if your entire window was right justified, then using the Push on the right side of an element would push it to be left justified.

Notice the last row of the layout. There are 2 buttons together with a Push on each side. This causes those 2 buttons to be centered.

image

Container Element Justification ( element_justification parameter)

You can use Container Elements (Column, Frame, Tab and Window too) to justify multiple rows at a time. The parameter element_justification controls how elements within a container or Window are justified.

In this example, all elements in the window are centered

image

"Alignment" is the term used to describe the vertical positioning of elements. Within a single row, alignment is performed by using a container element or by using a one of the alignment "layout helper functions". You'll find the layout helper functions in the call reference documentation here: https://pysimplegui.readthedocs.io/en/latest/call%20reference/#layout-helper-funcs

There are 3 functions in particular that affect vertical positioning: * vtop - Align an element or an entire row to the "top" of the row * vbottom - Align an element or an entire row to the "bottom" of the row * vcenter - Align an element or an entire row to the "center" of the row

By default the alignment on each row is center.

This program uses the default alignment which will center elements on each row.

image

If you want to have the Listbox and the Multiline aligned at the top, then you can use the vtop helper function. Since the Listbox is the shorter height, you could add vtop just to that element. Or, you can use vtop and pass in the entire row so that if the size of one of these elements changes in the future so that the Multiline is shorter, they'll remain top aligned.

If the elements on that row were top-aligned, the window will look like this:

image

Here are 3 ways you can accomplish this operation.

Align only the single element

Align the entire row

Notice how using vtop in the example above replaces the entire row with just the vtop call. The reason for this is that the vtop function returns a list (i.e. a row). This means that brackets are not needed. But it looks a little odd and makes it more difficult to see where the rows are.

Newer versions of PySimpleGUI allow an extra set of brackets [ ] so that the layout appears to still be a list-per-row.

Just like the Push element will "push" elements around in a horizontal fashion, the VPush element pushes entire groups of rows up and down within the container they are inside of.

If you have a single VPush in your layout, then the layout will be pushed to the top or to the bottom. Normally layouts are top-aligned by default so there's no need to have a single VPush at the bottom. If you have two VPush elements, then it will center the elements between them.

One of the best examples of using VPush is when a window's size has been hard coded. Hard coding a window's size is not recommended in PySimpleGUI. The reason is that the contents inside may not fit inside your hard coded size on some computers. It's usually better to allow the window's size to "float" and be automatically sized to fit the contents.

Perhaps a better example would be if you wanted to allow your window to be resized and have the contents vertically aligned after resizing.

But, if you're determined to hard code a size and want to vertically center your elements in that window, then the VPush is a good way to go.

This example window is 300 pixels by 300 pixels. The layout is both center justified and center aligned. This is accomplished using a combination of Push and VPush elements.

image

Recipe - Clean Simple Inputs

Many of our first GUIs involve collecting small bits of information and then continuing on with processing that input. They are simple programs that are quick for beginners to knock out and get a few accomplishments so their confidence builds.

The most basic of these are layouts that have a Text Element and an Input Element. This is a basic "form" the user fills out. Maybe you've got code that looks like this already.

image

One easy addition to your layout is to "push" each input row to the right. The effect is quite nice and the implementation involves one simple operation - add a Push element to the start of each row that has an Input

The change looks like this:

And the result is surprisingly pleasant.

image

If you really want to get clever and save time as well, you can make a 1-parameter change to your Window definition and get a similar result. The one difference is that the buttons will also get pushed over.

image

Recipe - Printing

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

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.

Printing 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.

There are at least 3 ways to transform your print statements that we'll explore here 1. The Debug window 2. The Output Element 3. The Multiline Element

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

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.

SNAG-0744

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.

image

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.

image

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" exprint 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

Added in version 4.25.0 was the ability to re-route stdout and stderr directly to any Multiline element. This is done using parameteres when you create the multiline or you can call class methods to do the rerouting operation after the element is created.

Since you may not be able to always have access to the window when printing, especially in code that it not your own code, another parameter was added auto_refresh . If set to True then the window will automatically refresh every time an update is made to that Multiline element.

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:

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

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

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:

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:

It produces this window:

image

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.

If you were to use a funciton, then your code my look like this:

A named lambda expression would perhaps resemeble this:

Putting it all together into a single block of code for you to copy and run results in

Recipe 3C - Rerouting stdout and stderr directly to a Multiline

This was made available to the tkinter port in version 4.25.0.

The eaiest way to make this happen is using parmaters when creating the Multline Element

  • reroute_stdout
  • reroute_stderr

If you wish to reroute stdout / stderr after you've already created (and finalized) the Multline, then you can call reroute_stdout_to_here to reroute stdeout and reroute_stderr_to_here to reroute stderr.

To restore the old values back, be sure and call restore_stdout and restore_stderr

This has a risky component to this.

Warning Regarding Threading and Printing

If programs outside of your control are running threads and they happen to call print, then the stdout will be routed to the window. This MAY cause tkinter to crash.

Your thread, by calling print, will trigger code inside of PySimpleGUI itself to be executed. This code can be significant if the stdout has been re-rerouted to a multiline element that has auto-refresh turned on for example. It is unclean how many operations or queued or if the calls from the threads will directly impact tkinter.

The point here it to simple be on the looking for the dreaded "tkinter not in the mainloop" error

This method was added to PySimpleGUI tkinter port in June 2020 and needs to be ported to the other ports still.

The idea is have a function, cprint that looks and acts like a normal print.... except, you can "route" it to any multiline element. There are 2 ways to do routing.

  • Call cprint_set_output_destination(window, multiline_key) to tell PySimpleGUI where the output should go
  • Indicate the output location directly in the cprint call itself

The color portion of the cprint call is achieved through additional parameters that are not normally present on a call to print. This means that if you use these color parameters, you cannot simply rename your cprint calls to be print calls. Of course you can safely go the other direction, renaming your print calls to call cprint .

While covered in "cprint", this trick can save you MASSIVE amount of typing. It works well in PyCharm too.

Would I do this in a huge production code base. No, but I'm wring a little 100 line packet of fun.

IF you're tire of writine sg.xxxxx as much as I am, then maybe you'll like this hack too.

Through simple assignment, you can rename PySimpleGUI functions. You add them to your local name space so you no longer need the sgl. part.

For example. I'm tired of writing sg.cprint . I can fix this by adding a line of code to make an alias and then using the aliase insteast.

I could even make it super short.

Now all I call is cp('This is what I want to print') The cool thing about PyCharm is that it knows these are the same and so the DOCSTRINGS work with them!!

Yes, you can rename the entire Elements ane still get all the documentation as you type it in.

So that you don't have to type: sg.cprint every time you want to print, you can add this statement to the top of your code:

cprint = sg.cprint

Now you can simply call cprint directly. You will still get the docstrings if you're running PyCharm so you're not losing anything there.

This Recipe shows many of the concepts and parameters. There is also one located in the Demo Programs area on GitHub (http://Demos.PySimpleGUI.org).

Beginning in verison 4.25.0 of the tkinter port you'll find new parameters for the Multline Element that makes the job of re-routihn your output much easier. Rather than calling the cprint_set_output_destination function, you will use the Multline element's initial parameters to both setup the routing of the print output, but also mark the element as being a write-only element. You can set the parameter write_only to True in order to make this a write-only Multiline.

The new parameters you'll be interested in are:

  • auto_refresh
  • reroute_cprint

This will cut out the call previously required to set up the routing. You will be setting up the routing through the Multiline creation ifself.

You will continue to be able to manually route stdout and stderr to the Multline uning the reroute_stdout_to_here call. Sorry about the wordiness of the call, but you're probably only going to have one in your code. So it didn't seem so bad to have something descriptive enough that you won't need a comment.

Automatic Refresh

The Multiline element has an option for auto-refreshing after an update. The Output element automatically refreshes after each write. Hopefully this will not slow things down considerably.

Here is the code for 4B

Recipe - Save and Load Program Settings

There is an entire set of API calls now available to you in PySimpleGUI to help with "settings".

Please check out the demo programs as there are numerous demos that have calls to the settings APIs.

There is also a section in the main documentation about these APIs. They are detailed in the call reference as well.

The basics are that in your layout or before your layout, you'll read your settings. If your program changes any settings, they will immediately be saved to your settings file. You never have to worry about loading or saving the settings file. It happens automatically. Just start calling the get and set calls if using the "function interface".

If you do not set a filename, then the name of your .py or .pyw file will be used. Beware, however, that turning your program into an EXE can impact the settings file as your filename won't look the same to the Python code. If you're going to turn your code into an EXE, then it's best to explicitly set the filename.

This statement sets the filename. Note that the path is not indicated in this example. PySimpleGUI will store all the settings in the default settings folder if you don't specify one.

Reading a setting can be as easy as this call:

The first parm is the "key" and the second is the default value if no setting is found.

Saving a setting can be done with this call:

Take a look at the main documentation for the Object interface if you would prefer it over the function based interface. These API calls are used in any demo program that has settings and for all PySimpleGUI projects that have settings. They're super SIMPLE to use and work well.

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.

image

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.

image

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.

Recipe - Long Operations - Multi-threading

Important gui topic.

Brief summary:

PySimpleGUI can help you with running long operations as threads without you needing to learn the threading library. The Window method perform_long_operation makes this serious GUI problem a non-issue.

Threads can "inject" events and data into a window.read() call. This allows your GUI application to simply stop, pend and awaken immediately when something happens. This makes for zero CPU time used when northing's happening and it means 0ms latency. In other words, you're not polling, you're pending.

The Long Operation

A classic problem of GUI programming is when you try to perform some operation that requires a lot of time. The problem is simple enough.... you have a GUI and when you press a button, you want a 10 second operation to take place while you're GUI patiently waits.

What happens to most people that give this a try gets the dreaded Windows/Linux/Mac "Your program has stopped responding do you wish to close it"

If you add a sleep(30) to your code, it's not very many seconds before your window does this:

SNAG-0866

To get you over the initial hump of multi-threaded programming, you can let PySimpleGUI create and manage threads for you. Like other APIs in PySimpleGUI, it's been simplified down as far as possible.

Here's the basic steps using perform_long_operation 1. Pass your function name and a key to the call to window.perform_long_operation 2. Continue running your GUI event loop 3. Windows pend using their typical window.read() call 4. You will get the event when your function returns 5. The values dictionary will contain your function's return value. They key will be the same as the event. So, values[event] is your function's return value.

What if my function takes parameters?

Note that the first parameter for perform_long_operation is your function. If you're like most of us, you'll enter my_func() instead of my_func . The first actually calls your function immediately, the second passes your function's object rather than calling it.

If you need to pass parameters to your function, then you'll need to make one simple change... add a lambda. Think of it as how you would want your function called.

In the Demo Program for this call, Demo_Long_Operations.py , it uses a function that takes parameters as the example. Here is the line of code from that demo:

I've broken the code up with newlines to emphasize where your function call goes. A more common format may be:

Here is the function definition that is to be called:

If you're ready to jump on into threading, then you can do that too.

Here's the basic steps 1. You put your long-running operation into a thread 2. Your thread signals the window when it is done 3. Windows pend using their typical window.read() call 4. The values dictionary will contain your function's return value if you pass it through

Take a moment to get to know the code. You'll find the typical event loop. If you run this program, and you don't touch anything like your mouse, then it should sit for 10 seconds doing nothing and then print out the completed the message.

SNAG-0867

If you attempted to interact with the window by pressing the "Nothing" button, then you will likely get a message about your window stopped responding.

Threaded Long Operation

I think we can agree that brute force, no matter how badly we want it to work, won't. Bummer

If you click the "Nothing" button, then you'll get a line printed in the Multiline that has the event and the values dictionary.

Because there are no "input" elements, your values dictionary is empty.

Clicking "Go" is when the fun begins.

You are immediately shown a message that the long-operation function is starting. The same function name as before is called long_function . But now the contents of that function have been replaced with starting a thread that executes the same code.

This single line of code is all that was needed to create our long0runing function as a thread and to start that thread:

The conversion over to a thread was done in 3 simple steps:

  • Renamed the long_fundtion to long_function_thread
  • Pass into the long_function_thread the window that it will communicate with
  • Add call to window.write_event_value when the long_running_thread is existing

The result is a GUI that continues to operate and be responsive to user's requests during the long running operation.

Long operations with feedback

The power of the Window.write_event_value is that it can be used at any time, not just at the beginning and end of operations. If a long operation can be broken into smaller parts, then progress can be shown to the user. Rather than calling Window.write_event_value one time, it can be called a number of times too.

If we modify the code so that instead of sleeping for 10 seconds, we sleep for 1 second 10 times, then it's possible to show information about progress.

Here's the code with the new operation broken up into 10 parts

And the resulting window

image

Recipe - convert_to_bytes Function + PIL Image Viewer

This function has turned out to be one of the best for working with images in PySimpleGUI.

It requires 3 packages - PIL, io, and base64. PIL is the only one you'll need to pip install.

PySimpleGUI does not directly use the PIL package so that PySimpleGUI can remain highly portable. Requiring users to install PIL was simply not acceptable for the package, but it's fine for demo programs and helper functions like this one.

One thing that PIL buys you is the ability to work with a LOT more file formats. If you want JPG images, then you want to use PIL as the tkinter based PySimpleGUI only supports PNGs and GIFs (because that's all tht tkinter supports)

convert_to_types is a fantastic little function because you can give it a filename or a bytes string and it will return a bytes string that is optionally resized.

This makes working with button images MUCH MUCH easier.

Here are a couple of demos that use this function. The first one is a Matplotlib previewer. It creates a grid of graphs

SNAG-0872

These shots are from the demo that you'll see the source code to below. Note the "Resize to" field below the file list.

SNAG-0873

As an example of one way to use this function, included here is the Demo Program you'll find in the demo programs area on the GitHub:

One particuarly good use of this function is when you want to add a graphic to a button. This function will convert images of any format into a byte string that can be passed into your Button element when you create it.

Let's say you want to user the PySimpleGUI icon as a button. You can do that easily enough using this statement:

But maybe your application has button images that are all 40 x 40 pixels. In that case, you simply pass this image to the convert function along with the new size you want it to be.

The result are these 2 buttons:

image

Setting elements to be invisible and visible again has been a big challenge until version 4.28.0 of the tkinter port of PySimpleGUI. This is when the pin function was added. This function will "pin" an element to a location in the layout. Without this pin, then the element may move when made inivisible and visible again. There was also a problem of the space not shrinking when make from visible to invisible. With the pin function, this problem was solved. There is a small, 1 pixel, cost to this operation. When the element is invisible, there will be a single pixel where it is pinned. These may add up if you have 40+ rows of invisible elements. This is not typical however so it tends to work pretty well.

This recipe shows how to use invisible elements to create a window with 2 sections that can be collapsed down to a single line with an arrow on it. You could just as easily make the entire section totally disappear if you wanted. In other words, you're not limited to using invisible elements in this way only.

You will also find this program in the Demo Programs section on GitHub.

Beginning in version 4.28.0 you'll find that working with multiple windows in the tkinter port of PySimpleGUI to be much much easier.

This Recipe shows 2 windows. Both of them are active and can be interacted with. When you enter something in window 1 it is updated in window 2. Notice that the keys are named the same in both windows. This makes it really easy to write generic code that will update fields in either window, the only difference will be which Window is updated.

You'll find that you'll have less chances for problems like "reusing layouts" if you put your layout and window creation into a function. This will guarantee a "fresh" window every time you call the function. If you close window 2 and then click the "Reopen" button in window 1, then all that is needed is to call the make_win2 function again and move the new window to the location below the first window.

The program remains active until both windows have been closed.

As of June 2022, this window represents all 33 of the PySimpleGUI elements in a single window. It takes about 70 lines of code to show all of the elements in this one window.

The code isn't as practical as what you'll find in the Demo Programs. This use of the elements is shortened and doesn't show how each is used in a typical way.

image

Custom Titlebar and Menubar

The checkbox at the top of the left column can be checked in order to display the window with the custom titlebar and custom menubar

Can use to preview Themes

One practical use of this Demo Program is that you can preview how the elements look when using a specific theme by choosing the theme using the Combo element in the window.

For example, choosing the DarkGrey13 theme, with the custom titlebar checked, the window is replaced with one using that theme. Very nice!

image

Recipe - Exception handling of a console-less application

Some applications, such as those that run in the system tray or are "Desktop Widgets" are meant to run entirely without a console. On Windows, they're often named with a .pyw extension. This is challenging in a couple of ways.

  • These programs run for days rather than moments
  • They have no console to output to

Debugging an intermittent problem is difficult when using plain Python for an application like these. Normally you would need to use a debugger so that the crash is caught when it happens or use a logging module that writes to disk.

With PySimpleGUI there are a number of simple ways to handle these types of errors, assuming that PySimpleGUI itself has remained functional.

Numerous popup calls are available to output information to a popup window. If you want to output a lot of information that you can also copy and paste from, then a popup_scrolled call is a good choice. However, there's an ever better technique.

The Debug Print Window is One of the easiest ways to get the information to help you debug the problem. To output to this window, call the function sg.Print in the same way you a normal print . It accepts similar parameters including sep and end as well as some PySimpleGUI specific ones that enable printing in color.

One advantage that the Debug Print has over popups is that you can output the information using multiple calls. Each time you call sg.Print , the information will be added to output that's already in the Debug Print Window. You will be able to copy and paste from this window to another application should there be a log or some other information that you can to save. Maybe you want to loop through a list and print certain items as part of the information to display. Using sg.Print will enable you to easily do this.

Use the wait / blocking parameter!

Be sure and set the wait parameter to True in the last call you make to sg.Print . The reason for this is that if you do not, the call will output to the window and then immediately return and your program will likely continue on and exit. Adding wait=True will output to the Debug Window and then wait for you to click the Continue button in the window before the call will return.

This example will crash when you click the "Go" button.

If this program was launched by double clicking a .pyw file or some other technique that doesn't involve a debugger or command line, then what you would see is this:

Your window would disappear and you would have nothing to help you understand why. This is why PySimpleGUI uses a popup window for errors that are encountered internally instead of raising an exception.

Here is the same program, but we've added a try block around the entire event loop. A total of 3 line of code were added. 1. The try statement 2. The except statement 3. The sg.Print call to output to the Debug Window

This time the experience enables you to understand why and where your program crashed. It's clearly there's a problem with the call to bad_call

With the Debug Print, you're able to output information about the exception which certainly helps. Because PySimpleGUI was written for you, a Python developer, there's a popup call that you can add to make your life even easier !

We'll change the exception handling portion this time to be these 2 lines of code:

We're still print to the Debug Window, but we've removed the wait parameter because the popup call immediately after it will stop the program from exiting. The popup we've added is popup_error_with_traceback . This call will show you more detailed information about where the problem happened, and more conveniently, enable you to open your editor to the line of code that caused the problem. You will need to add your editor's information in the PySimpleGUI globals settings for this feature to work, so be sure and fill in this information.

Now our experience changes considerably. We get the Debug Window as before, but we also get a popup that has a "Take me to error" button that will open your editor to the line of code where you called the popup. The exception information is included in the popup because we added it when calling the popup.

This popup saves you the time of locating where on your computer the .py or .pyw file is located. Just click the button and your editor will be launched with the correct filename and you'll be taken to the line of code. You also get, for free, an attempt at humor with an unhappy looking emoji.

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.

image

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.

image

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.

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.

image

Recipe - one_line_progress_meter

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

image

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.

If you want to enable the user to break out of your loop, then you will need to take action. one_line_progress_meter returns False if the cancel button is clicked or the window is somehow closed. The way you can turn the user's click on the Cancel button into cancelling the loop is by checking the return value and then breaking from your loop.

You've seen how the user can cancel the progress meter, now let's look at how your program can cancel the progress meter. Maybe you got an error 1/2 way through the processing and you want to stop the meter. To cancel the one_line_progress_meter ... I bet you can't guess what function you would call....

Care is neeeded when it comes to the parameters after the first 3 parms. You can add any number of variable arguments to be shown in the progress meter window.

The first 3 parms are required. Then there are any number of parms you can add to your progress meter window. After those then there are other parameters after the variable numbered *args. Here's the definition (see the Call Reference Documentaion for the most up to date version)

If you wanted your meter to be horizontal instead of vertical and include some additional information, then your call may look like this:

If you have only 1 one_line_progress_meter running at a time, then you don't need to set a key. The default keyt is fine. If you want multiple windows running simultaneously, then you will need to set keys for each window. You will need to use the same keys for cancelling the meter early.

Here's the example with the cancel using a custom key:

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.

image

Here is the code for the above window

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 FreeSimpleGUIWeb)

image

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.

media player

This program will run commands and display the output in an Output Element. There are numerous Demo Programs that show how to lauch subprocesses manually rather than using the newer Exec APIs.

script_launcher

Very simple script that will launch a program as a subprocess. Great for making a desktop launcher toolbar. In version 4.35.0 of PySimpleGUI the Exec APIs were added. These enable you to launch subprocesses

A standard non-blocking GUI with lots of inputs.

machine learning green

Perhaps you don't want all the statistics that the EasyProgressMeter provides and want to create your own progress bar. Use this recipe to do just that.

script_launcher

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.

cookbook columns

This simple program keep a window open, taking input values until the user terminates the program using the "X" button.

This Recipe has a number of concepts. * Element name aliases - Txt and In are used in the layout * Bind return key so that rather than clicking "Calculate" button, the user presses return key * No exit/close button. The window is closed using the "X" * Dark Green 7 theme - there are some nice themes, try some out for yourself * try/except for cathing errors with the floating point * These should be used sparingly * Don't place a try/except around your whole event loop to try and fix your coding errors * Displaying results using a Text element - Note: be sure and set the size to a large enough value

math_game

You can easily build "compound elements" in a single like of code. This recipe shows you how to add a numeric value onto a slider.

Recipe - Multiple Windows

There are numerous Demo Programs that show a multitude of techniques for running multiple windows in PySimpleGUI. Over the years these techniques have evolved. It's best to check with the Demo Propgrams as they are updated more frequently than this Cookbook.

This recipe is a design pattern for multiple windows where the first window is not active while the second window is showing. The first window is hidden to discourage continued interaction.

The Canvas Element is one of the few tkinter objects that are directly accessible. The tkinter Canvas widget itself can be retrieved from a Canvas Element like this:

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.

canvas

Just like you can draw on a tkinter widget, you can also draw on a Graph Element. Graph Elements are easier on the programmer as you get to work in your own coordinate system.

graph recipe

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)

image

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.

image

Clicking "Plot" will create the Matplotlib window

image

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.

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.

animated matplotlib

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.

timemanagement

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.

password entry

Hiding your windows commmand window

If you would like your python program to run without showing a console window, then you can name your file with a .pyw extension and open the file using pythonw instead of python . This is the preferred way to launch a final version of a PySimpleGUI program as there is no need for a Console window and it will be a much more "Windows-like" experience.

Floating toolbar

NOTE - Please look in the Demo Programs that use the newer Exec APIs. This Recipe uses an older technique to launch subprocesses. You'll find the Exec APIs documented in the main documentation and the Call Reference.

"Launchers" have come a long long ways since the early days of PySimpleGUI. This recipe directly calls subprocess.Popen . In 2020 a new set of APIs, the Exec APIs, were added to PySimpleGUI. These calls simplify the subprocess calls thus making them more approachable for newcomers to Python.

toolbar gray

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

toolbar black

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.

timer

Like the Timer widget above, this script can be kept running. You will need the package psutil installed in order to run this Recipe.

The spinner changes the number of seconds between reads. Note that you will get an error message printed when exiting because the window does not have have a titlebar. It's a known problem.

cpu widget 2

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()

tear off

Use the Graph Element to draw points, lines, circles, rectangles using your coordinate systems rather than the underlying graphics coordinates.

In this example we're defining our graph to be from -100, -100 to +100,+100. That means that zero is in the middle of the drawing. You define this graph description in your call to Graph.

graph markers

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.

tabs

NEW in 2021 was the release of the psgcompiler project. This is a front-end to the popular PyInstaller package. psgcompiler adds a PySimpleGUI GUI front-end to PyInstaller, making it easier for you to create binary versions of your code for distributing to people that do not have Python stalled on their system.

The psgcompiler will eventually support multiple back-ends. At the moment, only PyInstaller is supported. A HUGE "THANK YOU" to the PyInstaller project for making a brilliant program that enables Python programmers to share their work with non-Python users.

psgcompiler makes it 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.

You can also make APP files for the Mac and binary distributable for Linux as well. However, in order to do so, you must run the program on the OS you are targeting. In other words it is not a cross-compiler. You cannot run psgcompiler / PyInstaller on Windows and produce a Mac executable.

If you want to directly user PyInstaller instead of psgcompiler, then you can install the packages separately and use PyInstaller directly.

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.

The PySimpleGUI Organization

This documentation as well as all PySimpleGUI code and documentation is Copyright 2018, 2019, 2020, 2021, 2022 by PySimpleGUI.org

Send correspondence to [email protected] prior to use of documentation

From here you can search these documents. Enter your search terms below.

Keyboard Shortcuts

Keys Action
Open this help
Next page
Previous page
Search

Fix "local variable referenced before assignment" in Python

might be referenced before assignment pycharm

Introduction

If you're a Python developer, you've probably come across a variety of errors, like the "local variable referenced before assignment" error. This error can be a bit puzzling, especially for beginners and when it involves local/global variables.

Today, we'll explain this error, understand why it occurs, and see how you can fix it.

The "local variable referenced before assignment" Error

The "local variable referenced before assignment" error in Python is a common error that occurs when a local variable is referenced before it has been assigned a value. This error is a type of UnboundLocalError , which is raised when a local variable is referenced before it has been assigned in the local scope.

Here's a simple example:

Running this code will throw the "local variable 'x' referenced before assignment" error. This is because the variable x is referenced in the print(x) statement before it is assigned a value in the local scope of the foo function.

Even more confusing is when it involves global variables. For example, the following code also produces the error:

But wait, why does this also produce the error? Isn't x assigned before it's used in the say_hello function? The problem here is that x is a global variable when assigned "Hello ". However, in the say_hello function, it's a different local variable, which has not yet been assigned.

We'll see later in this Byte how you can fix these cases as well.

Fixing the Error: Initialization

One way to fix this error is to initialize the variable before using it. This ensures that the variable exists in the local scope before it is referenced.

Let's correct the error from our first example:

In this revised code, we initialize x with a value of 1 before printing it. Now, when you run the function, it will print 1 without any errors.

Fixing the Error: Global Keyword

Another way to fix this error, depending on your specific scenario, is by using the global keyword. This is especially useful when you want to use a global variable inside a function.

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

Here's how:

In this snippet, we declare x as a global variable inside the function foo . This tells Python to look for x in the global scope, not the local one . Now, when you run the function, it will increment the global x by 1 and print 1 .

Similar Error: NameError

An error that's similar to the "local variable referenced before assignment" error is the NameError . This is raised when you try to use a variable or a function name that has not been defined yet.

Running this code will result in a NameError :

In this case, we're trying to print the value of y , but y has not been defined anywhere in the code. Hence, Python raises a NameError . This is similar in that we are trying to use an uninitialized/undefined variable, but the main difference is that we didn't try to initialize y anywhere else in our code.

Variable Scope in Python

Understanding the concept of variable scope can help avoid many common errors in Python, including the main error of interest in this Byte. But what exactly is variable scope?

In Python, variables have two types of scope - global and local. A variable declared inside a function is known as a local variable, while a variable declared outside a function is a global variable.

Consider this example:

In this code, x is a global variable, and y is a local variable. x can be accessed anywhere in the code, but y can only be accessed within my_function . Confusion surrounding this is one of the most common causes for the "variable referenced before assignment" error.

In this Byte, we've taken a look at the "local variable referenced before assignment" error and another similar error, NameError . We also delved into the concept of variable scope in Python, which is an important concept to understand to avoid these errors. If you're seeing one of these errors, check the scope of your variables and make sure they're being assigned before they're being used.

might be referenced before assignment pycharm

Monitor with Ping Bot

Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

OpenAI

© 2013- 2024 Stack Abuse. All rights reserved.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

try: VAR = ... except: VAR = ... finally: VAR - Local variable 'VAR' might be referenced before assignment [duplicate]

Why is PyCharm warning me that streamer might be referenced before assignment? In my opinion, all the situations are covered by try or except block so in finally block the streamer is always defined.

enter image description here

Is there a reason behind this warning?

Milano's user avatar

  • 1 This isn't the problem, but you don't need both except clauses here, since the second one includes the first, and both have the same statement in them. And you should not use bare except but rather except Exception to avoid catching exceptions like KeyboardInterrupt . –  kindall Commented Nov 8, 2021 at 1:24

If the assignment in your except section throws an exception as well (and it may):

.. then the finally block still gets executed, but streamer won't be defined. I think the issue is you didn't realise that a finally gets executed even when an exception occurs?

The only times a finally won't run is if the thread or process that has the block is killed beforehand, you exited the program (using exit() ) or something underlying fails (like the OS, VM, container, etc.)

Grismar's user avatar

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

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Which version of Netscape, on which OS, appears in the movie “Cut” (2000)?
  • Writing an i with a line over it instead of an i with a dot and a line over it
  • Felt VR40 - 2020
  • Causal Reconciliation: Is this a viable way for my FTL system to preserve the course of History?
  • Explain how π – 1 + 50 + ⅔ × 1000 is PLONK
  • 1960s Stylesheet/Format for working Physics problems
  • Why does average of Monte Carlo simulations not hold for simple problem?
  • 2 in 1: Twin Puzzle
  • Motion of the COM of 2-body system
  • What are the 270 mitzvot relevant today?
  • Coding exercise to represent an integer as words using python
  • Journal keeps messing with my proof
  • Who is the referent of "him" in Genesis 18:2?
  • Compact symmetric spaces and sub-root systems
  • Where to donate foreign-language academic books?
  • Generate vectors with a certain property
  • My supervisor wants me to switch to another software/programming language that I am not proficient in. What to do?
  • Gomoku game 5 in a row. Javascript simple game Canvas
  • How is it possible to know a proposed perpetual motion machine won't work without even looking at it?
  • Took a pic of old school friend in the 80s who is now quite famous and written a huge selling memoir. Pic has ben used in book without permission
  • Unable to update ubuntu 24.04 after incorrectly installing debian key
  • Why is simpler prose more popular these days?
  • magnetic boots inverted
  • What does "CD military" mean on this sign at this crossing point between East Berlin and West Berlin? (June/July 1989)

might be referenced before assignment pycharm

How to Fix Local Variable Referenced Before Assignment Error in Python

How to Fix Local Variable Referenced Before Assignment Error in Python

Table of Contents

Fixing local variable referenced before assignment error.

In Python , when you try to reference a variable that hasn't yet been given a value (assigned), it will throw an error.

That error will look like this:

In this post, we'll see examples of what causes this and how to fix it.

Let's begin by looking at an example of this error:

If you run this code, you'll get

The issue is that in this line:

We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.

If we want to refer the variable that was defined in the first line, we can make use of the global keyword.

The global keyword is used to refer to a variable that is defined outside of a function.

Let's look at how using global can fix our issue here:

Global variables have global scope, so you can referenced them anywhere in your code, thus avoiding the error.

If you run this code, you'll get this output:

In this post, we learned at how to avoid the local variable referenced before assignment error in Python.

The error stems from trying to refer to a variable without an assigned value, so either make use of a global variable using the global keyword, or assign the variable a value before using it.

Thanks for reading!

might be referenced before assignment pycharm

  • Privacy Policy
  • Terms of Service

How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python

might be referenced before assignment pycharm

You could also see this error when you forget to pass the variable as an argument to your function.

How to reproduce this error

How to fix this error.

I hope this tutorial is useful. See you in other tutorials.

Take your skills to the next level ⚡️

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

How to Fix – UnboundLocalError: Local variable Referenced Before Assignment in Python

Developers often encounter the  UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches.

What is UnboundLocalError: Local variable Referenced Before Assignment?

This error occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Below, are the reasons by which UnboundLocalError: Local variable Referenced Before Assignment error occurs in  Python :

Nested Function Variable Access

Global variable modification.

In this code, the outer_function defines a variable ‘x’ and a nested inner_function attempts to access it, but encounters an UnboundLocalError due to a local ‘x’ being defined later in the inner_function.

In this code, the function example_function tries to increment the global variable ‘x’, but encounters an UnboundLocalError since it’s treated as a local variable due to the assignment operation within the function.

Solution for Local variable Referenced Before Assignment in Python

Below, are the approaches to solve “Local variable Referenced Before Assignment”.

In this code, example_function successfully modifies the global variable ‘x’ by declaring it as global within the function, incrementing its value by 1, and then printing the updated value.

In this code, the outer_function defines a local variable ‘x’, and the inner_function accesses and modifies it as a nonlocal variable, allowing changes to the outer function’s scope from within the inner function.

Please Login to comment...

Similar reads.

  • Python Programs
  • Python Errors
  • Python How-to-fix
  • California Lawmakers Pass Bill to Limit AI Replicas
  • Best 10 IPTV Service Providers in Germany
  • Python 3.13 Releases | Enhanced REPL for Developers
  • IPTV Anbieter in Deutschland - Top IPTV Anbieter Abonnements
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Local variable referenced before assignment in Python

avatar

Last updated: Apr 8, 2024 Reading time · 4 min

banner

# Local variable referenced before assignment in Python

The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function.

To solve the error, mark the variable as global in the function definition, e.g. global my_var .

unboundlocalerror local variable name referenced before assignment

Here is an example of how the error occurs.

We assign a value to the name variable in the function.

# Mark the variable as global to solve the error

To solve the error, mark the variable as global in your function definition.

mark variable as global

If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global .

# Local variables shadow global ones with the same name

You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the global one.

accessing global variables in functions

Accessing the name variable in the function is perfectly fine.

On the other hand, variables declared in a function cannot be accessed from the global scope.

variables declared in function cannot be accessed in global scope

The name variable is declared in the function, so trying to access it from outside causes an error.

Make sure you don't try to access the variable before using the global keyword, otherwise, you'd get the SyntaxError: name 'X' is used prior to global declaration error.

# Returning a value from the function instead

An alternative solution to using the global keyword is to return a value from the function and use the value to reassign the global variable.

return value from the function

We simply return the value that we eventually use to assign to the name global variable.

# Passing the global variable as an argument to the function

You should also consider passing the global variable as an argument to the function.

pass global variable as argument to function

We passed the name global variable as an argument to the function.

If we assign a value to a variable in a function, the variable is assumed to be local unless explicitly declared as global .

# Assigning a value to a local variable from an outer scope

If you have a nested function and are trying to assign a value to the local variables from the outer function, use the nonlocal keyword.

assign value to local variable from outer scope

The nonlocal keyword allows us to work with the local variables of enclosing functions.

Had we not used the nonlocal statement, the call to the print() function would have returned an empty string.

not using nonlocal prints empty string

Printing the message variable on the last line of the function shows an empty string because the inner() function has its own scope.

Changing the value of the variable in the inner scope is not possible unless we use the nonlocal keyword.

Instead, the message variable in the inner function simply shadows the variable with the same name from the outer scope.

# Discussion

As shown in this section of the documentation, when you assign a value to a variable inside a function, the variable:

  • Becomes local to the scope.
  • Shadows any variables from the outer scope that have the same name.

The last line in the example function assigns a value to the name variable, marking it as a local variable and shadowing the name variable from the outer scope.

At the time the print(name) line runs, the name variable is not yet initialized, which causes the error.

The most intuitive way to solve the error is to use the global keyword.

The global keyword is used to indicate to Python that we are actually modifying the value of the name variable from the outer scope.

  • If a variable is only referenced inside a function, it is implicitly global.
  • If a variable is assigned a value inside a function's body, it is assumed to be local, unless explicitly marked as global .

If you want to read more about why this error occurs, check out [this section] ( this section ) of the docs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • SyntaxError: name 'X' is used prior to global declaration

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

might be referenced before assignment pycharm

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

Python local variable referenced before assignment Solution

When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. This error is raised when you try to use a variable before it has been assigned in the local context .

In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you understand how you can solve it.

Find your bootcamp match

What is unboundlocalerror: local variable referenced before assignment.

Trying to assign a value to a variable that does not have local scope can result in this error:

Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function , that variable is local. This is because it is assumed that when you define a variable inside a function you only need to access it inside that function.

There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program; local variables are only accessible within the function in which they are originally defined.

Let’s take a look at how to solve this error.

An Example Scenario

We’re going to write a program that calculates the grade a student has earned in class.

We start by declaring two variables:

These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Next, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement :

Finally, we call our function:

This line of code prints out the value returned by the calculate_grade() function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.

Let’s run our code and see what happens:

An error has been raised.

The Solution

Our code returns an error because we reference “letter” before we assign it.

We have set the value of “numerical” to 42. Our if statement does not set a value for any grade over 50. This means that when we call our calculate_grade() function, our return statement does not know the value to which we are referring.

We do define “letter” at the start of our program. However, we define it in the global context. Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.

We solve this problem in two ways. First, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:

Let’s try to run our code again:

Our code successfully prints out the student’s grade.

If you are using an “if” statement where you declare a variable, you should make sure there is an “else” statement in place. This will make sure that even if none of your if statements evaluate to True, you can still set a value for the variable with which you are going to work.

Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function. However, this approach is likely to lead to more confusing code and other issues. In general, variables should not be declared using “global” unless absolutely necessary . Your first, and main, port of call should always be to make sure that a variable is correctly defined.

In the example above, for instance, we did not check that the variable “letter” was defined in all use cases.

That’s it! We have fixed the local variable error in our code.

The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.

Now you’re ready to solve UnboundLocalError Python errors like a professional developer !

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

What's Next?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Apply to top tech training programs in one click

Consultancy

  • Technology Consulting
  • Customer Experience Consulting
  • Solution Architect Consulting

Software Development Services

  • Ecommerce Development
  • Web App Development
  • Mobile App Development
  • SAAS Product Development
  • Content Management System
  • System Integration & Data Migration
  • Cloud Computing
  • Computer Vision

Dedicated Development Team

  • Full Stack Developers For Hire
  • Offshore Development Center

Marketing & Creative Design

  • UX/UI Design
  • Customer Experience Optimization
  • Digital Marketing
  • Devops Services
  • Service Level Management
  • Security Services
  • Odoo gold partner

By Industry

  • Retail & Ecommerce
  • Manufacturing
  • Import & Distribution
  • Financical & Banking
  • Technology For Startups

Business Model

  • MARKETPLACE ECOMMERCE

Our realized projects

might be referenced before assignment pycharm

MB Securities - A Premier Brokerage

might be referenced before assignment pycharm

iONAH - A Pioneer in Consumer Electronics Industry

might be referenced before assignment pycharm

Emers Group - An Official Nike Distributing Agent

might be referenced before assignment pycharm

Academy Xi - An Australian-based EdTech Startup

  • Market insight

might be referenced before assignment pycharm

  • Ohio Digital
  • Onnet Consoulting

></center></p><h2>Local variable referenced before assignment: The UnboundLocalError in Python</h2><p>When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. Because you try to use a local variable referenced before assignment. So, in this guide, we talk about what this error means and why it is raised. We walk through an example in action to help you understand how you can solve it.</p><p>Source: careerkarma</p><p><center><img style=

What is UnboundLocalError: local variable referenced before assignment?

Trying to assign a value to a variable that does not have local scope can result in this error:

Python has a simple rule to determine the scope of a variable. To clarify, a variable is assigned in a function, that variable is local. Because it is assumed that when you define a variable inside a function, you only need to access it inside that function.

There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program. Whereas, local variables are only accessible within the function in which they are originally defined.

An example of Local variable referenced before assignment

We’re going to write a program that calculates the grade a student has earned in class.

Firstly, we start by declaring two variables:

These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Then, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement:

Finally, we call our function:

This line of code prints out the value returned by the  calculate_grade()  function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.

Let’s run our code of Local variable referenced before assignment and see what happens:

Here is an error!

The Solution of Local variable referenced before assignment

The code returns an error: Unboundlocalerror local variable referenced before assignment because we reference “letter” before we assign it.

We have set the value of “numerical” to 42. Our  if  statement does not set a value for any grade over 50. This means that when we call our  calculate_grade()  function, our return statement does not know the value to which we are referring.

Moreover, we do define “letter” at the start of our program. However, we define it in the global context. Because Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.

Therefore, this problem of variable referenced before assignment could be solved in two ways. Firstly, we can add an  else  statement to our code. This ensures we declare “letter” before we try to return it:

Let’s try to run our code again:

Our code successfully prints out the student’s grade. This approach is good because it lets us keep “letter” in the local context. To clarify, we could even remove the “letter = “F”” statement from the top of our code because we do not use it in the global context.

Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our  calculate_grade()  function:

We use the “global” keyword at the start of our function.

This keyword changes the scope of our variable to a global variable. This means the “return” statement will no longer treat “letter” like a local variable. Let’s run our code. Our code returns: F.

The code works successfully! Let’s try it using a different grade number by setting the value of “numerical” to a new number:

Our code returns: B.

Finally, we have fixed the local variable referenced before assignment error in the code.

To sum up, as you can see, the UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. Then, you can solve this error by ensuring that a local variable is declared before you assign it a value. Moreover, if a variable is declared globally that you want to access in a function, you can use the “global” keyword to change its value. In case you have any inquiry, let’s CONTACT US . With a lot of experience in Mobile app development services , we will surely solve it for you instantly.

>>> Read more

  • Average python length: How to find it with examples
  • List assignment index out of range: Python indexerror solution you should know
  • Spyder vs Pycharm: The detailed comparison to get best option for Python programming
  • fix python error , Local variable referenced before assignment , python , python dictionary , python error , python learning , UnboundLocalError , UnboundLocalError in Python

Our Other Services

  • E-commerce Development
  • Web Apps Development
  • Web CMS Development
  • Mobile Apps Development
  • Software Consultant & Development
  • System Integration & Data Migration
  • Dedicated Developers & Testers For Hire
  • Remote Working Team
  • Saas Products Development
  • Web/Mobile App Development
  • Outsourcing
  • Hiring Developers
  • Digital Transformation
  • Advanced SEO Tips

Offshore Development center

Lastest News

aws-cloud-managed-services

Challenges and Advices When Using AWS Cloud Managed Services

aws-well-architected-framework

Comprehensive Guide about AWS Well Architected Framework

aws-cloud-migration

AWS Cloud Migration: Guide-to-Guide from A to Z

cloud computing for healthcare

Uncover The Treasures Of Cloud Computing For Healthcare 

cloud computing in financial services

A Synopsis of Cloud Computing in Financial Services 

applications of cloud computing

Discover Cutting-Edge Cloud Computing Applications To Optimize Business Resources

Tailor your experience

  • Success Stories

Copyright ©2007 – 2021 by AHT TECH JSC. All Rights Reserved.

might be referenced before assignment pycharm

Thank you for your message. It has been sent.

Get the Reddit app

Subreddit for JetBrains PyCharm, the Python IDE for professional developers by JetBrains. Find out more about PyCharm at https://www.jetbrains.com/pycharm/

local variable 'test1' referenced before assignment.

What do I do in an instance where error "local variable referenced before assignment." comes up, but it is not referenced before assignment? Here is my example:

"data:[ [ "FS" , 0], [ "FL" , 4], [ "FR, 5 ], [ "FA" , 7]

value = plt.table(cellText=data)

UnboundLocalError: local variable 'data' referenced before assignment"

it says that data is the local variable, but it isn't referenced before assignment?

BTW, for reference in case the code doesn't make any sense, I replaced the important parts of the code with no substitute variables. The important part is I don't get why it is saying to is referenced before assignment when it is not. If you need to see the whole real code, I. understand, but if possible I would like to keep it private. Any help wpuld be appreciated. Thanks!

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

[SOLVED] Local Variable Referenced Before Assignment

local variable referenced before assignment

Python treats variables referenced only inside a function as global variables. Any variable assigned to a function’s body is assumed to be a local variable unless explicitly declared as global.

Why Does This Error Occur?

Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Hence it searches for the variable whenever used. When not found, it throws the error.

Before we hop into the solutions, let’s have a look at what is the global and local variables.

Local Variable Declarations vs. Global Variable Declarations

Local VariablesGlobal Variables
A variable is declared primarily within a Python function.Global variables are in the global scope, outside a function.
A local variable is created when the function is called and destroyed when the execution is finished.A Variable is created upon execution and exists in memory till the program stops.
Local Variables can only be accessed within their own function.All functions of the program can access global variables.
Local variables are immune to changes in the global scope. Thereby being more secure.Global Variables are less safer from manipulation as they are accessible in the global scope.

[Fixed] typeerror can’t compare datetime.datetime to datetime.date

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

Local Variable Referenced Before Assignment Error

Explanation

The variable myVar has been assigned a value twice. Once before the declaration of myFunction and within myFunction itself.

Using Global Variables

Passing the variable as global allows the function to recognize the variable outside the function.

Create Functions that Take in Parameters

Instead of initializing myVar as a global or local variable, it can be passed to the function as a parameter. This removes the need to create a variable in memory.

UnboundLocalError: local variable ‘DISTRO_NAME’

This error may occur when trying to launch the Anaconda Navigator in Linux Systems.

Upon launching Anaconda Navigator, the opening screen freezes and doesn’t proceed to load.

Try and update your Anaconda Navigator with the following command.

If solution one doesn’t work, you have to edit a file located at

After finding and opening the Python file, make the following changes:

In the function on line 159, simply add the line:

DISTRO_NAME = None

Save the file and re-launch Anaconda Navigator.

DJANGO – Local Variable Referenced Before Assignment [Form]

The program takes information from a form filled out by a user. Accordingly, an email is sent using the information.

Upon running you get the following error:

We have created a class myForm that creates instances of Django forms. It extracts the user’s name, email, and message to be sent.

A function GetContact is created to use the information from the Django form and produce an email. It takes one request parameter. Prior to sending the email, the function verifies the validity of the form. Upon True , .get() function is passed to fetch the name, email, and message. Finally, the email sent via the send_mail function

Why does the error occur?

We are initializing form under the if request.method == “POST” condition statement. Using the GET request, our variable form doesn’t get defined.

Local variable Referenced before assignment but it is global

This is a common error that happens when we don’t provide a value to a variable and reference it. This can happen with local variables. Global variables can’t be assigned.

This error message is raised when a variable is referenced before it has been assigned a value within the local scope of a function, even though it is a global variable.

Here’s an example to help illustrate the problem:

In this example, x is a global variable that is defined outside of the function my_func(). However, when we try to print the value of x inside the function, we get a UnboundLocalError with the message “local variable ‘x’ referenced before assignment”.

This is because the += operator implicitly creates a local variable within the function’s scope, which shadows the global variable of the same name. Since we’re trying to access the value of x before it’s been assigned a value within the local scope, the interpreter raises an error.

To fix this, you can use the global keyword to explicitly refer to the global variable within the function’s scope:

However, in the above example, the global keyword tells Python that we want to modify the value of the global variable x, rather than creating a new local variable. This allows us to access and modify the global variable within the function’s scope, without causing any errors.

Local variable ‘version’ referenced before assignment ubuntu-drivers

This error occurs with Ubuntu version drivers. To solve this error, you can re-specify the version information and give a split as 2 –

Here, p_name means package name.

With the help of the threading module, you can avoid using global variables in multi-threading. Make sure you lock and release your threads correctly to avoid the race condition.

When a variable that is created locally is called before assigning, it results in Unbound Local Error in Python. The interpreter can’t track the variable.

Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable declaration have been explained, and multiple solutions regarding the issue have been provided.

Trending Python Articles

[Fixed] nameerror: name Unicode is not defined

COMMENTS

  1. Search for usages

    When you write or edit code, you might come across a code element that you want to change or delete. Before you make the changes, it is a good practice to see where the code element is used and how it affects the application. With the Find Usages actions you can search for the references of your code element throughout the whole codebase.

  2. The PySimpleGUI Cookbook

    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. If you were to use a funciton, then your code my look like this: def mprint(*args, **kwargs): window['-ML1-' + sg.WRITE_ONLY_KEY].print(*args, **kwargs) print = mprint

  3. PyCharm warns local variable might be referenced

    UnboundLocalError: local variable 'boolean' referenced before assignment. After all, nothing else in the code type-checked the value; and pi isn't equal to 3, nor to 2, nor is it less than 2. There are several reasonable approaches to the problem, in context. We can simply assign boolean = True before the loop: boolean = True.

  4. PyCharm: Variable in finally block might be referenced before assignment?

    PyCharm warns me that variable category can be referenced before assignment but I don't think so. Except should catch every Exception (except fatal errors) and finally is called after try or except block. try: category = lst[2] except: category = None. finally: if not category: #here. category = self.default_category.

  5. Why does PyCharm think that this variable may be referenced before

    However, when I add a continue statement at the bottom of the except block PyCharm does not like it and says that the response variable may be referenced before assignment, even though I believe both code blocks do the exact same thing and the continue statement is unnecessary since the the execution will move to the top of the while loop ...

  6. python

    It might be worth nothing that you only need the "global" keyword if you assign to the global variable within a local scope. ... #cl = [1, 2] # access this way will throw `reference before assignment` cl[0] = 1 cl[1] = 2 # these won't inner() Share. Improve this answer. Follow edited Jun 9, 2020 at 2:57. mic. 1,256 1 1 gold badge 18 18 silver ...

  7. python

    PyCharm marks the c in the return c with. Local variable 'c' might be referenced before assignment. This is a good warning, usually, and I don't want to disable it. (#noqa is not an answer) In this case, however, it can be deduced before running that c always has a value.

  8. Why is PyCharm telling me that one of my variables could be referenced

    This likely isn't an error, but just a warning from the PyCharm IDE. Whenever this occurs, it is because there is a possibility that a variable is not defined later in the code. In your case, the variable that may not be defined if a certain set of conditions are True is the slope variable.

  9. Warning

    Local variable cache_data might be used before assignment. Could you please explain how this could possibly happen in this case or is this an inspection bug? python; pycharm; python-3.8; Share. Improve this question. Follow ... pycharm can't reference global variable inside a function. 0

  10. Fix "local variable referenced before assignment" in Python

    Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

  11. try: VAR = ... except: VAR = ... finally: VAR

    If the assignment in your except section throws an exception as well (and it may):. except: streamer = Streamer.objects.create(**streamer_attrs) .. then the finally block still gets executed, but streamer won't be defined. I think the issue is you didn't realise that a finally gets executed even when an exception occurs?. The only times a finally won't run is if the thread or process that has ...

  12. How to Fix Local Variable Referenced Before Assignment Error in Python

    value = value + 1 print (value) increment() If you run this code, you'll get. BASH. UnboundLocalError: local variable 'value' referenced before assignment. The issue is that in this line: PYTHON. value = value + 1. We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the ...

  13. for..else local variable might be referenced before assignment

    for..else local variable might be referenced before assignment Answered. Pablo García Chacón Created November 30, 2017 11:14. Look at this piece of code: for i in range (10): pass else: i # Local variable 'i' might be reference before assignment. Why does PyCharm detect a warning? I can't really think of a scenario where that warning is true. ...

  14. How to fix UnboundLocalError: local variable 'x' referenced before

    The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable. To resolve this error, you need to use a different variable name when referencing the existing variable, or you can also specify a parameter for the function. I hope this tutorial is useful.

  15. How to Fix

    Output. Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced Before Assignment in Python

  16. "Local variable 'x' might be referenced before assignment" offered by

    "Local variable 'x' might be referenced before assignment" offered by any linter? I can't seem to find out if this is offered by anything besides PyCharm, and I keep running into issues where this would be useful to know. Usually it crops up in branches that rarely occur, and I'm sure there's more ideal testing methods, this would just be quick ...

  17. Local variable referenced before assignment in Python

    If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global. # Local variables shadow global ones with the same name You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the global one.

  18. Python local variable referenced before assignment Solution

    Trying to assign a value to a variable that does not have local scope can result in this error: UnboundLocalError: local variable referenced before assignment. Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function, that variable is local. This is because it is assumed that when you define a ...

  19. Local variable referenced before assignment: The UnboundLocalError

    What is UnboundLocalError: local variable referenced before assignment? Trying to assign a value to a variable that does not have local scope can result in this error: 1 UnboundLocalError: local variable referenced before assignment. Python has a simple rule to determine the scope of a variable.

  20. local variable 'test1' referenced before assignment. : r/pycharm

    value = plt.table (cellText=data) UnboundLocalError: local variable 'data' referenced before assignment". it says that data is the local variable, but it isn't referenced before assignment? BTW, for reference in case the code doesn't make any sense, I replaced the important parts of the code with no substitute variables.

  21. [SOLVED] Local Variable Referenced Before Assignment

    May 4, 2023 April 13, 2022. ... Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable declaration have been explained, and multiple solutions regarding the issue have been provided.