100% found this document useful (14 votes)
29 views

Download Complete (Ebook) Python GUI Programming Cookbook by Burkhard A. Meier ISBN 9781787129450, 1787129454 PDF for All Chapters

Programming

Uploaded by

caydesteffds
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (14 votes)
29 views

Download Complete (Ebook) Python GUI Programming Cookbook by Burkhard A. Meier ISBN 9781787129450, 1787129454 PDF for All Chapters

Programming

Uploaded by

caydesteffds
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Python GUI Programming Cookbook by


Burkhard A. Meier ISBN 9781787129450, 1787129454

https://ebooknice.com/product/python-gui-programming-
cookbook-6821428

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Python GUI Programming Cookbook by Meier, Burkhard


A ISBN 9781787129023, 9781787129450, 1787129020,
1787129454
https://ebooknice.com/product/python-gui-programming-cookbook-11861058

ebooknice.com

(Ebook) Python GUI Programming Cookbook: Use recipes to


develop responsive and powerful GUIs using Tkinter, 2nd
Edition by Meier, Burkhard A. ISBN 9781787129450,
1787129454
https://ebooknice.com/product/python-gui-programming-cookbook-use-
recipes-to-develop-responsive-and-powerful-guis-using-tkinter-2nd-
edition-29873630
ebooknice.com

(Ebook) GUI Programming with Python: QT Edition by


Boudewijn Rempt ISBN 9780970033048, 0970033044

https://ebooknice.com/product/gui-programming-with-python-qt-
edition-5644898

ebooknice.com

(Ebook) Maya Programming with Python Cookbook by Herbez,


Adrian;

https://ebooknice.com/product/maya-programming-with-python-
cookbook-55668148

ebooknice.com
(Ebook) Rapid GUI Programming with Python and Qt: The
Definitive Guide to PyQt Programming (paperback) by
Summerfield, Mark ISBN 9780134393339, 0134393333
https://ebooknice.com/product/rapid-gui-programming-with-python-and-
qt-the-definitive-guide-to-pyqt-programming-paperback-36002214

ebooknice.com

(Ebook) QT6 C++ GUI Programming Cookbook: Practical


recipes for building cross-platform GUI applications,
widgets, and animations with Qt6 by Lee Zhi Eng ISBN
9781805122630, 1805122630
https://ebooknice.com/product/qt6-c-gui-programming-cookbook-
practical-recipes-for-building-cross-platform-gui-applications-
widgets-and-animations-with-qt6-58733138
ebooknice.com

(Ebook) Rapid GUI Programming with Python and Qt.


Definitive Guide to PyQt by Mark Summerfield ISBN
9780132354189, 0132354187
https://ebooknice.com/product/rapid-gui-programming-with-python-and-
qt-definitive-guide-to-pyqt-1021714

ebooknice.com

(Ebook) Python Parallel Programming Cookbook by Giancarlo


Zaccone ISBN 9781785289583, 1785289586

https://ebooknice.com/product/python-parallel-programming-
cookbook-7296210

ebooknice.com

(Ebook) Programming ArcGIS with Python Cookbook by Eric


Pimpler ISBN 9781785282898, 1785282891

https://ebooknice.com/product/programming-arcgis-with-python-
cookbook-6809154

ebooknice.com
Python GUI Programming
Cookbook
Second Edition

Develop beautiful and powerful GUIs using the Python


programming language

Burkhard A. Meier

BIRMINGHAM - MUMBAI
Python GUI Programming Cookbook
Second Edition
Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be caused
directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: November 2015

Second edition: May 2017

Production reference: 1190517

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78712-945-0

www.packtpub.com
Credits

Author Copy Editor


Burkhard A. Meier Muktikant Garimella

Reviewer Project Coordinator


Mohit Ulhas Kambali

Commissioning Editor Proofreader


Kunal Parikh Safis Editing

Acquisition Editor Indexer


Denim Pinto Aishwarya Gangawane

Content Development Editor Graphics


Anurag Ghogre Abhinash Sahu

Technical Editor Production Coordinator


Prashant Mishra Nilesh Mohite
About the Author
Burkhard A. Meier has more than 17 years of professional experience working in the
software industry as a software tester and developer, specializing in software test
automation development, execution, and analysis. He has a very strong background in
Python 3 software test automation development, as well as in SQL relational database
administration, the development of stored procedures, and debugging code.

While experienced in Visual Studio .NET C#, Visual Test, TestComplete, and other testing
languages (such as C/C++), the main focus of the author over the past five years has been
developing test automation written in Python 3 to test the leading edge of FLIR ONE (now
in its third generation) infrared cameras for iPhone and Android smart phones and
handheld tablets, as well as assuring the quality of FLIR bolometer IR camera platforms.

Being highly appreciative of art, beauty, and programming, the author developed GUIs in
C# and Python to streamline everyday test automation tasks, enabling these automated tests
to run unattended for weeks, collecting very useful data to be analyzed, automatically
plotted in graphs, and e-mailed to upper management upon completion of nightly
automated test runs.

His previous jobs include working as a senior test automation engineer and designer for
InfoGenesis (now Agilysys), QAD, InTouch Health, and FLIR Systems.

You can get in touch with him through his LinkedIn account, https://www.linkedin.com
/pub/burkhard-meier/5/246/296.

I would like to thank all truly great artists, such as Leonardo da Vinci, Charles Baudelaire,
Edgar Allan Poe, and so many more for bringing the presence of beauty into our human
lives. This book is about creating very beautiful GUIs written in the Python programming
language, and it was inspired by these truly great artists.
I would like to thank all of the great people that made this book possible. Without any of
you, this book would only exist in my mind. I would like to especially thank all of my
editors at Packt Publishing: Sonali, Anurag, Prashant, Vivek, Arwa, Sumeet, Saurabh,
Pramod, Nikhil, and so many more. I would also like to thank all of the reviewers of the
code of this book. Without them, this book would be harder to read and apply to real-world
problems. Last but not least, I'd like to thank my wife, our daughter, and our parents for
the emotional support they provided so successfully during the writing of the second
edition of this book. I'd also like to give thanks to the creator of the very beautiful and
powerful programming language that Python truly is. Thank you Guido.
About the Reviewer
Mohit (mohitraj.cs@gmail.com) is a Python programmer with a keen interest in the field
of information security. He completed his bachelor’s in technology in computer science
from Kurukshetra University, Kurukshetra, and master’s in engineering (2012) in computer
science from Thapar University, Patiala. He is a C|EH, ECSA from EC-Council USA and
former IBMer. He has published several articles in national and international magazines. He
is the author of Python Penetration Testing Essentials and Python Penetration Testing for
Developers, also by Packt Publishing.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial
process. To help us improve, please leave us an honest review on this book's Amazon page
at https://www.amazon.com/dp/1787129454.

If you'd like to join our team of regular reviewers, you can e-mail us at
customerreviews@packtpub.com. We award our regular reviewers with free eBooks and
videos in exchange for their valuable feedback. Help us be relentless in improving our
products!
Table of Contents
Preface 1
Chapter 1: Creating the GUI Form and Adding Widgets 7
Introduction 7
Creating our first Python GUI 9
Getting ready 9
How to do it… 10
How it works… 10
There's more… 11
Preventing the GUI from being resized 12
Getting ready 12
How to do it… 12
How it works… 13
Adding a label to the GUI form 14
Getting ready 14
How to do it… 14
How it works… 15
There's more… 16
Creating buttons and changing their text property 16
Getting ready 17
How to do it… 17
How it works… 18
There's more… 18
Text box widgets 19
Getting ready 19
How to do it… 19
How it works… 20
Setting the focus to a widget and disabling widgets 21
Getting ready 21
How to do it… 21
How it works… 23
There's more… 23
Combo box widgets 24
Getting ready 24
How to do it… 24
How it works… 25
There's more… 26
Creating a check button with different initial states 26
Getting ready 26
How to do it… 27
How it works… 28
Using radio button widgets 28
Getting ready 29
How to do it… 29
How it works… 30
There's more… 31
Using scrolled text widgets 31
Getting ready 31
How to do it… 32
How it works… 33
Adding several widgets in a loop 34
Getting ready 34
How to do it… 34
How it works… 35
There's more… 35
Chapter 2: Layout Management 36
Introduction 36
Arranging several labels within a label frame widget 38
Getting ready 38
How to do it… 38
How it works… 40
There's more… 41
Using padding to add space around widgets 41
Getting ready 41
How to do it… 41
How it works… 42
How widgets dynamically expand the GUI 44
Getting ready 45
How to do it… 45
How it works… 49
There's more… 49
Aligning the GUI widgets by embedding frames within frames 49
Getting ready 49
How to do it… 50

