Pysimplegui Tutorial
Pysimplegui Tutorial
Pysimplegui Tutorial
PySimpleGUI also has a port for Remi which is useful for building GUIs for
the web. PySimpleGui lets you build GUIs quicker than by directly using the
libraries it uses.
Audience
This tutorial is designed for Python developers who want to learn how to
build cross-platform desktop as well as web based GUI designs using
PySimpleGui library.
Prerequisites
Before you proceed, make sure that you understand the basics of procedural
and object-oriented programming in Python. For understanding the
advanced topics such as integration of PySimpleGui with Matplotlib and
OpenCV packages, their understanding is essential.
All the content and graphics published in this e-book are the property of
Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse,
retain, copy, distribute or republish any contents or a part of contents of
this e-book in any manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and
as precisely as possible, however, the contents may contain inaccuracies or
errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the
accuracy, timeliness or completeness of our website or its contents
including this tutorial. If you discover any errors on our website or in this
tutorial, please notify us at [email protected]
i
PySimpleGUI – Python GUIs for Humans
Table of Contents
About the Tutorial ........................................................................................................ i
Audience ...................................................................................................................... i
Prerequisites ................................................................................................................ i
PySimpleGUIQt ........................................................................................................... 7
PySimpleGUIWx ........................................................................................................ 10
PySimpleGUIWeb ...................................................................................................... 12
Progress Meter.......................................................................................................... 20
Debug Popup............................................................................................................. 21
ii
PySimpleGUI – Python GUIs for Humans
Layout Structure........................................................................................................ 23
Button Events............................................................................................................ 41
Multiline Element...................................................................................................... 48
FileBrowse ................................................................................................................ 52
iii
PySimpleGUI – Python GUIs for Humans
FilesBrowse ............................................................................................................... 53
FolderBrowse ............................................................................................................ 55
FileSaveAs ................................................................................................................. 56
ColorChooserButton .................................................................................................. 58
CalendarButton ......................................................................................................... 60
iv
PySimpleGUI – Python GUIs for Humans
ButtonMenu............................................................................................................ 103
v
1. PySimpleGUI – Introduction
PySimpleGUI – Python GUIs for Humans
All the packages in the PySimpleGui group follow the similar API, which
means the names of GUI elements, their properties and methods are same
in all the four packages. As a result, just by replacing the import statement
(and keeping the rest of the code unchanged), one can get the
corresponding GUI design rendered. This is in fact the most important
feature of PySimpleGui. That’s why, it is known as Python GUIs for
Humans.
1
PySimpleGUI – Python GUIs for Humans
2
2. PySimpleGUI –PySimpleGUI
Environment Setup
– Python GUIs for Humans
The pysimplegui.py file has the "main()" function. When called from
Python prompt, it generates the following window to affirm that the package
is correctly installed.
3
PySimpleGUI – Python GUIs for Humans
If you are using Python3 version earlier than 3.4, you may need to install the
"typing" module since it is not shipped in the corresponding standard library
while True:
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
break
window.close()
Python hello.py
5
PySimpleGUI – Python GUIs for Humans
window=Tk()
window.title('HelloWorld Tk')
window['bg']='#64778D'
window.geometry("715x250+10+10")
window.mainloop()
All other functionalities remain same, except we use the serve() function
off waitress module to start the WSGI server. On visiting the '/' route in
6
PySimpleGUI – Python GUIs for Humans
the browser after running the program, the Hello World message is
displayed as before.
class MyView(object):
def __init__(self, request):
self.request = request
def __call__(self):
return Response('hello world')
PySimpleGUIQt
The object model of PySimpleGUI API has been made compatible with the
widgets as defined in PySide2 package (which is the Python port for Qt
graphics toolkit). The Qt version of PySimpleGui is called PySimpleGUIQt.
It can be similarly installed with following PIP command:
Since this package depends on PySide2, the same will also be installed.
7
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
break
window.close()
8
PySimpleGUI – Python GUIs for Humans
import sys
def window():
app = QApplication(sys.argv)
w = QWidget()
w.setStyleSheet("background-color: #64778D;")
b = QLabel(w)
b.setText("Hello World!")
b.setFont(QFont('Arial Bold', 20))
b.setAlignment(Qt.AlignCenter)
b.setStyleSheet("color: white;")
b.setGeometry(100, 100, 715, 250)
b.move(50, 20)
w.setWindowTitle("HelloWorldQt")
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
9
PySimpleGUI – Python GUIs for Humans
PySimpleGUIWx
This module encapsulates the functionality of GUI widgets as defined in
WxPython toolkit. WxPython is a Python port for the widely used WxWidgets
library originally written in C++. Obviously, PySimpleGUIWx depends on
WxPython package, and hence the latter will get automatically installed by
the following PIP command:
while True:
10
PySimpleGUI – Python GUIs for Humans
window.close()
Note that you’ll need a little more complex code to obtain the similar output
with pure WxPython code as follows:
import wx
app = wx.App()
window = wx.Frame(None, title="WxPython", size=(715, 250))
panel = wx.Panel(window)
panel.SetBackgroundColour((100, 119, 141))
font = wx.Font()
11
PySimpleGUI – Python GUIs for Humans
font.SetFaceName("Arial Bold")
font.SetPointSize(30)
label.SetFont(font)
window.Show(True)
app.MainLoop()
It will display a top level window with a text label having Hello World as the
caption.
PySimpleGUIWeb
Remi (REMote Interface) is a GUI library for Python applications that are
rendered in a web browser. PySimpleGUIWeb package ports the original
PySimpleGui library to Remi so that its apps can be run in a browser.
Following PIP command installs both PySimpleGUIWeb and Remi in the
current Python environment:
12
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
break
window.close()
class HelloWeb(App):
def __init__(self, *args):
super(HelloWeb, self).__init__(*args)
def main(self):
wid = gui.VBox(style={"background-color": "#64778D"})
"font-size": "20px"}
)
wid.append(self.lbl)
return wid
13
PySimpleGUI – Python GUIs for Humans
if __name__ == "__main__":
start(HelloWeb, debug=True, address='0.0.0.0', port=0)
When we run these programs, the Remi server starts, a browser window
automatically opens and the Hello World message is displayed.
Here we have seen the Hello World program written in the PySimpleGUI,
PySimpleGUIQt, PySimpleGUIWx and PySimpleGUIWeb libraries. We can
see that the widget library remains the same. Moreover, the same Hello
world program, when written in pure Tkinter, PySide, WxPython and Remi
respectively, becomes far more complex and tedious than the PySimpleGUI
versions.
14
4. PySimpleGUIPySimpleGUI
– Popup Windows
– Python GUIs for Humans
A most basic popup is created by the popup() function. It can be used like
a print() function to display more than one parameters on the window, and
an OK button. It acts like a message box, that disappears immediately on
pressing the OK button
It displays a popup window with Hello World text and OK button. Note that
more than one strings can be displayed. Following popups with different
button configurations are available:
These functions return the text of the button pressed by the user. For
example, if the user presses OK button of the ok-cancel popup, it returns
Ok which can be used in further programming logic.
Following popups accept input from the user in the form of text or let the
user select file/folder/date from the selectors.
15
PySimpleGUI – Python GUIs for Humans
When user has made the selection and Ok button is pressed, the return
value of the popup is the text, which can be used further in the program.
file=psg.popup_get_file('Select a file',
title="File selector")
print ("File selected", file)
folder=psg.popup_get_folder('Get folder',
title="Folder selector")
print ("Folder selected",folder)
ch = psg.popup_ok_cancel("Press Ok to proceed",
"Press cancel to stop",
title="OkCancel")
if ch=="OK":
print ("You pressed OK")
16
PySimpleGUI – Python GUIs for Humans
if ch=="Cancel":
print ("You pressed Cancel")
psg.popup_no_buttons('You pressed', ch, non_blocking=True)
Output: The popups generated by the above code are shown below:
All types of popups are objects of respective classes inherited from popup
class. All of them have a common set of properties. These properties have
a certain default value, and can be used to customize the appearance and
17
PySimpleGUI – Python GUIs for Humans
18
PySimpleGUI – Python GUIs for Humans
Scrolled Popup
The popup_scrolled() function generates a popup with a scrollable text
box in it. Use this to display a large amount of text, consisting of many lines
with number of characters more than the width.
The size property is a tuple (w, h) with "w" being the number of characters
in one line, and "h" being the lines displayed at a time. The
horizontal/vertical scrollbar to the text box will become active if the number
of characters/no of lines of text are more than "w" or "h".
file=open("zen.txt")
text=file.read()
19
PySimpleGUI – Python GUIs for Humans
Progress Meter
The "one_line_progress_meter" is a popup that displays the visual
representation of an ongoing long process, such as a loop. It shows the
instantaneous value of a certain parameter, estimated time to complete the
process, and the elapsed time.
size = os.path.getsize('zen.txt')
file=open("zen.txt")
i=0
while True:
text=file.read(1)
i=i+1
if text=="":
file.close()
break
print (text,end='')
psg.one_line_progress_meter(
'Progress Meter', i, size,
'Character Counter'
)
20
PySimpleGUI – Python GUIs for Humans
Debug Popup
During the execution of a program, it is usually required to keep track of
intermediate values of certain variables, although not required in the
following output. This can be achieved by the Print() function in
PySimpleGUI library.
Note: Unlike Python’s built-in print() function, this function has "P" in
uppercase).
As the program encounters this function for the first time, the debug window
appears and all the subsequent Prints are echoed in it. Moreover, we can
use EasyPrint or eprint that also have same effect.
The following program computes the factorial value of the number input by
the user. Inside the for loop, we want to keep track of the values of f (for
factorial) on each iteration. That is done by the Print function and displayed
in the debug window.
21
PySimpleGUI – Python GUIs for Humans
f=1
num=int(psg.popup_get_text("enter a number: "))
Assuming that the user inputs 5, the debug window shows the following
output:
22
5. PySimpleGUI – Window Class
PySimpleGUI – Python GUIs for Humans
A persistent window on the other hand continues to be visible till the event
causing it to be closed occurs. The asynchronous window is the one whose
contents are periodically updated.
Layout Structure
The placement of elements or widgets in the window’s client area is
controlled by list of list objects. Each list element corresponds to one row
on the window surface, and may contain one or more GUI elements
available in PySimpleGUI library.
The elements on the window are placed in four rows. First three rows have
a Text element (displays a static text) and an InputText element (in which
user can enter). Last row has two buttons, Ok and Cancel.
layout = [
[psg.Text('Name '),psg.Input()],
[psg.Text('Address '), psg.Input()],
[psg.Text('Email ID '), psg.Input()],
[psg.OK(), psg.Cancel()]
]
This list object is used as the value of layout parameter for the constructor
of the Window class.
This will display the desired window. The user inputs are stored in a
dictionary named as values. The read() method of Window class is called
as the user presses the Ok button, and the window closes immediately.
layout = [
[psg.Text('Name ', size=(15,1)),psg.Input(expand_x=True)],
[psg.Text('Address ', size=(15,1)), psg.Input(expand_x=True)],
[psg.Text('Email ID ', size=(15,1)), psg.Input(expand_x=True)],
[psg.OK(), psg.Cancel()]
]
window.close()
24
PySimpleGUI – Python GUIs for Humans
Enter the data as shown and press the "OK" button. The values will be
printed as below:
If, after filling the data, you press the "Cancel" button, the result printed
will be:
Persistent Window
Note that this window gets closed as soon as any button (or the "X" button
in the title bar) is clicked. To keep the window alive till a special type of
button called Exit is pressed or if the window is closed by pressing "X", the
read() method is placed in an infinite loop with provision to break when
WIN_CLOSED event occurs (when Exit button is pressed) or Exit event
occurs (when "X" button is pressed).
Let us change the Cancel button in the above code with Exit button.
layout = [
[psg.Text('Name '), psg.Input()],
[psg.Text('Address '), psg.Input()],
[psg.Text('Email ID '), psg.Input()],
[psg.OK(), psg.Exit()]
]
25
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
if event == psg.WIN_CLOSED or event == 'Exit':
break
print (event, values)
window.close()
The appearance of the window will be similar as before, except that instead
of Cancel, it has Exit button.
The entered data will be printed in the form of a tuple. First element is the
event, i.e., the caption of button, and second is a dictionary whose key is
incrementing number and value is the text entered.
Window Methods
The important method defined in the Window class is the read() method,
to collect the values entered in all input elements. The Window class has
other methods to customize the appearance and behaviour. They are listed
below:
26
PySimpleGUI – Python GUIs for Humans
27
PySimpleGUI – Python GUIs for Humans
Let us assign keys to the Input elements in the above example as shown
below:
layout = [
[psg.Text('Name '),psg.Input(key='-NM-')],
[psg.Text('Address '), psg.Input(key='-AD-')],
[psg.Text('Email ID '), psg.Input(key='-ID-')],
[psg.OK(), psg.Exit()],
]
As a result, the values dictionary returned after the read() method will
contain the key identifiers instead of integers previously.
Now, values[-NM-'] will fetch 'Kiran'. The key can be assigned to any
element and not just the input element. You can use the same key to call
Update on an element. We can use "find_element(key)" of the Window
object, or use window['key'] to refer to the element.
28
PySimpleGUI – Python GUIs for Humans
Let us extend our previous example to add a row before the Ok and Cancel
buttons and have an empty Text element with "-OUT-" key. On the OK
event, this Text label shows the concatenation of data entered in three input
elements having keys "-NM-", "-AD-" and "-ID-".
layout = [
[psg.Text('Name ', size=(15, 1)),
psg.Input(key='-NM-', expand_x=True)],
[psg.OK(), psg.Exit()],
]
while True:
event, values = window.read()
print(event, values)
out = values['-NM-'] + ' ' + values['-AD-'] + ' ' + values['-ID-']
window['-OUT-'].update(out)
29
PySimpleGUI – Python GUIs for Humans
window.close()
Run the above code, enter text in three input elements and press OK. The
-OUT- text label will be updated as shown here:
layout = [
[psg.Text('Enter a num: '), psg.Input(key='-FIRST-')],
[psg.Text('Enter a num: '), psg.Input(key='-SECOND-')],
[psg.Text('Result : '), psg.Text(key='-OUT-')],
[psg.Button("Add"), psg.Button("Sub"), psg.Exit()],
]
while True:
event, values = window.read()
print(event, values)
30
PySimpleGUI – Python GUIs for Humans
if event == "Add":
result = int(values['-FIRST-']) + int(values['-SECOND-'])
if event == "Sub":
result = int(values['-FIRST-']) - int(values['-SECOND-'])
window['-OUT-'].update(result)
window.close()
The following screenshot shows the result when the "Add" button is pressed.
Borderless Window
By default, the application window is created with a title bar above the client
area wherein all other elements are placed in the layout. The titlebar
consists of a window title on the left, and the control buttons (minimize,
restore/maxmimize and close) on the right. However, particularly for a
kiosk-like application, there is no need of a title bar. You can get rid of the
title bar by setting the "no_titlebar" property of the Window object to
"True".
31
PySimpleGUI – Python GUIs for Humans
Transparent Window
The "alpha_channel" property of the Window object decides the
transparency of the window. Its value is between 0 to 1. By default, it is 0,
which means that the window appears as opaque. Set it to 1 to make it
completely transparent. Any float value between 0 to 1 makes the
transparency proportional.
Multiple Windows
PySimpleGUI allows more than one windows to be displayed
simultaneously. The static function in PySimpleGUI module reads all the
active windows when called. To make the window active, it must be
finalized. The function returns a tuple of (window, event, values) structure.
32
PySimpleGUI – Python GUIs for Humans
In the following code, two functions "win1()" and "win2()" create a window
each when called. Starting with the first window, the button captioned
Window-2 opens another window, so that both are active. When CLOSED
event on first window takes place, both are closed and the program ends.
If the "X" button on second window is pressed, it is marked as closed,
leaving the first open.
def win1():
layout = [
[psg.Text('This is the FIRST WINDOW'), psg.Text('
', key='-OUTPUT-')],
[psg.Text('popup one')],
[psg.Button('Window-2'), psg.Button('Popup'),
psg.Button('Exit')]
]
return psg.Window('Window Title', layout, finalize=True)
def win2():
layout = [
[psg.Text('The second window')],
[psg.Input(key='-IN-', enable_events=True)],
[psg.Text(size=(25, 1), key='-OUTPUT-')],
[psg.Button('Erase'), psg.popup('Popup two'),
psg.Button('Exit')]]
return psg.Window('Second Window', layout, finalize=True)
window1 = win1()
window2 = None
while True:
33
PySimpleGUI – Python GUIs for Humans
if window == window2:
window2 = None
window.close()
34
PySimpleGUI – Python GUIs for Humans
Asynchronous Window
The read() method of the Window class has the following additional
parameters:
The longer you're able to add to the timeout value, the less CPU time you'll
be taking. During the timeout time, you are "yielding" the processor to do
other tasks. your GUI will be more responsive than if you used a non-
blocking read.
The timeout_key parameter helps in deciding whether there has been any
user action within the stipulated time. The default value of "timeout_key"
is "__timeout__".
while True:
event, value = window.read(timeout=10)
if event == sg.WIN_CLOSED:
break
if event == sg.TIMEOUT_KEY:
print("Nothing happened")
35
PySimpleGUI – Python GUIs for Humans
36
6. PySimpleGUI – Element Class
PySimpleGUI – Python GUIs for Humans
Spin element A spinner with up/down buttons and a single line of text.
37
PySimpleGUI – Python GUIs for Humans
38
7. PySimpleGUI – Events
PySimpleGUI – Python GUIs for Humans
Any GUI application is event driven, having the ability to respond to the
various possible events occurring on the GUI elements. In PySimpleGUI,
the event handling is done inside an infinite loop below the constitution of
GUI design, continuously checking whether an event occurs and perform
the actions based on the event.
The window events are enabled by default, and include the button events
(occur when any button is clicked) and the event of the "X" button on the
titlebar clicked.
The element events are not enabled by default. Element-specific events can
be detected only when the "enable_events" parameter is set to True when
an element is created.
if event == psg.WIN_CLOSED:
break
...
window.close()
39
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print(event, values)
if event == "Add":
result = int(values['-FIRST-']) + int(values['-SECOND-'])
if event == "Sub":
result = int(values['-FIRST-']) - int(values['-SECOND-'])
window['-OUT-'].update(result)
In this case, as the "X" button is pressed, the Popup with Yes/No button
appears and the program exits when the "Yes" button is clicked.
40
PySimpleGUI – Python GUIs for Humans
The event value also returns the "-WINDOW CLOSE ATTEMPTED-" value.
Button Events
The button click event is enabled by default. To disable, use
"Button.update(disabled=True)". You can also set "enable_events=True" in
Button’s constructor, it will enable the Button Modified event. This event is
triggered when something 'writes' to a button.
In the above example, since the key parameter is not set on the Add and
Sub buttons, their captions are returned when the window is read.
layout = [
[psg.Text('Enter a num: '), psg.Input(key='-FIRST-')],
[psg.Text('Enter a num: '), psg.Input(key='-SECOND-')],
[psg.Text('Result : '), psg.Text(key='-OUT-')],
[psg.Button("Add", key='-ADD-'), psg.Button("Sub", key='-
SUB-'), psg.Exit()],
]
41
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print(event, values)
if event == "-ADD-":
result = int(values['-FIRST-']) + int(values['-SECOND-'])
if event == "-SUB-":
result = int(values['-FIRST-']) - int(values['-SECOND-'])
window['-OUT-'].update(result)
window.close()
The tuple returned by the read() method will now show the key of button
pressed.
The following table shows the elements and the events generated by them.
Name Events
InputText any key pressed
42
PySimpleGUI – Python GUIs for Humans
43
8. PySimpleGUI – Text Element
PySimpleGUI – Python GUIs for Humans
The Text element is one of the basic and most commonly used elements.
An object of the Text class displays a non-editable, single line of text
containing Unicode characters. Although most of the times, it is not used to
respond to events, it can emit the event having its key as the name.
The Text element has the following properties in addition to those derived
from the Element class:
The most important method defined in the Text class is the get() method
that retrieves the current value of the displayed text, to be used
programmatically elsewhere. You can also change the displayed text
programmatically by capturing the click event, which should be enabled in
the constructor.
The following example initially displays "Hello World" on the Text element,
which changes to "Hello Python", when clicked.
44
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print(event, values)
if event == '-TEXT-':
window['-TEXT-'].update("Hello Python")
window.close()
Run the above program. Click the label to change its text as shown below:
45
9. PySimpleGUI – Input Element
PySimpleGUI – Python GUIs for Humans
This type of widget is most popular in any GUI toolkit. The Input element is
based on the Entry widget in TKinter. The object of this class gives a input
text field of single line.
The Input class defines the get() method which returns the text entered by
the user. The update() method changes some of the settings for the Input
Element. Following properties are defined:
In the example give below, the window has an Input element to accept user
input. It is programmed to accept only digits. If any non-digit key is
pressed, a message pops up informing that it is not allowed. For that, the
last character from the Input is compared with a string made of digit
46
PySimpleGUI – Python GUIs for Humans
characters. If the last key pressed is not a digit, it is removed from the
Input box.
while True:
event, values = window.read()
print(event, values)
if event == '-INPUT-':
if values['-INPUT-'][-1] not in ('0123456789'):
psg.popup("Only digits allowed")
window['-INPUT-'].update(values['-INPUT-'][:-1])
window.close()
47
PySimpleGUI – Python GUIs for Humans
Multiline Element
If you wish to input a text consisting of mor than one lines, you can use
Multiline element instead of Input element. In fact, it is used as an input as
well as output element. If the length of the text is more than the
height/width of the text entered/displayed, the scroll bars appear to the
element.
48
PySimpleGUI – Python GUIs for Humans
Like the Input element, the Multiline class also has a get() method to
retrieve its text content. The Update() method changes the values of some
properties of this element. For example:
append: If True, then the new value will be added onto the end of
the current value. if False then contents will be replaced.
file = open("zen.txt")
text = file.read()
while True:
event, values = window.read()
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()
49
PySimpleGUI – Python GUIs for Humans
50
10. PySimpleGUIPySimpleGUI
– Button Element
– Python GUIs for Humans
Almost every GUI window will have at least one button. When a button
element is clicked, it initiates a certain action. PySimpleGUI has some
button types with predefined caption. They are defined to perform a specific
task. Ohers with a user defined caption are capable of doing any required
task.
The buttons with predefined caption have a shortcut name. So that a button
with OK as a caption can be created in two ways:
>>> b1=psg.Button("OK")
# OR
>>> b1=psg.OK()
OK
Ok
Submit
Cancel
Yes
No
Exit
Quit
Help
Save
SaveAs
Open
FileBrowse
FilesBrowse
FileSaveAs
FolderBrowse
CalendarButton
ColorChooserButton
51
PySimpleGUI – Python GUIs for Humans
The value of the target property is represented using (row, col) tuple. The
default target is the element in the same row and to the left of this button,
represented by (ThisRow, -1) value. ThisRow means the same row, "-1"
means the element to the button’s immediate left. If a value of target is set
to (None, None), then the button itself will hold the information. The value
can be accessed by using the button's key.
The target property can also be the key property of target element.
FileBrowse
The FileBrowse button opens a file dialog from which a single file can be
selected. In the following code, the path string of the selected file is
displayed in the target Input bow in the same row.
while True:
event, values = window.read()
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()
52
PySimpleGUI – Python GUIs for Humans
The selected file name along with its path is displayed in the Input box.
FilesBrowse
This element allows the user to select multiple files. The return string is the
concatenation of files, separated by ";" character. We shall populate a list
box with the selected files by the following code.
53
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
if event == '-IN-':
window['-LIST-'].Update(values['-IN-'].split(';'))
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()
Here, the Input element with "-IN-" key is hidden by setting the "visible"
property to False. Still, it contains the ";" separated list of selected files.
The string is split at occurrence of ";" character and the list below is file
with the file names.
54
PySimpleGUI – Python GUIs for Humans
FolderBrowse
This element works similar to the FileBrowse element. It is used to select
the current folder. It may be used to set the selected folder as default for
subsequent file related operations.
You can set the "initial_folder" property of this element to a folder name
(along with its path) to open the folder dialog with that folder opened to
start with.
layout = [
[psg.Text('Select a folder', font=('Arial Bold', 20),
expand_x=True, justification='center')],
[psg.Input(enable_events=True, key='-IN-',
font=('Arial Bold', 12), expand_x=True),
psg.FolderBrowse(initial_folder="c:/Python310")]
]
window = psg.Window('FolderChooser Demo', layout, size=(715,
100))
while True:
event, values = window.read()
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()
55
PySimpleGUI – Python GUIs for Humans
The path of the selected folder is displayed in the Input text field.
FileSaveAs
This button also opens a file dialog, but provides a save button so that
information on the PySimpleGUI window can be saved by the name given
by the user. The SaveAs dialog can be customized by the following
properties. We can apply filter on file types to be selected, and set the initial
folder for browsing action.
56
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
if event == '-T1-':
file = open(t1.get())
txt = file.read()
window['-INPUT-'].Update(value=txt)
if event == '-T2-':
file = open(t2.get(), "w")
file.write(t3.get())
file.close()
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()
57
PySimpleGUI – Python GUIs for Humans
Choose the name and destination folder to save the text in a new file.
ColorChooserButton
This button brings up a color dialog. You can choose a color from the
swatches, or using the slider, or setting the RGB values from the spinner.
The dialog box returns the Hex string of the RGB value of the selected
colour. It is displayed in the target input control, and it can be further used
to change the color relate property of any element.
In the following example, the chosen color is used to update the "text_color"
property of the Text element displaying Hello World string.
58
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print(event, values)
if event == '-IN-':
window['-T1-'].update(text_color=values['-IN-'])
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()
59
PySimpleGUI – Python GUIs for Humans
Choose the desired colour and press OK. The Hex string corresponding to it
will be returned and displayed in the target Input element. The get()
method of the Input element is used to fetch it and update the text_color
property of Hello World text.
CalendarButton
This button shows a calendar chooser window. The target element is filled
with return value as a string. Following important properties are defined in
CalendarButton class:
60
PySimpleGUI – Python GUIs for Humans
Using the selector arrows, choose the required date. It will be displayed in
the window.
Image Button
Instead of a text caption, an image can be displayed on the face of a button.
The button class has an "image_filename" property. Assign the name of the
image to be displayed. The image should be PNG or GIF type.
In the following example, the Add, Subtract and Exit buttons have images
instead of captions. To capture their click event, their key parameter is
used.
layout = [
[psg.Text('Enter a num: '), psg.Input(key='-FIRST-')],
[psg.Text('Enter a num: '), psg.Input(key='-SECOND-')],
61
PySimpleGUI – Python GUIs for Humans
window.close()
62
11. PySimpleGUIPySimpleGUI
– ListBox Element
– Python GUIs for Humans
This GUI element in PySimpleGUI toolkit is a container that can display one
or more items, and select from it. You can specify the number of items that
can be visible at a time. If the number of items or their length becomes
more than the dimensions of the Listbox, a vertical and/or horizontal
scrollbar appears towards the right or bottom of the element.
LISTBOX_SELECT_MODE_SINGLE (default)
LISTBOX_SELECT_MODE_MULTIPLE
LISTBOX_SELECT_MODE_BROWSE
LISTBOX_SELECT_MODE_EXTENDED
The Listbox class inherits the update() method from the Element class. It
effects changes in some of the properties when the window gets updated.
The parameters to the update() method are:
63
PySimpleGUI – Python GUIs for Humans
scroll_to_index Scroll the listbox so that this index is the first shown
names = []
lst = psg.Listbox(names, size=(20, 4),
font=('Arial Bold', 14), expand_y=True,
enable_events=True, key='-LIST-')
while True:
event, values = window.read()
print(event, values)
if event in (psg.WIN_CLOSED, 'Exit'):
64
PySimpleGUI – Python GUIs for Humans
break
if event == 'Add':
names.append(values['-INPUT-'])
window['-LIST-'].update(names)
msg = "A new item added : {}".format(values['-INPUT-'])
window['-MSG-'].update(msg)
if event == 'Remove':
val = lst.get()[0]
names.remove(val)
window['-LIST-'].update(names)
msg = "A new item removed : {}".format(val)
window['-MSG-'].update(msg)
window.close()
Run the above code, type some text in the Input box and press Add button.
The text will be added in the listbox below it.
The get() method of the Listbox class returns the list of selected items. By
default, a single item is selectable. The remove button gets the value of the
selected item and removes it from the collection.
65
12. PySimpleGUIPySimpleGUI
– Combo Element
– Python GUIs for Humans
The Combo element is a drop down list. It initially shows an Input element
with an arrow towards its right hand side. When the arrow is clicked, the
list box pulls down. So, you can enter text in the Input text box, or select
an item from the drop down list, so that the selected item shows up in the
Input box.
The get() method returns the current (right now) value of the Combo. The
update() method modifies following properties of the Combo object:
In the following example, we use the selection changed event of the Combo
element. The selected element in the dropdown is removed if the user
responds by pressing Yes on the Popup dialog.
names = []
66
PySimpleGUI – Python GUIs for Humans
layout = [[lst,
psg.Button('Add', ),
psg.Button('Remove'),
psg.Button('Exit')],
[psg.Text("", key='-MSG-',
font=('Arial Bold', 14),
justification='center')]
]
window = psg.Window('Combobox Example',
layout, size=(715, 200))
while True:
event, values = window.read()
print(event, values)
if event in (psg.WIN_CLOSED, 'Exit'):
break
if event == 'Add':
names.append(values['-COMBO-'])
print(names)
window['-COMBO-'].update(values=names, value=values['-COMBO-'])
window['-MSG-'].update(msg)
if event == '-COMBO-':
ch = psg.popup_yes_no("Do you want to Continue?",
title="YesNo")
67
PySimpleGUI – Python GUIs for Humans
if ch == 'Yes':
val = values['-COMBO-']
names.remove(val)
window['-COMBO-'].update(values=names, value=' ')
msg = "A new item removed : {}".format(val)
window['-MSG-'].update(msg)
window.close()
When the Combo object emits the event (identified by its key "-COMBO-")
as an item in the dropdown is clicked. A Yes-No popup is displayed asking
for the confirmation. If the Yes button is clicked, the item corresponding to
the text box of the Combo element is removed from the list and the element
is repopulated by the remaining items.
68
13. PySimpleGUI – Radio Element
PySimpleGUI – Python GUIs for Humans
A Radio button is a type of toggle button. Its state changes to True to False
and vice versa on every click. A caption appears to the right of a circular
clickable region the dot selection indicator in it.
When more than one radio buttons are added as members of a group, they
are mutually exclusive, in the sense only one of the buttons can have True
state and others become False.
Apart from the common properties inherited from the Element class, the
Radio object has following properties important in the context of a Radio
button:
default: Set to True for the one element of the group you want
initially selected
If the "enable_events" property is set to True for all the buttons having
same group_id, the selection changed event is transmitted.
In the following example, three groups of radio buttons are used. The code
computes interest on a loan amount. The interest rate depends on the
gender (less by 0.25% for female), period and the type of loan (personal or
business – 3% more for business loan) selected by the user.
l2 = psg.Text("Gender")
l3 = psg.Text("Period")
l4 = psg.Text("Category")
l5 = psg.Text(" ", expand_x=True,
key='-OUT-', justification='center')
t1 = psg.Input("", key='-AMT-')
b1 = psg.Button("OK")
b2 = psg.Button("Exit")
while True:
rate = 12
period = 5
event, values = window.read()
print(event, values)
70
PySimpleGUI – Python GUIs for Humans
if event == 'OK':
if values['female'] == True: rate = rate - 0.25
if values['one'] == True:
rate = rate + 1
period = 1
if values['ten'] == True:
rate = rate - 1
period = 10
if values['bus'] == True: rate = rate + 3
amt = int(values['-AMT-'])
print(amt, rate, period)
interest = amt * period * rate / 100
window['-OUT-'].update("Interest={}".format(interest))
window.close()
71
14. PySimpleGUI PySimpleGUI
– Checkbox Element
– Python GUIs for Humans
The Checkbox is also a toggle button having two states: checked and
unchecked. It presents a rectangular box which when clicked displays a
check mark (or removes it when it already has one) and a caption next to
it.
Usually, checkbox controls are provided to let the user select one or more
items from the available options. Unlike the Radio button, the Checkboxes
on the GUI window do not belong to any group. Hence, user can make
multiple selections.
Apart from these, other common keyword arguments to set the properties
inherited from the Element class can be given to the constructor.
The two important methods inherited but overridden in the Checkbox class
are:
psg.set_options(font=("Arial Bold",14))
l1=psg.Text("Enter Name")
l2=psg.Text("Faculty")
l3=psg.Text("Subjects")
l4=psg.Text("Category")
l5=psg.Multiline(" ", expand_x=True, key='-OUT-',
expand_y=True,justification='left')
t1=psg.Input("", key='-NM-')
rb=[]
rb.append(psg.Radio("Arts", "faculty", key='arts',
enable_events=True,default=True))
rb.append(psg.Radio("Commerce", "faculty", key='comm',
enable_events=True))
rb.append(psg.Radio("Science", "faculty",
key='sci',enable_events=True))
cb=[]
cb.append(psg.Checkbox("History", key='s1'))
cb.append(psg.Checkbox("Sociology", key='s2'))
cb.append(psg.Checkbox("Economics", key='s3'))
b1=psg.Button("OK")
b2=psg.Button("Exit")
73
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print (event, values)
Name={}
Faculty: {}
Subjects: {}
""".format(values['-NM-'], fac[0], " ".join(subs))
window['-OUT-'].update(out)
window.close()
74
PySimpleGUI – Python GUIs for Humans
Run the above code. Select a faculty name and mark checks in the
corresponding check buttons to register the selection. Note that the
subjects change as the faculty option is changed.
Press the OK button so that the choices are printed in the Multiline box, as
shown below:
75
15. PySimpleGUI – Slider Element
PySimpleGUI – Python GUIs for Humans
These parameters are specific to the Slider control. The description of these
parameters is given below:
range: The slider's bar represents this range (min value, max
value)
Other attributes inherited from the Element class, such as color, size, font
etc can be used to further customize the Slider object.
The update() method of the Slider class helps in refreshing the following
parameters of the Slider object:
76
PySimpleGUI – Python GUIs for Humans
Whenever the slider button is moved across, the "-SL-" event occurs. The
instantaneous value of the slider button is used as the font size and the
Text caption is refreshed.
layout = [
while True:
event, values = window.read()
print(event, values)
window.close()
77
PySimpleGUI – Python GUIs for Humans
Save and run the above code. As you move the slider button, the font size
of the Hello World text keeps changing. The output window will appear as
follows:
78
16. PySimpleGUI – Spin Element
PySimpleGUI – Python GUIs for Humans
Where,
The get() method of the Spin class returns the current item displayed in its
text box. On the other hand, the update() method is used to dynamically
change following properties of the Spin element:
The Spin element generates the selection changed event identified by the
key parameter when the up/down button is clicked.
In the following example, we construct a simple date selector with the help
of three Spin elements – for date, name of month and year between 2000
to 2025. Ranges for date and year elements are numeric whereas for the
month spin element, the range is of strings.
79
PySimpleGUI – Python GUIs for Humans
months = calendar.month_abbr[1:]
s2 = psg.Spin(months, initial_value='Jan', readonly=True,
size=10, enable_events=True, key='-MON-')
layout = [
[psg.Text('Date'), s1, psg.Text("Month"), s2, psg.Text("Year"), s3],
while True:
event, values = window.read()
if event == 'OK':
datestr = str(values['-DAY-']) + " " \
+ values['-MON-'] + "," \
+ str(values['-YR-'])
try:
d = datetime.strptime(datestr, '%d %b,%Y')
window['-OUT-'].update("Date: {}".format(datestr))
80
PySimpleGUI – Python GUIs for Humans
except:
window['-OUT-'].update("")
psg.Popup("Invalid date")
if event == psg.WIN_CLOSED:
break
window.close()
Set the Spin elements to the desired date value and press OK. If the date
string represents a valid date, it is displayed in the Text element in the
bottom row.
81
17. PySimpleGUI –PySimpleGUI
ProgressBar element
– Python GUIs for Humans
bar_color: The two colors that make up a progress bar. First color
shows the progress. Second color is the background.
layout = [
[psg.ProgressBar(100, orientation='h',
expand_x=True, size=(20, 20),
key='-PBAR-'), psg.Button('Test')],
[psg.Text('', key='-OUT-', enable_events=True,
82
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print(event, values)
if event == 'Test':
window['Test'].update(disabled=True)
for i in range(100):
window['-PBAR-'].update(current_count=i + 1)
window['-OUT-'].update(str(i + 1))
time.sleep(1)
window['Test'].update(disabled=False)
if event == 'Cancel':
window['-PBAR-'].update(max=100)
window.close()
83
18. PySimpleGUI – Frame Element
PySimpleGUI – Python GUIs for Humans
The title parameter is the text that is displayed as the Frame's "label" or
title. The Frame object can be seen as a child layout of the layout of the
main window. It may also be a list of list of elements.
The Frame object is not normally used as an event listener. Still, when
clicked on the area of frame, its title can be updated although this feature
is rarely used.
The following code is the same that was used as the example of checkbox.
Here, the three radio buttons for choosing the Faculty and the subjects in
the chosen faculty as checkboxes are put in separate frames.
l1 = psg.Text("Enter Name")
l2 = psg.Text("Faculty")
l3 = psg.Text("Subjects")
l4 = psg.Text("Category")
l5 = psg.Multiline(" ", expand_x=True, key='-OUT-',
expand_y=True, justification='left')
t1 = psg.Input("", key='-NM-')
84
PySimpleGUI – Python GUIs for Humans
rb = []
rb.append(psg.Radio("Arts", "faculty", key='arts',
enable_events=True, default=True))
rb.append(psg.Radio("Commerce", "faculty", key='comm',
enable_events=True))
rb.append(psg.Radio("Science", "faculty", key='sci',
enable_events=True))
cb = []
cb.append(psg.Checkbox("History", key='s1'))
cb.append(psg.Checkbox("Sociology", key='s2'))
cb.append(psg.Checkbox("Economics", key='s3'))
b1 = psg.Button("OK")
b2 = psg.Button("Exit")
85
19. PySimpleGUIPySimpleGUI
– Column Element
– Python GUIs for Humans
The Column element is also a container widget. It is very useful if you want
to design the GUI window elements represented in one or more vertical
columns. Just as a window, the Column area places the other PySimpleGUI
elements in a layout consisting of list of lists.
Where,
Although the container elements like Column normally are not event
listeners, its visible property may be dynamically updated.
The following code shows how you can use the Column element. The main
layout’s upper row has a Text and Input element. The last row has "Ok" and
"Cancel" buttons. The middle row has two columns, each having input
elements for entering the correspondence and permanent address. Their
86
PySimpleGUI – Python GUIs for Humans
element layouts are stored as col1 and col2. These are used to declare two
Column objects and placed in the list for middle row of the main layout.
psg.set_options(font=("Arial Bold",10))
l=psg.Text("Enter Name")
l1=psg.Text("Address for Correspondence")
l2=psg.Text("Permanent Address")
t=psg.Input("", key='-NM-')
a11=psg.Input(key='-a11-')
a12=psg.Input(key='-a12-')
a13=psg.Input(key='-a13-')
a21=psg.Input(key='-a21-')
a22=psg.Input(key='-a22-')
a23=psg.Input(key='-a23-')
layout=[[l,t],[psg.Column(col1), psg.Column(col2)],
[psg.OK(), psg.Cancel()]]
while True:
87
PySimpleGUI – Python GUIs for Humans
window.close()
88
20. PySimpleGUI – Tab Element
PySimpleGUI – Python GUIs for Humans
Sometimes, the application’s GUI design is too big to fit in a single window,
and even if we try to arrange all the elements in a layout for the main
window, it becomes very clumsy. The use of Tab elements makes the design
very convenient, effective and easy for the user to navigate. Tab element
is also a container element such as Frame or Column.
First divide the elements in logically relevant groups and put them in
separate layouts. Each of them is used to construct a Tab element. These
Tab elements are put in a TabGroup as per the following syntax:
Tg = PySimpleGUI.TabGroup([[tab1, tab2]])
# This titlegroup object may be further used
# in the row of the main layout.
The advantage of the tabgroup and tab elements is that only one tab of all
the tabs in a group is visible at a time. When you click the title of one tab,
it becomes visible and all others are hidden. So that, the entire available
area can be utilized to display the elements in a single tab. This makes the
GUI design very clean and effective.
Remember that the Tab elements are never placed directly in the main
layout. They are always contained in a TabGroup.
Here, the title parameter is a string displayed on the tab. The layout refers
to the nested list of elements to be shown on the top and the title_color the
color to be used for displaying the title.
89
PySimpleGUI – Python GUIs for Humans
psg.set_options(font=("Arial Bold",14))
l1=psg.Text("Enter Name")
lt1=psg.Text("Address")
t1=psg.Input("", key='-NM-')
a11=psg.Input(key='-a11-')
a12=psg.Input(key='-a12-')
a13=psg.Input(key='-a13-')
lt2=psg.Text("EmailID:")
lt3=psg.Text("Mob No:")
a21=psg.Input("", key='-ID-')
a22=psg.Input("", key='-MOB-')
layout = [[psg.TabGroup([
[psg.Tab('Basic Info', tab1),
psg.Tab('Contact Details', tab2)]])],
[psg.OK(), psg.Cancel()]
]
90
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print (event, values)
if event in (psg.WIN_CLOSED, 'Exit'):
break
window.close()
Run the above code. The main window with two tabs is displayed, with the
first tab visible by default.
Click the title of the second tab which will show the two Input controls for
entering the EmailID and the Mobile number.
91
21. PySimpleGUIPySimpleGUI
– Canvas Element
– Python GUIs for Humans
Where,
tkc = can.TkCanvas
92
PySimpleGUI – Python GUIs for Humans
import PySimpleGUI as sg
can=sg.Canvas(size=(700,500),
background_color='grey',
key='canvas')
layout = [[can]]
tkc=can.TKCanvas
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
When the above code is run, you get the following result:
93
PySimpleGUI – Python GUIs for Humans
94
22. PySimpleGUI – Graph Element
PySimpleGUI – Python GUIs for Humans
The Graph element is similar to Canvas, but very powerful. You can define
your own coordinate system, working in your own units, and then displaying
them in an area defined in pixels.
draw_lines(self, points,
color='black', width=1)
95
PySimpleGUI – Python GUIs for Humans
draw_point(self, point,
size=2, color='black')
draw_polygon(self, points,
fill_color=None, line_color=None,
line_width=None)
Apart from the above draw methods, the Graph class also defines the
move_figure() method by which the image identified by its ID is moved
to its new position by giving new coordinates relative to its previous
coordinates.
The mouse event inside the graph area can be captured if you set
drag_submits property to True. When you click anywhere in the graph area,
the event generated is: Graph_key + '+UP'.
In the following example, we draw a small circle at the center of the graph
element. Below the graph object, there are buttons for moving the circle in
left, right, up and down direction. When clicked, the mov_figure() method
is called.
graph=psg.Graph(canvas_size=(700,300),
graph_bottom_left=(0, 0),
graph_top_right=(700,300),
background_color='red',
96
PySimpleGUI – Python GUIs for Humans
enable_events=True,
drag_submits=True, key='graph')
x1,y1 = 350,150
while True:
event, values = window.read()
if event == psg.WIN_CLOSED:
break
if event == 'RIGHT':
graph.MoveFigure(circle, 10, 0)
if event == 'LEFT':
graph.MoveFigure(circle, -10,0)
if event == 'UP':
graph.MoveFigure(circle, 0, 10)
if event == 'DOWN':
graph.MoveFigure(circle, 0,-10)
if event=="graph+UP":
x2,y2= values['graph']
97
PySimpleGUI – Python GUIs for Humans
window.close()
Run the above program. Use the buttons to move the circle.
98
23. PySimpleGUI – Menubar
PySimpleGUI – Python GUIs for Humans
You may have a sub-menu under an option button, in which case the
captions are put in a third level list. Likewise, the captions can be nested
up to any level.
menu_def = [
['Memu1', ['btn1', 'btn2', 'btn3', 'btn4',]],
['menu2', ['btn5', 'btn6','btn7', 'btn8'],],
]
The Menu constructor is given the menu_def list as the argument. Other
rows of the main layout may be given after the row having Menu object.
In the code given below, we have a menu bar with File, Edit and Help
menus, each having a few menu buttons in respective menu bar.
99
PySimpleGUI – Python GUIs for Humans
layout = [[psg.Menu(menu_def)],
[psg.Multiline("", key='-IN-',
expand_x=True, expand_y=True)],
[psg.Multiline("", key='-OUT-',
expand_x=True, expand_y=True)],
[psg.Text("", key='-TXT-',
expand_x=True, font=("Arial Bold", 14))]
]
window = psg.Window("Menu", layout, size=(715, 300))
while True:
event, values = window.read()
print(event, values)
if event != psg.WIN_CLOSED:
window['-TXT-'].update(values[0] + "Menu Button Clicked")
if event == 'Copy':
txt = window['-IN-'].get()
if event == 'Paste':
window['-OUT-'].update(value=txt)
if event == psg.WIN_CLOSED:
break
window.close()
Below the Menubar, two Multiline elements are placed. The last row has a
Text element.
100
PySimpleGUI – Python GUIs for Humans
When any menu option button is clicked, the event so generated is the
caption of the button. This caption is displayed on the Text label in the last
row. Refer to the following figure:
When the Copy event occurs, the text in the upper multiline box with -IN-
key is stored in a txt variable. Afterwards, when Paste button is pressed,
the -OUT- box is updated with the value of txt.
101
PySimpleGUI – Python GUIs for Humans
menu_def = [
['&File', ['&New', '&Open', '&Save', 'E&xit',]],
['&Edit', ['C&ut', '&Copy','&Paste', '&Undo'],],
['&Help', '&About...'],
]
When the code is run, the hot keys in the menu are shown as underlined.
Right-click Menu
This menu is detached from the menubar which is at the top of the
application window. Whenever the user presses the right click button of the
mouse, this menu pops up at the same position where the click takes place.
Let us use rightclick as a variable for the list corresponding to the Edit menu.
menu_def = [
102
PySimpleGUI – Python GUIs for Humans
Make these changes and run the code. Click anywhere in the window. The
menu pops up as shown:
ButtonMenu
This menu is similar to the right click menu, except that it is attached to a
button and pops up when the button is clicked.
In the last row of the main layout, we add a ButtonMenu element and use
the rightclick list as its layout.
layout= [
[psg.Menu(menu_def)],
[psg.Multiline("", key='-IN-', expand_x=True, expand_y=True)],
[psg.Multiline("", key='-OUT-', expand_x=True, expand_y=True)],
103
PySimpleGUI – Python GUIs for Humans
When the button at the lower right is clicked, the menu comes up as can be
seen in the following figure:
104
24. PySimpleGUI – Table Element
PySimpleGUI – Python GUIs for Humans
The Table object is a useful GUI widget in any GUI library. Its purpose is to
display a two-dimensional data structure of numbers and strings in a tabular
form having rows and columns.
display_row_numbers If True, the first column of the table will be the row
105
PySimpleGUI – Python GUIs for Humans
layout = [[tbl1]]
106
PySimpleGUI – Python GUIs for Humans
while True:
event, values = window.read()
print("event:", event, "values:", values)
if event == psg.WIN_CLOSED:
break
if '+CLICKED+' in event:
psg.popup("You clicked row:{} Column:
{}".format(event[2][0], event[2][1]))
window.close()
The Table object also has an update() method to dynamically update the
table properties such as values, num_rows, and row_color.
107
25. PySimpleGUI – Tree Element
PySimpleGUI – Python GUIs for Humans
treedata = psg.TreeData()
Use the insert() method of the TreeData class to construct the hierarchy
of nodes.
To insert a node at the first level of the tree, use the parant_key as "". So,
every top-level node in the tree will have a parent node = "". To insert a
child node, give the key of the node at the upper level as its parent_key.
For example,
108
PySimpleGUI – Python GUIs for Humans
psg.set_options(font=("Arial Bold",14))
treedata = psg.TreeData()
rootnodes=[
["","MH", "Maharashtra", 175, 150, 200],
["MH", "MUM", "Mumbai", 100, 100,100],
["MH", "PUN", "Pune", 30, 20, 40],
["MH", "NGP", "Nagpur", 45, 30, 60],
["","TEL", "Telangana", 120, 80, 125],
["TEL", "HYD", "Hyderabad", 75, 55, 80],
["TEL", "SEC", "Secunderabad", 25, 15, 30],
["TEL", "NZB", "Nizamabad", 20, 10, 15]
]
tree=psg.Tree(data=treedata,
headings=['Product A','Product B','Product C' ],
auto_size_columns=True,
select_mode=psg.TABLE_SELECT_MODE_EXTENDED,
num_rows=10,
109
PySimpleGUI – Python GUIs for Humans
col0_width=5,
key='-TREE-',
show_expanded=False,
enable_events=True,
expand_x=True,
expand_y=True,
)
layout=[[tree]]
window=psg.Window("Tree Demo", layout,
size=(715, 200), resizable=True)
while True:
event, values = window.read()
print ("event:",event, "values:",values)
if event == psg.WIN_CLOSED:
break
110
26. PySimpleGUI – Image Element
PySimpleGUI – Python GUIs for Humans
The PySimpleGUI library contains an Image element, which has the ability
to display images of PNG, GIF, PPM/PGM format. The Image() function
needs one mandatory argument which is the path to the image file.
while True:
event, values = window.read()
print(event, values)
window.close()
111
PySimpleGUI – Python GUIs for Humans
layout = [
[graph],
[psg.Button('LEFT'), psg.Button('RIGHT'),
psg.Button('UP'), psg.Button('DOWN')]
]
112
PySimpleGUI – Python GUIs for Humans
id = graph.draw_image(filename="PySimpleGUI_Logo.png",
location=(0, 300))
while True:
event, values = window.read()
if event == psg.WIN_CLOSED:
break
if event == 'RIGHT':
graph.MoveFigure(id, 10, 0)
if event == 'LEFT':
graph.MoveFigure(id, -10, 0)
if event == 'UP':
graph.MoveFigure(id, 0, 10)
if event == 'DOWN':
graph.MoveFigure(id, 0, -10)
if event == "graph+UP":
x2, y2 = values['graph']
graph.MoveFigure(id, x2 - x1, y2 - y1)
x1, y1 = x2, y2
window.close()
113
27. PySimpleGUI – PySimpleGUI
Matplotlib Integration
– Python GUIs for Humans
When Matplotlib is used from Python shell, the plots are displayed in a
default window. The backend_tkagg module is useful for embedding plots
in Tkinter.
First, we need to create the figure object using the Figure() class and a
plot to it. We shall draw a simple plot showing sine wave.
layout = [
[psg.Text('Plot test')],
[psg.Canvas(key='-CANVAS-')],
[psg.Button('Ok')]
]
114
PySimpleGUI – Python GUIs for Humans
Draw the figure by calling the above function. Pass the Canvas object and
fifure object to it.
matplotlib.use('TkAgg')
return tkcanvas
115
PySimpleGUI – Python GUIs for Humans
window.close()
116
28. PySimpleGUIPySimpleGUI
– Working with PIL
– Python GUIs for Humans
In the following example, we obtain the byte value of the PNG image with PIL
function and display the same in Image element on a PySimpleGUI window.
import PySimpleGUI as sg
import PIL.Image
import io
import base64
imgdata = convert_to_bytes("PySimpleGUI_logo.png")
layout = [[sg.Image(key='-IMAGE-', data=imgdata)]]
window = sg.Window('PIL based Image Viewer', layout,resizable=True)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
window.close()
117
PySimpleGUI – Python GUIs for Humans
118
29. PySimpleGUI – Debugger
PySimpleGUI – Python GUIs for Humans
import PySimpleGUI as sg
sg.show_debugger_window(location=(10,10))
while True:
event, values = window.read(timeout=500)
if event == sg.TIMEOUT_KEY:
continue
if event == sg.WIN_CLOSED:
break
print(event, values)
window.close()
119
PySimpleGUI – Python GUIs for Humans
The window shows two tabs Variables and REPL. Click on the Variables tab.
A list of variables to auto-watch is shown Check the ones that you want to
watch during the execution of the program.
120
PySimpleGUI – Python GUIs for Humans
121
30. PySimpleGUI – Settings
PySimpleGUI – Python GUIs for Humans
Global Settings
Global settings are the application settings available application wide. These
settings control the various properties of the Element class to be applied to
all the Elements in the application.
For example, if the font size is set to 16 globally, the text of all elements is
displayed accordingly. However, if a specific Text or Input element with Font
property with size other than 16 is defined in the layout, it will change the
appearance accordingly.
The function set_options is used to change settings that will apply globally.
If it's a setting that applies to Windows, then that setting will apply not only
to Windows that you create, but also to popup Windows.
import PySimpleGUI as sg
sg.set_options(font=('Arial Bold', 16))
User Settings
"User settings" is a dictionary that is automatically written to your hard
drive. User settings are stored in a Python dictionary which is saved to and
loaded from the disk. Individual settings are thus keys into a dictionary.
Function Description
user_settings Returns settings as a dictionary
user_settings_delete_entry Deletes a setting
user_settings_delete_filename Deletes the settings file
Returns True if settings file
user_settings_file_exists
specified exists
122
PySimpleGUI – Python GUIs for Humans
settings = sg.UserSettings()
Use the dictionary-style [ ] syntax to read a setting. If the item's name is '-
item-', then reading the value is achieved by writing
item_value = settings['-item-']
settings['-item-'] = new_value
del settings['-item-']
You can also call the delete_entry method to delete the entry.
settings.delete_entry('-item-')
import PySimpleGUI as sg
import json
123
PySimpleGUI – Python GUIs for Humans
layout = [
[sg.Text('Settings', justification='left')],
# Event Loop
while True:
event, values = window.read()
if event == 'LOAD':
f = open("settings.txt", 'r')
settings = json.load(f)
window['-USER-'].update(value=settings['-USER-'])
window['-ID-'].update(value=settings['-ID-'])
window['-ROLE-'].update(value=settings['-ROLE-'])
124
PySimpleGUI – Python GUIs for Humans
if event == 'SAVE':
settings = {'-USER-': values['-USER-'],
'-ID-': values['-ID-'],
'-ROLE-': values['-ROLE-']}
f = open("settings.txt", 'w')
json.dump(settings, f)
f.close()
window.close()
Enter the data in the input boxes and click the "Save" button.
A JSON file will be saved. To load the previously saved settings, click the
"Load" button.
125