[ ii ]
How it works… 53
Creating menu bars 54
Getting ready 55
How to do it… 55
How it works… 61
There's more… 62
Creating tabbed widgets 62
Getting ready 62
How to do it… 63
How it works… 68
Using the grid layout manager 68
Getting ready… 68
How to do it… 68
How it works… 70
Chapter 3: Look and Feel Customization 71
Introduction 71
Creating message boxes – information, warning, and error 72
Getting ready 73
How to do it… 73
How it works… 75
How to create independent message boxes 77
Getting ready 77
How to do it… 77
How it works… 80
How to create the title of a tkinter window form 81
Getting ready 81
How to do it… 81
How it works… 81
Changing the icon of the main root window 82
Getting ready 82
How to do it… 82
How it works… 83
Using a spin box control 83
Getting ready 83
How to do it... 83
How it works… 87
Relief, sunken and raised appearance of widgets 87
Getting ready 87
How to do it… 88

[ iii ]
How it works… 89
Creating tooltips using Python 90
Getting ready 90
How to do it… 91
How it works… 93
Adding a progressbar to the GUI 94
Getting ready 94
How to do it… 95
How it works… 97
How to use the canvas widget 97
Getting ready 97
How to do it… 98
How it works… 98
Chapter 4: Data and Classes 100
Introduction 100
How to use StringVar() 102
Getting ready 102
How to do it… 103
How it works… 105
How to get data from a widget 108
Getting ready 108
How to do it… 108
How it works… 109
Using module-level global variables 110
Getting ready 110
How to do it… 110
How it works… 111
How coding in classes can improve the GUI 114
Getting ready 115
How to do it… 115
How it works… 120
Writing callback functions 120
Getting ready 121
How to do it… 121
How it works… 121
Creating reusable GUI components 122
Getting ready 122
How to do it… 122
How it works… 126

[ iv ]
Chapter 5: Matplotlib Charts 127
Introduction 127
Creating beautiful charts using Matplotlib 128
Getting ready 128
How to do it… 129
How it works… 131
Installing Matplotlib using pip with whl extension 131
Getting ready 131
How to do it… 134
How it works… 137
Creating our first chart 138
Getting ready 138
How to do it… 138
How it works… 139
Placing labels on charts 140
Getting ready 140
How to do it... 140
How it works… 145
How to give the chart a legend 146
Getting ready 146
How to do it… 146
How it works… 149
Scaling charts 149
Getting ready 150
How to do it… 150
How it works… 151
Adjusting the scale of charts dynamically 152
Getting ready 152
How to do it… 152
How it works… 156
Chapter 6: Threads and Networking 157
Introduction 157
How to create multiple threads 159
Getting ready 160
How to do it… 160
How it works… 163
Starting a thread 163
Getting ready 163

[v]
How to do it… 165
How it works… 168
Stopping a thread 169
Getting ready 169
How to do it… 169
How it works… 172
How to use queues 173
Getting ready 173
How to do it… 174
How it works… 179
Passing queues among different modules 179
Getting ready 180
How to do it… 180
How it works… 182
Using dialog widgets to copy files to your network 183
Getting ready 183
How to do it… 183
How it works… 193
Using TCP/IP to communicate via networks 194
Getting ready 194
How to do it… 194
How it works… 197
Using urlopen to read data from websites 197
Getting ready 197
How to do it… 197
How it works… 201
Chapter 7: Storing Data in our MySQL Database via our GUI 202
Introduction 202
Installing and connecting to a MySQL server from Python 204
Getting ready 204
How to do it… 207
How it works… 210
Configuring the MySQL database connection 210
Getting ready 211
How to do it… 211
How it works… 214
Designing the Python GUI database 215
Getting ready 215
How to do it… 215

[ vi ]
How it works… 222
Using the SQL INSERT command 222
Getting ready 223
How to do it… 223
How it works… 225
Using the SQL UPDATE command 225
Getting ready 226
How to do it… 226
How it works… 230
Using the SQL DELETE command 231
Getting ready 231
How to do it… 231
How it works… 235
Storing and retrieving data from our MySQL database 235
Getting ready 235
How to do it… 235
How it works… 239
Using the MySQL workbench 239
Getting ready 240
How to do it… 240
How it works… 246
There's more… 246
Chapter 8: Internationalization and Testing 247
Introduction 247
Displaying widget text in different languages 249
Getting ready 249
How to do it… 249
How it works… 251
Changing the entire GUI language, all at once 252
Getting ready 252
How to do it… 252
How it works… 257
Localizing the GUI 257
Getting ready 258
How to do it… 258
How it works… 262
Preparing the GUI for internationalization 263
Getting ready 263
How to do it… 263

[ vii ]
How it works… 267
How to design a GUI in an agile fashion 267
Getting ready 268
How to do it… 268
How it works… 271
Do we need to test the GUI code? 271
Getting ready 272
How to do it… 272
How it works… 275
Setting debug watches 275
Getting ready 276
How to do it… 276
How it works… 280
Configuring different debug output levels 280
Getting ready 280
How to do it… 281
How it works… 283
Creating self-testing code using Python's __main__ section 284
Getting ready 284
How to do it… 284
How it works… 289
Creating robust GUIs using unit tests 289
Getting ready 289
How to do it… 289
How it works… 293
How to write unit tests using the Eclipse PyDev IDE 293
Getting ready 294
How to do it… 294
How it works… 300
Chapter 9: Extending Our GUI with the wxPython Library 301
Introduction 301
Installing the wxPython library 303
Getting ready 303
How to do it… 303
How it works… 306
Creating our GUI in wxPython 306
Getting ready 307
How to do it… 307
How it works… 311

[ viii ]
Quickly adding controls using wxPython 312
Getting ready 312
How to do it… 312
How it works… 317
Trying to embed a main wxPython app in a main tkinter app 318
Getting ready 318
How to do it… 319
How it works… 320
Trying to embed our tkinter GUI code into wxPython 321
Getting ready 321
How to do it… 321
How it works… 323
Using Python to control two different GUI frameworks 324
Getting ready 324
How to do it… 324
How it works… 326
Communicating between the two connected GUIs 327
Getting ready 328
How to do it… 328
How it works… 332
Chapter 10: Creating Amazing 3D GUIs with PyOpenGL and PyGLet 333
Introduction 333
PyOpenGL transforms our GUI 335
Getting ready 335
How to do it… 336
How it works… 339
Our GUI in 3D! 339
Getting ready 340
How to do it… 340
How it works… 344
Using bitmaps to make our GUI pretty 345
Getting ready 345
How to do it… 346
How it works… 348
PyGLet transforms our GUI easier than PyOpenGL 348
How to do it… 349
How it works… 351
Our GUI in amazing colors 351
Getting ready 352

[ ix ]
How to do it… 352
How it works… 355
OpenGL animation 355
Getting ready 356
How to do it… 356
How it works… 362
Creating a slide show using tkinter 362
Getting ready 363
How to do it… 363
How it works… 368
Chapter 11: Best Practices 369
Introduction 369
Avoiding spaghetti code 370
Getting ready 371
How to do it… 371
How it works… 374
Using __init__ to connect modules 377
Getting ready 378
How to do it… 378
How it works… 383
Mixing fall-down and OOP coding 384
Getting ready 384
How to do it… 384
How it works… 388
Using a code naming convention 388
Getting ready 389
How to do it… 389
How it works… 391
When not to use OOP 392
Getting ready 392
How to do it… 392
How it works… 396
How to use design patterns successfully 396
Getting ready 396
How to do it… 396
How it works… 399
Avoiding complexity 399
Getting ready 399
How to do it… 400

[x]
How it works… 404
GUI design using multiple notebooks 405
Getting ready 405
How to do it… 405
How it works… 409
Index 413

[ xi ]
Preface
In the second edition of this book, we will explore the beautiful world of graphical user
interfaces (GUIs) using the Python programming language. We will be using the latest
version of Python 3. All of the recipes from the First Edition are included in this edition. We
have added a few new recipes to the Second Edition, which you might not easily find via a
Google search. I think these new recipes will be useful and interesting to the reader.

This is a programming cookbook. Every chapter is self-contained and explains a certain


programming solution. We will start very simply, yet throughout this book we will build a
working application written in Python 3. Each recipe will extend building this application.
Along the way, we will talk to networks, queues, databases, the OpenGL graphical library,
and many more technologies. We will apply design patterns and use best practices.

The book assumes that the reader has some experience using the Python programming
language, but that is not really required to successfully use this book. This book can also be
used as an introduction to the Python programming language, if, and only if, you are
dedicated in your desire to become a Pythonic programmer.

If you are an experienced developer in any other language, you will have a fun time
extending your professional toolbox by adding writing GUIs using Python to your toolbox.
Are you ready?

Let's start on our journey…

What this book covers


Chapter 1, Creating the GUI Form and Adding Widgets, explains how to develop our first GUI
in Python. We will start with the minimum code required to build a running GUI
application. Each recipe then adds different widgets to the GUI form.

Chapter 2, Layout Management, explores how to arrange widgets to create our Python GUI.
The grid layout manager is one of the most important layout tools built into tkinter that we
will be using.

Chapter 3, Look and Feel Customization, shows several examples of how to create a good look
and feel GUI. On a practical level, we will add functionality to the Help | About menu item
we created in one of the recipes.
Preface

Chapter 4, Data and Classes, discusses saving the data our GUI displays. We will start using
object-oriented programming (OOP) in order to extend Python's built-in functionality.

Chapter 5, Matplotlib Charts, explains how to create beautiful charts that visually represent
data. Depending upon the format of the data source, we can plot one or several columns of
data within the same chart.

Chapter 6, Threads and Networking, explains how to extend the functionality of our Python
GUI using threads, queues, and network connections. This will show us that our GUI is not
limited at all to the local scope of our PC.

Chapter 7, Storing Data in Our MySQL Database via Our GUI, shows us how to connect to a
MySQL database server. The first recipe in this chapter will show how to install the free
MySQL Server Community Edition, and in the following recipes we will create databases,
tables, and then load data into those tables as well as modify these data. We will also read
the data back out from the MySQL server into our GUI.

Chapter 8, Internationalization and Testing, shows how to internationalize our GUI by


displaying text on labels, buttons, tabs, and other widgets in different languages. We will
start simple and then explore how we can prepare our GUI for internationalization at the
design level. We will also explore several ways to automatically test our GUI using Python's
built-in unit testing framework.

Chapter 9, Extending Our GUI with the wxPython Library, introduces another Python GUI
toolkit that currently does not ship with Python. It is called wxPython, and we will be using
the Phoenix version of wxPython, which was designed to work well with Python 3.

Chapter 10, Creating Amazing 3D GUIs with PyOpenGL and PyGLet, shows how to transform
our GUI by giving it true three-dimensional capabilities. We will use two Python third-
party packages. PyOpenGL is a Python binding to the OpenGL standard, which is a
graphics library that comes built-in with all major operating systems. This gives the
resulting widgets a native look and feel. PyGLet is another such binding that we will
explore in this chapter. We will also show some code that directly uses the PyOpenGL
library. This is a low-level approach that might open some doors for the interested reader.

Chapter 11, Best Practices, explores different best practices that can help us to build our GUI
in an efficient way and keep it both maintainable and extendible. Best practices are
applicable to any good code, and our GUI is no exception to designing and implementing
good software practices.

[2]
Preface

What you need for this book


All required software for this book is available online and is free of charge. This starts with
Python 3 itself, and then extends to Python's add-on modules. In order to download any
required software, you will need a working Internet connection.

Who this book is for


This book is for programmers who wish to create a GUI. You might be surprised by what
we can achieve by creating beautiful, functional, and powerful GUIs using the Python
programming language. Python is a wonderful, intuitive programming language, and is
very easy to learn.

I invite you to start on this journey now. It will be a lot of fun!

Conventions
In this book, you will find a number of styles of text that distinguish between different
kinds of information. Here are some examples of these styles, and an explanation of their
meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, and user input are shown as follows: "Using Python, we can create our own
classes using the class keyword instead of the def keyword."

A block of code is set as follows:


import tkinter as tk
win = tk.Tk()
win.title("Python GUI")
win.mainloop()

Any command-line input or output is written as follows:


pip install numpy-1.9.2+mkl-cp36-none-win_amd64.whl

New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "Next, we will add
functionality to the menu items, for example, closing the main window by clicking the Exit
menu item and displaying a Help | About dialog."

[3]
Preface

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book-what you liked or disliked. Reader feedback is important for us as it helps us develop
titles that you will really get the most out of.

To send us general feedback, simply e-mail feedback@packtpub.com, and mention the


book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.

Downloading the example code


You can download the example code files for this book from your account at http://www.p
acktpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.c
om/supportand register to have the files e-mailed directly to you.

You can download the code files by following these steps:

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.

[4]
Preface

6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR / 7-Zip for Windows


Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPubl
ishing/Python-GUI-Programming-Cookbook-Second-Edition. We also have other code
bundles from our rich catalog of books and videos available at https://github.com/Packt
Publishing/. Check them out!

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/diagrams used
in this book. The color images will help you better understand the changes in the output.
You can download this file from
https://www.packtpub.com/sites/default/files/downloads/PythonGUIProgrammingCook
bookSecondEdition_ColorImages.pdf.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-
we would be grateful if you could report this to us. By doing so, you can save other readers
from frustration and help us improve subsequent versions of this book. If you find any
errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting
your book, clicking on the Errata Submission Form link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata will
be uploaded to our website or added to any list of existing errata under the Errata section of
that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/conten


t/supportand enter the name of the book in the search field. The required information will
appear under the Errata section.

[5]
Preface

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come
across any illegal copies of our works in any form on the Internet, please provide us with
the location address or website name immediately so that we can pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected pirated


material.

We appreciate your help in protecting our authors and our ability to bring you valuable
content.

Questions
If you have a problem with any aspect of this book, you can contact us
at questions@packtpub.com, and we will do our best to address the problem.

[6]
Creating the GUI Form and
1
Adding Widgets
In this chapter, we start creating amazing GUIs using Python 3.6 and above. We will cover
the following topics:

Creating our first Python GUI


Preventing the GUI from being resized
Adding a label to the GUI form
Creating buttons and changing their text property
Text box widgets
Setting the focus to a widget and disabling widgets
Combo box widgets
Creating a check button with different initial states
Using radio button widgets
Using scrolled text widgets
Adding several widgets in a loop

Introduction
In this chapter, we will develop our first GUI in Python. We will start with the minimum
code required to build a running GUI application. Each recipe then adds different widgets
to the GUI form.
Creating the GUI Form and Adding Widgets

In the first two recipes, we will show the entire code, consisting of only a few lines of code.
In the following recipes, we will only show the code to be added to the previous recipes.

By the end of this chapter, we will have created a working GUI application that consists of
labels, buttons, text boxes, combo boxes, check buttons in various states, as well as radio
buttons that change the background color of the GUI.

At the beginning of each chapter, I will show the Python modules that belong to each
chapter. I will then reference the different modules that belong to the code shown, studied
and run.

Here is the overview of Python modules (ending in a .py extension) for this chapter:

[8]
Creating the GUI Form and Adding Widgets

Creating our first Python GUI


Python is a very powerful programming language. It ships with the built-in tkinter
module. In only a few lines of code (four, to be precise) we can build our first Python GUI.

Getting ready
To follow this recipe, a working Python development environment is a prerequisite. The
IDLE GUI, which ships with Python, is enough to start. IDLE was built using tkinter!

All the recipes in this book were developed using Python 3.6 on
a Windows 10 64-bit OS. They have not been tested on any other
configuration. As Python is a cross-platform language, the code
from each recipe is expected to run everywhere.
If you are using a Mac, it does come with built-in Python, yet it
might be missing some modules such as tkinter, which we will
use throughout this book.
We are using Python 3.6, and the creator of Python intentionally
chose not to make it backwards compatible with Python 2. If
you are using a Mac or Python 2, you might have to install
Python 3.6 from www.python.org in order to successfully run the
recipes in this book.
If you really wish to run the code in this book on Python 2.7,
you will have to make some adjustments. For example, tkinter
in Python 2.x has an uppercase T. The Python 2.7 print
statement is a function in Python 3.6 and requires parentheses.
While the EOL (End Of Life) for the Python 2.x branch has been
extended to the year 2020, I would strongly recommend that
you start using Python 3.6 and above.
Why hold on to the past, unless you really have to?
Here is a link to the Python Enhancement Proposal (PEP) 373
that refers to the EOL of Python 2: https://www.python.org/d
ev/peps/pep-0373/

[9]
Exploring the Variety of Random
Documents with Different Content
protest and the most promising form of revolutionary action consist in
giving the oppressed, the disinherited, and all who are conscious of a
demand for justice, as much truth as they can receive, trusting that it will
direct their energies in the great work of the regeneration of society.

Hence the terms of the first announcement of the Modern School that was
issued to the public. It ran as follows:—

Programme.

The mission of the Modern School is to secure that the boys and girls who are
entrusted to it shall become well-instructed, truthful, just, and free from all
prejudice.

To that end the rational method of the natural sciences will be substituted for
the old dogmatic teaching. It will stimulate, develop, and direct the natural
ability of each pupil, so that he or she will not only become a useful member of
society, with his individual value fully developed, but will contribute, as a
necessary consequence, to the uplifting of the whole community.

It will instruct the young in sound social duties, in conformity with the just
principle that “there are no duties without rights, and no rights without duties.”

In view of the good results that have been obtained abroad by mixed education,
and especially in order to realise the great aim of the Modern School—the
[16]formation of an entirely fraternal body of men and women, without
distinction of sex or class—children of both sexes, from the age of five upward,
will be received.

For the further development of its work, the Modern School will be opened on
Sunday mornings, when there will be classes on the sufferings of mankind
throughout the course of history, and on the men and women who have
distinguished themselves in science, art, or the fight for progress. The parents
of the children may attend these classes.

In the hope that the intellectual work of the Modern School will be fruitful, we
have, besides securing hygienic conditions in the institution and its
dependencies, arranged to have a medical inspection of children at their
entrance into the school. The result of this will be communicated to the parents
if it is deemed necessary; and others will be held periodically, in order to
prevent the spread of contagious diseases during the school hours.
During the week which preceded the opening of the Modern School I
invited the representatives of the press to visit the institution and make it
known, and some of the journals inserted appreciative notices of the
work. It may be of historical interest to quote a few paragraphs from El
Diluvio:—

The future is budding in the school. To build on any other foundation is to build
on sand. Unhappily, the school may serve either the purposes of tyranny or the
cause of liberty, and may thus serve either barbarism or civilisation.

We are therefore pleased to see certain patriots and humanitarians, who grasp
the transcendent importance of this social function, which our Government
[17]systematically overlooks, hasten to meet this pressing need by founding a
Modern School; a school which will not seek to promote the interests of sect
and to move in the old ruts, as has been done hitherto, but will create an
intellectual environment in which the new generation will absorb the ideas and
the impulses which the stream of progress unceasingly brings.

This end can only be attained by private enterprise. Our existing institutions,
tainted with all the vices of the past and weakened by all the trivialities of the
present, cannot discharge this useful function. It is reserved for men of noble
mind and unselfish feeling to open up the new path by which succeeding
generations will rise to higher destinies.

This has been done, or will be done, by the founders of the modest Modern
School which we have visited at the courteous invitation of its directors and
those who are interested in its development. This school is not a commercial
enterprise, like most scholastic institutions, but a pædagogical experiment, of
which only one other specimen exists in Spain (the Free Institution of Education
at Madrid).

Sr. Salas Antón brilliantly expounded the programme of the school to the small
audience of journalists and others who attended the modest opening-festival,
and descanted on the design of educating children in the whole truth and
nothing but the truth, or what is proved to be such. His chief theme was that
the founders do not propose to add one more to the number of what are known
as “Lay Schools,” with their impassioned dogmatism, but a serene observatory,
open to the four winds of heaven, with no cloud darkening the horizon and
interposing between the light and the mind of man.

[18]
Mlle. Meunier died, leaving about £30,000 unconditionally to Ferrer, before he
1
returned to Spain in 1900.—J. M. ↑

[Contents]
Chapter IV.
THE EARLY PROGRAMME
The time had come to think of the inauguration of the Modern School.
Some time previously I had invited a number of gentlemen of great
distinction and of progressive sentiments to assist me with their advice
and form a kind of Committee of Consultation. My intercourse with them
at Barcelona was of great value to me, and many of them remained in
permanent relation with me, for which I may express my gratitude. They
were of opinion that the Modern School should be opened with some
display—invitation-cards, a circular to the press, a large hall, music, and
oratorical addresses by distinguished Liberal politicians. It would have
been easy to do this, and we would have attracted an audience of
hundreds of people who would have applauded with that momentary
enthusiasm which characterises our public functions. But I was not
seduced by the idea. As a Positivist and an idealist I was convinced that a
simple modesty best befitted the inauguration of a work of reform. Any
other method seemed to me disingenuous, a concession to enervating
conventions and to the very evil which I was setting out to reform. The
proposal of the Committee was, therefore, repugnant [19]to my conscience
and my sentiments, and I was, in that and all other things relating to the
Modern School, the executive power.

In the first number of the Bulletin of the Modern School, issued on


October 30, 1901, I gave a general exposition of the fundamental
principles of the School, which I may repeat here:—

Those imaginary products of the mind, a priori ideas, and all the absurd and
fantastical fictions hitherto regarded as truth and imposed as directive principles
of human conduct, have for some time past incurred the condemnation of
reason and the resentment of conscience. The sun no longer merely touches the
tips of the mountains; it floods the valleys, and we enjoy the light of noon.
Science is no longer the patrimony of a small group of privileged individuals; its
beneficent rays more or less consciously penetrate every rank of society. On all
sides traditional errors are being dispelled by it; by the confident procedure of
experience and observation it enables us to attain accurate knowledge and
criteria in regard to natural objects and the laws which govern them. With
indisputable authority it bids men lay aside for ever their exclusivisms and
privileges, and it offers itself as the controlling principle of human life, seeking
to imbue all with a common sentiment of humanity.

Relying on modest resources, but with a robust and rational faith and a spirit
that will not easily be intimidated, whatever obstacles arise in our path, we have
founded the Modern School. Its aim is to convey, without concession to
traditional methods, an education based on the natural sciences. This new
method, though the only sound and positive [20]method, has spread throughout
the civilised world, and has innumerable supporters of intellectual distinction
and lofty principles.

We are aware how many enemies there are about us. We are conscious of the
innumerable prejudices which oppress the social conscience of our country. This
is the outcome of a medieval, subjective, dogmatic education, which makes
ridiculous pretensions to the possession of an infallible criterion. We are further
aware that, in virtue of the law of heredity, strengthened by the influences of
the environment, the tendencies which are connatural and spontaneous in the
young child are still more pronounced in adolescence. The struggle will be
severe, the work difficult; but with a constant and unwavering will, the sole
providence of the moral world, we are confident that we will win the victory to
which we aspire. We will develop living brains, capable of reacting on our
instruction. We will take care that the minds of our pupils will sustain, when
they leave the control of their teachers, a stern hostility to prejudice; that they
will be solid minds, capable of forming their own rational convictions on every
subject.

This does not mean that we will leave the child, at the very outset of its
education, to form its own ideas. The Socratic procedure is wrong, if it is taken
too literally. The very constitution of the mind, at the commencement of its
development, demands that at this stage the child shall be receptive. The
teacher must implant the germs of ideas. These will, when age and strength
invigorate the brain, bring forth corresponding flowers and fruit, in accordance
with the degree of initiative and the characteristic features of the pupil’s mind.
[21]

On the other hand, we may say that we regard as absurd the widespread notion
that an education based on natural science stunts the organ of the idealist
faculty. We are convinced that the contrary is true. What science does is to
correct and direct it, and give it a wholesome sense of reality. The work of
man’s cerebral energy is to create the ideal, with the aid of art and philosophy.
But in order that the ideal shall not degenerate into fables, or mystic and
unsubstantial dreams, and the structure be not built on sand, it is absolutely
necessary to give it a secure and unshakable foundation in the exact and
positive teaching of the natural sciences.

Moreover, the education of a man does not consist merely in the training of his
intelligence, without having regard to the heart and the will. Man is a complete
and unified whole, in spite of the variety of his functions. He presents various
facets, but is at the bottom a single energy, which sees, loves, and applies a will
to the prosecution of what he has conceived or affected. It is a morbid
condition, an infringement of the laws of the human organism, to establish an
abyss where there ought to be a sane and harmonious continuity. The divorce
between thought and will is an unhappy feature of our time. To what fatal
consequences it has led! We need only refer to our political leaders and to the
various orders of social life; they are deeply infected with this pernicious
dualism. Many of them are assuredly powerful enough in respect of their mental
faculties, and have an abundance of ideas; but they lack a sound orientation
and the fine thoughts which science applies to the life of individuals and of
peoples. Their restless egoism and the wish to [22]accommodate their relatives,
together with their leaven of traditional sentiments, form an impermeable
barrier round their hearts and prevent the infiltration of progressive ideas and
the formation of that sap of sentiment which is the impelling and determining
power in the conduct of man. Hence the attempt to obstruct progress and put
obstacles in the way of new ideas; hence, as a result of these attempts, the
scepticism of multitudes, the death of nations, and the inevitable despair of the
oppressed.

We regard it as one of the first principles of our pædagogical mission that there
is no such duality of character in any individual—one which sees and appreciates
truth and goodness, and one which follows evil. And, since we take natural
science as our guide in education, a further consequence will be recognised; we
shall endeavour to secure that the intellectual impressions which science
conveys to the pupil shall be converted into the sap of sentiment and shall be
intensely loved. When sentiment is strong it penetrates and diffuses itself
through the deepest recesses of a man’s being, pervading and giving a special
colour to his character.

And as a man’s conduct must revolve within the circle of his character, it follows
that a youth educated in the manner we have indicated will, when he comes to
rule himself, recognise science as the one helpful master of his life.

The school was opened on September 8, 1901, with thirty pupils—twelve


girls and eighteen boys. These sufficed for the purpose of our experiment,
and we had no intention of increasing the number for a time, [23]so that
we might keep a more effective watch on the pupils. The enemies of the
new school would take the first opportunity to criticise our work in co-
educating boys and girls.

The people present at the opening were partly attracted by the notices of
our work published in the press, and partly consisted of the parents of the
pupils and delegates of various working-class societies who had been
invited on account of their assistance to me. I was supported in the chair
by the teachers and the Committee of Consultation, two of whom
expounded the system and aim of the school. In this quiet fashion we
inaugurated a work that was destined to last. We created the Modern,
Scientific, and Rational School, the fame of which soon spread in Europe
and America. Time may witness a change of its name—the “Modern”
School—but the description “scientific and rational” will be more and more
fully vindicated. [24]

[Contents]
Chapter V.
THE CO-EDUCATION OF THE SEXES
The most important point in our programme of rational education, in view
of the intellectual condition of the country, and the feature which was
most likely to shock current prejudices and habits, was the co-education
of boys and girls.

The idea was not absolutely new in Spain. As a result of necessity and of
primitive conditions, there were villages in remote valleys and on the
mountains where some good-natured neighbour, or the priest or sacristan,
used to teach the catechism, and sometimes elementary letters, to boys
and girls in common. In fact, it is sometimes legally authorised, or at least
tolerated, by the State among small populations which have not the
means to pay both a master and mistress. In such cases, either a master
or mistress gives common lessons to boys and girls, as I had myself seen
in a village not far from Barcelona. In towns and cities, however, mixed
education was not recognised. One read sometimes of the occurrence of it
in foreign countries, but no one proposed to adopt it in Spain, where such
a proposal would have been deemed an innovation of the most utopian
character.

Knowing this, I refrained from making any public [25]propaganda on the


subject, and confined myself to private discussion with individuals. We
asked every parent who wished to send a boy to the school if there were
girls in the family, and it was necessary to explain to each the reasons for
co-education. Wherever we did this, the result was satisfactory. If we had
announced our intention publicly, it would have raised a storm of
prejudice. There would have been a discussion in the press, conventional
feeling would have been aroused, and the fear of “what people would
say”—that paralysing obstacle to good intentions—would have been
stronger than reason. Our project would have proved exceedingly difficult,
if not impossible. Whereas, proceeding as we did, we were able to open
with a sufficient number of boys and girls, and the number steadily
increased, as the Bulletin of the school shows.
In my own mind, co-education was of vital importance. It was not merely
an indispensable condition of realising what I regard as the ideal result of
rational education; it was the ideal itself, initiating its life in the Modern
School, developing progressively without any form of exclusion, inspiring a
confidence of attaining our end. Natural science, philosophy, and history
unite in teaching, in face of all prejudice to the contrary, that man and
woman are two complementary aspects of human nature, and the failure
to recognise this essential and important truth has had the most
disastrous consequences.

In the second number of the Bulletin, therefore, I published a careful


vindication of my ideas:— [26]

Mixed education (I said) is spreading among civilised nations. In many places it


has already had excellent results. The principle of this new scheme of education
is that children of both sexes shall receive the same lessons; that their minds
shall be developed, their hearts purified, and their wills strengthened in
precisely the same manner; that the sexes shall be in touch with each other
from infancy, so that woman shall be, not in name only, but in reality and truth,
the companion of man.

A venerable institution which dominates the thoughts of our people declares, at


one of the most solemn moments of life, when, with ceremonious pomp, man
and woman are united in matrimony, that woman is the companion of man.
These are hollow words, void of sense, without vital and rational significance in
life, since what we witness in the Christian Church, in Catholicism particularly, is
the exact opposite of this idea. Not long ago a Christian woman of fine feeling
and great sincerity complained bitterly of the moral debasement which is put
upon her sex in the bosom of the Church: “It would be impious audacity for a
woman to aspire in the Church even to the position of the lowest sacristan.”

A man must suffer from ophthalmia of the mind not to see that, under the
inspiration of Christianity, the position of woman is no better than it was under
the ancient civilisations; it is, indeed, worse, and has aggravating circumstances.
It is a conspicuous fact in our modern Christian society that, as a result and
culmination of our patriarchal development, the woman does not belong to
herself; she is neither more nor less than an adjunct of man, subject constantly
to his absolute dominion, bound to him—it may be—by chains of gold. Man has
made her [27]a perpetual minor. Once this was done, she was bound to
experience one of two alternatives: man either oppresses and silences her, or
treats her as a child to be coaxed—according to the mood of the master. If at
length we note in her some sign of the new spirit, if she begins to assert her will
and claim some share of independence, if she is passing, with irritating
slowness, from the state of slave to the condition of a respected ward, she owes
it to the redeeming spirit of science, which is dominating the customs of races
and the designs of our social rulers.

The work of man for the greater happiness of the race has hitherto been
defective; in future it must be a joint action of the sexes; it is incumbent
on both man and woman, according to the point of view of each. It is
important to realise that, in face of the purposes of life, man is neither
inferior nor (as we affect to think) superior to woman. They have different
qualities, and no comparison is possible between diverse things.

As many psychologists and sociologists observe, the human race displays


two fundamental aspects. Man typifies the dominion of thought and of the
progressive spirit; woman bears in her moral nature the characteristic
note of intense sentiment and of the conservative spirit. But this view of
the sexes gives no encouragement whatever to the ideas of reactionaries.
If the predominance of the conservative element and of the emotions is
ensured in woman by natural law, this does not make her the less fitted to
be the companion of man. She is not prevented by [28]the constitution of
her nature from reflecting on things of importance, nor is it necessary that
she should use her mind in contradiction to the teaching of science and
absorb all kinds of superstitions and fables. The possession of a
conservative disposition does not imply that one is bound to crystallise in
a certain stage of thought, or that one must be obsessed with prejudice in
all that relates to reality.

“To conserve” merely means “to retain,” to keep what has been given us,
or what we have ourselves produced. The author of The Religion of the
Future says, referring to woman in this respect: “The conservative spirit
may be applied to truth as well as to error; it all depends what it is you
conserve. If woman is instructed in philosophical and scientific matters,
her conservative power will be to the advantage, not to the disadvantage,
of progressive thought.”
On the other hand, it is pointed out that woman is emotional. She does
not selfishly keep to herself what she receives; she spreads abroad her
beliefs, her ideas, and all the good and evil that form her moral treasures.
She insists on sharing them with all those who are, by the mysterious
power of emotion, identified with her. With exquisite art, with invariable
unconsciousness, her whole moral physiognomy, her whole soul, so to say,
impresses itself on the soul of those she loves.

If the first ideas implanted in the mind of the child by the teacher are
germs of truth and of positive knowledge; if the teacher himself is in
touch with the scientific spirit of the time, the result will be good [29]from
every point of view. But if a man be fed in the first stage of his mental
development with fables, errors, and all that is contrary to the spirit of
science, what can be expected of his future? When the boy becomes a
man he will be an obstacle to progress. The human conscience is in
infancy of the same natural texture as the bodily organism; it is tender
and pliant. It readily accepts what comes to it from without. In the course
of time this plasticity gives place to rigidity; it loses its pliancy and
becomes relatively fixed. From that time the ideas communicated to it by
the mother will be encrusted and identified with the youth’s conscience.

The acid of the more rational ideas which the youth acquires by social
intercourse or private study may in cases relieve the mind of the
erroneous ideas implanted in childhood. But what is likely to be the
practical outcome of this transformation of the mind in the sphere of
conduct? We must not forget that in most cases the emotions associated
with the early ideas remain in the deeper folds of the heart. Hence it is
that we find in so many men such a flagrant and lamentable antithesis
between the thought and the deed, the intelligence and the will; and this
often leads to an eclipse of good conduct and a paralysis of progress.

This primary sediment which we owe to our mothers is so tenacious and


enduring—it passes so intimately into the very marrow of our being—that
even energetic characters, which have effected a sincere reform of mind
and will, have the mortification of discovering [30]this Jesuitical element,
derived from their mothers, when they turn to make an inventory of their
ideas.

Woman must not be restricted to the home. The sphere of her activity
must go out far beyond her home: it must extend to the very confines of
society. But in order to ensure a helpful result from her activity we must
not restrict the amount of knowledge we communicate to her; she must
learn, both in regard to quantity and quality, the same things as man.
When science enters the mind of woman it will direct her rich vein of
emotion, the characteristic element of her nature, the glad harbinger of
peace and happiness among men.

It has been said that woman represents continuity, and man represents
change: man is the individual, woman is the species. Change, however,
would be useless, fugitive, and inconstant, with no solid foundation of
reality, if the work of woman did not strengthen and consolidate the
achievements of man. The individual, as such, is the flower of a day, a
thing of ephemeral significance in life. Woman, who represents the
species, has the function of retaining within the species the elements
which improve its life, and to discharge this function adequately she needs
scientific instruction.

Humanity will advance more rapidly and confidently in the path of


progress and increase its resources a hundredfold if it combines the ideas
acquired by science with the emotional strength of woman. Ribot observes
that an idea is merely an idea, an act of [31]intelligence, incapable of
producing or doing anything, unless it is accompanied by an emotional
state, a motive element. Hence it is conceived as a scientific truth that, to
the advantage of progress, an idea does not long remain in a purely
contemplative condition when it appears. This is obviated by associating
the idea with emotion and love, which do not fail to convert it into vital
action.

When will all this be accomplished? When shall we see the marriage of
ideas with the impassioned heart of woman? From that date we shall have
a moral matriarchate among civilised nations. Then, on the one hand,
humanity, considered in the home circle, will have the proper teacher to
direct the new generations in the sense of the ideal; and, on the other
hand, it will have an apostle and enthusiastic propagandist who will
impress the value of liberty on the minds of men and the need of co-
operation upon the peoples of the world. [32]

[Contents]
Chapter VI.
CO-EDUCATION OF THE SOCIAL CLASSES
There must be a co-education of the different social classes as well as of
the two sexes. I might have founded a school giving lessons gratuitously;
but a school for poor children only would not be a rational school, since, if
they were not taught submission and credulity as in the old type of
school, they would have been strongly disposed to rebel, and would
instinctively cherish sentiments of hatred.

There is no escape from the dilemma. There is no middle term in the


school for the disinherited class alone; you have either a systematic
insistence, by means of false teaching, on error and ignorance, or hatred
of those who domineer and exploit. It is a delicate point, and needs
stating clearly. Rebellion against oppression is merely a question of statics,
of equilibrium. Between one man and another who are perfectly equal, as
is said in the immortal first clause of the famous Declaration of the French
Revolution (“Men are born and remain free and equal in rights”), there
can be no social inequality. If there is such inequality, some will tyrannise,
the others protest and hate. Rebellion is a levelling tendency, and to that
extent natural and rational, however much it may be [33]discredited by
justice and its evil companions, law and religion.

I venture to say quite plainly: the oppressed and the exploited have a
right to rebel, because they have to reclaim their rights until they enjoy
their full share in the common patrimony. The Modern School, however,
has to deal with children, whom it prepares by instruction for the state of
manhood, and it must not anticipate the cravings and hatreds, the
adhesions and rebellions, which may be fitting sentiments in the adult. In
other words, it must not seek to gather fruit until it has been produced by
cultivation, nor must it attempt to implant a sense of responsibility until it
has equipped the conscience with the fundamental conditions of such
responsibility. Let it teach the children to be men; when they are men,
they may declare themselves rebels against injustice.
It needs very little reflection to see that a school for rich children only
cannot be a rational school. From the very nature of things it will tend to
insist on the maintenance of privilege and the securing of their
advantages. The only sound and enlightened form of school is that which
co-educates the poor and the rich, which brings the one class into touch
with the other in the innocent equality of childhood, by means of the
systematic equality of the rational school.

With this end in view I decided to secure pupils of every social rank and
include them in a common class, adopting a system accommodated to the
circumstances [34]of the parents or guardians of the children; I would not
have a fixed and invariable fee, but a kind of sliding scale, with free
lessons for some and different charges for others. I later published the
following article on the subject in the Bulletin (May 10, 1905):—

Our friend D. R. C. gave a lecture last Sunday at the Republican Club on the
subject of “Modern Pædagogy,” explaining to his audience what we mean by
modern education and what advantages society may derive from it. As I think
that the subject is one of very great interest and most proper to receive public
attention, I offer the following reflections and considerations on it. It seems to
me that the lecturer was happy in his exposition of the ideal, but not in the
suggestions he made with a view to realising it, nor in bringing forward the
schools of France and Belgium as models to be imitated.

Señor C., in fact, relies upon the State, upon Parliament or municipalities, for the
building, equipment, and management of scholastic institutions. This seems to
me a great mistake. If modern pædagogy means an effort towards the
realisation of a new and more just form of society; if it means that we propose
to instruct the rising generation in the causes which have brought about and
maintain the lack of social equilibrium; if it means that we are anxious to
prepare the race for better days, freeing it from religious fiction and from all
idea of submission to an inevitable socio-economic inequality; we cannot entrust
it to the State nor to other official organisms which necessarily maintain existing
privileges and support the laws which at present consecrate the exploitation of
[35]one man by another, the pernicious source of the worst abuses.

Evidence of the truth of this is so abundant that any person can obtain it by
visiting the factories and workshops and other centres of paid workers, by
inquiring what is the manner of life of those in the higher and those in the lower
social rank, by frequenting what are called courts of justice, and by asking the
prisoners in our penal institutions what were the motives for their misconduct. If
all this does not suffice to prove that the State favours those who are in
possession of wealth and frowns on those who rebel against injustice, it may be
useful to notice what has happened in Belgium. Here, according to Señor C., the
government is so attentive to education and conducts it so excellently that
private schools are impossible. In the official schools, he says, the children of
the rich mingle with the children of the poor, and one may at times see the child
of wealthy parents arm in arm with a poor and lowly companion. It is true, I
admit, that children of all classes may attend the Belgian schools; but the
instruction that is given in them is based on the supposed eternal necessity for a
division of rich and poor, and on the principle that social harmony consists in the
fulfilment of the laws.

It is natural enough that the masters should like to see this kind of education
given on every side. It is a means of bringing to reason those who might one
day be tempted to rebel. Not long ago, in Brussels and other Belgian towns, the
sons of the rich, armed and organised in national troops, shot down the sons of
the poor who were claiming universal suffrage. On the other hand, my
acquaintance with the quality of Belgian education differs [36]considerably from
that of the lecturer. I have before me various issues of a Belgian journal
(L’Exprèss de Liège) which devotes an article to the subject, entitled “The
Destruction of our National System of Education.” The facts given are,
unfortunately, very similar to the facts about education in Spain, though in this
country there has been a great development of education by religious orders,
which is, as everybody knows, the systematisation of ignorance. In fine, it is not
for nothing that a violently clerical government rules in Belgium.

As to the modern education which is given in French schools, we may say that
not a single one of the books used in them serves the purpose of a really
secular education. On the very day on which Señor C. was lecturing in Gracia
the Parisian journal L’Action published an article, with the title “How Secular
Morality is Taught,” in regard to the book Recueil de maximes et pensées
morales, and quoted from it certain ridiculously anachronistic ideas which offend
the most elementary common sense.

We shall be asked, What are we to do if we cannot rely on the aid of the State,
of Parliament, or municipalities? We must appeal to those whose interest it is to
bring about a reform; to the workers, in the first place, then to the cultivated
and privileged people who cherish sentiments of justice. They may not be
numerous, but there are such. I am personally acquainted with several. The
lecturer complained that the civic authorities were so dilatory in granting the
reforms that are needed. I feel sure that he would do better not to waste his
time on them, but appeal directly to the working class. [37]
The field has been well prepared. Let him visit the various working men’s
societies, the Republican Fraternities, the Centres of Instruction, the Workers’
Athenæums, and all the bodies which are working for reform, 1 and let him give
ear to the language of truth, the exhortations to union and courage. Let him
observe the attention given to the problem of rational and scientific instruction,
a kind of instruction which shows the injustice of privilege and the possibility of
reforms. If individuals and societies continue thus to combine their endeavours
to secure the emancipation of those who suffer—for it is not the workers only
who suffer—Señor C. may rest assured of a positive, sound, and speedy result,
while whatever may be obtained of the government will be dilatory, and will
tend only to stupefy, to confuse ideas, and to perpetuate the domination of one
class over another.

[38]

These societies are particularly numerous in Spain, where the government system of
1
education is deplorable, and schools are often established in connection with them.—J.
M. ↑

[Contents]
Chapter VII.
SCHOOL HYGIENE
In regard to hygiene we are, in Spain, dominated by the abominable ideas
of the Catholic Church. Saint Aloysius and Saint Benedict J. Labré are not
the only, or the most characteristic, saints in the list of the supposed
citizens of the kingdom of heaven, but they are the most popular with the
masters of uncleanliness. With such types of perfection, 1 in an
atmosphere of ignorance, cleverly and maliciously sustained by the clergy
and the middle-class Liberals, it was to be expected that the children who
would come to our school would be wanting in cleanliness; dirt is
traditional in their world.

We began a discreet and systematic campaign against it, showing the


children how a dirty person or object inspires repugnance, and how
cleanliness attracts esteem and sympathy; how one instinctively moves
towards the cleanly person and away from the dirty and malodorous; and
how we should be pleased to win the regard of those who see us and
ashamed to excite their disgust.

We then explained cleanliness as an aspect of [39]beauty, and


uncleanliness as a part of ugliness; and we at length entered expressly
into the province of hygiene, pointing out that dirt was a cause of disease
and a constant possible source of infection and epidemic, while cleanliness
was one of the chief conditions of health. We thus soon succeeded in
disposing the children in favour of cleanliness, and making them
understand the scientific principles of hygiene.

The influence of these lessons spread to their families, as the new


demands of the children disturbed traditional habits. One child would ask
urgently for its feet to be washed, another would ask to be bathed,
another wanted a brush and powder for its teeth, another new clothes or
boots, and so on. The poor mothers, burdened with their daily tasks,
sometimes crushed by the hardness of the circumstances in which their
life was passed, and probably under the influence of religious teaching,
endeavoured to stop their petitions; but in the end the new life introduced
into the home by the child triumphed, a welcome presage of the
regeneration which rational education will one day accomplish.

I entrusted the expounding of the principles of scholastic hygiene to


competent men, and Dr. Martínez Vargas and others wrote able and
detailed articles on the subject in the Bulletin. Other articles were written
on the subject of games and play, on the lines of modern pædagogy. 2 [40]

It is especially commended in the life of Benedict J. Labré and others that they
1
deliberately cultivated filthiness of person.—J. M. ↑
These articles are reproduced in the Spanish edition. As they are not from Ferrer’s
2 pen, I omit them.—J. M. ↑

[Contents]
Chapter VIII.
THE TEACHERS
The choice of teachers was another point of great difficulty. The tracing of
a programme of rational instruction once accomplished, it remained to
choose teachers who were competent to carry it out, and I found that in
fact no such persons existed. We were to illustrate once more that a need
creates its own organs.

Certainly there were plenty of teachers. Teaching, though not very


lucrative, is a profession by which a man can support himself. There is not
a universal truth in the popular proverb which says of an unfortunate
man: “He is hungrier than a schoolmaster.” 1 The truth is that in many
parts of Spain the schoolmaster forms part of the local governing clique,
with the priest, the doctor, the shopkeeper, and the money-lender (who is
often one of the richest men in the place, though he contributes least to
its welfare). The master receives a municipal salary, and has a certain
influence which may at times secure material advantages. In larger towns
the master, if he is not [41]content with his salary, may give lessons in
private schools, where, in accord with the provincial institute, he prepares
young men for the University. Even if he does not obtain a position of
distinction, he lives as well as the generality of his fellow townsmen.

There are, moreover, teachers in what are called “secular schools”—a


name imported from France, where it arose because the schooling was
formerly exclusively clerical and conducted by religious bodies. This is not
the case in Spain; however Christian the teaching is, it is always given by
lay masters. However, the Spanish lay teachers, inspired by sentiments of
freethought and political radicalism, were rather anti-Catholic and anti-
clerical than Rationalist, in the best sense of the word.

Professional teachers have to undergo a special preparation for the task of


imparting scientific and rational instruction. This is difficult in all cases,
and is sometimes rendered impossible by the difficulties caused by habits
of routine. On the other hand, those who had had no pædagogical
experience, and offered themselves for the work out of pure enthusiasm
for the idea, stood in even greater need of preparatory study. The solution
of the problem was very difficult, because there was no other place but
the rational school itself for making this preparation.

The excellence of the system saved us. Once the Modern School had been
established by private initiative, with a firm determination to be guided by
the ideal, the difficulties began to disappear. Every dogmatic imposition
was detected and rejected, [42]every excursion or deviation in the
direction of metaphysics was at once abandoned, and experience
gradually formed a new and salutary pædagogical science. This was due,
not merely to my zeal and vigilance, but to my earliest teachers, and to
some extent to the naive expressions of the pupils themselves. We may
certainly say that if a need creates an organ, the organ speedily meets the
need.

Nevertheless, in order to complete my work, I established a Rationalist


Normal School for the education of teachers, under the direction of an
experienced master and with the co-operation of the teachers in the
Modern School. In this a number of young people of both sexes were
trained, and they worked excellently until the despotic authorities, yielding
to our obscure and powerful enemies, put a stop to our work, and
flattered themselves that they had destroyed it for ever. [43]

£20 a year is a not uncommon salary of masters and mistresses in Spain, and many
1
cannot obtain even that.—J. M. ↑

[Contents]
Chapter IX.
THE REFORM OF THE SCHOOL
There are two ways open to those who seek to reform the education of
children. They may seek to transform the school by studying the child and
proving scientifically that the actual scheme of instruction is defective, and
must be modified; or they may found new schools in which principles may
be directly applied in the service of that ideal which is formed by all who
reject the conventions, the cruelty, the trickery, and the untruth which
enter into the bases of modern society.

The first method offers great advantages, and is in harmony with the
evolutionary conception which men of science regard as the only effective
way of attaining the end. They are right in theory, as we fully admit. It is
evident that the progress of psychology and physiology must lead to
important changes in educational methods; that the teachers, being now
in a better position to understand the child, will make their teaching more
in conformity with natural laws. I further grant that this evolution will
proceed in the direction of greater liberty, as I am convinced that violence
is the method of ignorance, and that the educator who is really worthy of
the name will [44]gain everything by spontaneity; he will know the child’s
needs, and will be able to promote its development by giving it the
greatest possible satisfaction.

In point of fact, however, I do not think that those who are working for
the regeneration of humanity have much to hope from this side. Rulers
have always taken care to control the education of the people; they know
better than any that their power is based entirely on the school, and they
therefore insist on retaining their monopoly of it. The time has gone by
when rulers could oppose the spread of instruction and put limits to the
education of the masses. Such a policy was possible formerly because
economic life was consistent with general ignorance, and this ignorance
facilitated despotism. The circumstances have changed, however. The
progress of science and our repeated discoveries have revolutionised the
conditions of labour and production. It is no longer possible for the people
to remain ignorant; education is absolutely necessary for a nation to
maintain itself and make headway against its economic competitors.
Recognising this, the rulers have sought to give a more and more
complete organisation to the school, not because they look to education
to regenerate society, but because they need more competent workers to
sustain industrial enterprises and enrich their cities. Even the most
reactionary rulers have learned this lesson; they clearly understand that
the old policy was dangerous to the economic life of nations, and [45]that
it was necessary to adapt popular education to the new conditions.

It would be a serious mistake to think that the ruling classes have not
foreseen the danger to themselves of the intellectual development of the
people, and have not understood that it was necessary to change their
methods. In fact, their methods have been adapted to the new conditions
of life; they have sought to gain control of the ideas which are in course
of evolution. They have endeavoured to preserve the beliefs on which
social discipline had been grounded, and to give to the results of scientific
research and the ideas involved in them a meaning which will not be to
the disadvantage of existing institutions; and it is this that has induced
them to assume control of the school. In every country the governing
classes, which formerly left the education of the people to the clergy, as
these were quite willing to educate in a sense of obedience to authority,
have now themselves undertaken the direction of the schools.

The danger to them consists in the stimulation of the human mind by the
new spectacle of life and the possible rise of thoughts of emancipation in
the depths of their hearts. It would have been folly to struggle against the
evolving forces; the effect would be only to inflame them, and, instead of
adhering to earlier methods of government, they would adopt new and
more effective methods. It did not require any extraordinary genius to
discover the solution. The course of events itself suggested to those who
were in power the way in which they were to meet the [46]difficulties
which threatened; they built schools, they sought generously to extend
the sphere of education, and if there were at one point a few who resisted
this impulse—as certain tendencies favoured one or other of the political
parties—all soon understood that it was better to yield, and that the best
policy was to find some new way of defending their interests and
principles. There were then sharp struggles for the control of the schools,
and these struggles continue to-day in every civilised country; sometimes
the republican middle-class triumphs, sometimes the clergy. All parties
appreciate the importance of the issue, and they shrink from no sacrifice
to win the victory. “The school” is the cry of every party. The public good
must be recognised in this zeal. Everybody seeks to raise himself and
improve his condition by education. In former times it might have been
said: “Those people want to keep thee in ignorance in order the better to
exploit thee: we want to see thee educated and free.” That is no longer
possible; schools of all kinds rise on every side.

In regard to this general change of ideas among the governing classes as


to the need of schools, I may state certain reasons for distrusting their
intentions and doubting the efficacy of the means of reform which are
advocated by certain writers. As a rule, these reformers care little about
the social significance of education; they are men who eagerly embrace
scientific truth, but eliminate all that is foreign to the object of their
studies. They are patiently endeavouring [47]to understand the child, and
are eager to know—though their science is young, it must be remembered
—what are the best methods to promote its intellectual development.

This kind of professional indifference is, in my opinion, very prejudicial to


the cause they seek to serve. I do not in the least think them insensible of
the realities of the social world, and I know that they believe that the
public welfare will be greatly furthered by their labours. “Seeking to
penetrate the secrets of the life of man,” they reflect, “and unravelling the
normal process of his physical and psychic development, we shall direct
education into a channel which will be favourable to the liberation of
energy. We are not immediately concerned with the reform of the school,
and indeed we are unable to say exactly what lines it should follow. We
will proceed slowly, knowing that, from the very nature of things, the
reform of the school will result from our research. If you ask us what are
our hopes, we will grant that, like you, we foresee a revolution in the
sense of a placing of the child and humanity under the direction of
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like