Python GUI Programming with Tkinter
eBook - ePub

Python GUI Programming with Tkinter

Alan D. Moore

Condividi libro
  1. 452 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Python GUI Programming with Tkinter

Alan D. Moore

Dettagli del libro
Anteprima del libro
Indice dei contenuti

Informazioni sul libro

Find out how to create visually stunning and feature-rich applications by empowering Python's built-in Tkinter GUI toolkit

Key Features

  • Explore Tkinter's powerful features to easily design and customize your GUI application
  • Learn the basics of 2D and 3D animation in GUI applications.
  • Learn to integrate stunning Data Visualizations using Tkinter Canvas and Matplotlib.

Book Description

Tkinter is a lightweight, portable, and easy-to-use graphical toolkit available in the Python Standard Library, widely used to build Python GUIs due to its simplicity and availability. This book teaches you to design and build graphical user interfaces that are functional, appealing, and user-friendly using the powerful combination of Python and Tkinter.

After being introduced to Tkinter, you will be guided step-by-step through the application development process. Over the course of the book, your application will evolve from a simple data-entry form to a complex data management and visualization tool while maintaining a clean and robust design. In addition to building the GUI, you'll learn how to connect to external databases and network resources, test your code to avoid errors, and maximize performance using asynchronous programming. You'll make the most of Tkinter's cross-platform availability by learning how to maintain compatibility, mimic platform-native look and feel, and build executables for deployment across popular computing platforms.

By the end of this book, you will have the skills and confidence to design and build powerful high-end GUI applications to solve real-world problems.

What you will learn

  • Implement the tools provided by Tkinter to design beautiful GUIs
  • Discover cross-platform development through minor customizations in your existing application
  • Visualize graphs in real time as data comes in using Tkinter's animation capabilities
  • Use PostgreSQL authentication to ensure data security for your application
  • Write unit tests to avoid regressions when updating code

Who this book is for

This book will appeal to developers and programmers who would like to build GUI-based applications. Knowledge of Python is a prerequisite.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Python GUI Programming with Tkinter è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Python GUI Programming with Tkinter di Alan D. Moore in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Ciencia de la computación e Programación en Python. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.



Improving Data Storage with SQL

As weeks have passed by, there is a growing problem at the lab: the CSV files are everywhere! Conflicting copies, missing files, records getting changed by non-data entry staff, and other CSV-related frustrations are plaguing the project. It's clear that individual CSV files are not working out as a way to store data for the experiments. Something better is needed.
The facility has an older Linux server with a PostgreSQL database installed. You've been asked to update your program so that it stores data in the PostgreSQL database rather than in the CSV files. This promises to be a major update to your application!
In this chapter, you'll learn the following topics:
  • Installing and configuring the PostgreSQL database system
  • Structuring data in a database for good performance and reliability
  • The basics of SQL queries
  • Using the psycopg2 library to connect your program to PostgreSQL


PostgreSQL (usually pronounced post-gress) is a free, open source, cross-platform relational database system. It runs as a network service with which you can communicate using client programs or software libraries. At the time of writing, the project has just released version 10.0.
Although ABQ has provided a PostgreSQL server which is already installed and configured, you'll need to download and install the software on your workstation for development purposes.
Shared production resources such as databases and web services should never be used for testing or development. Always set up a separate development copy of these resources on your own workstation or a separate server machine.

Installing and configuring PostgreSQL

To download PostgreSQL, visit Installers are provided for Windows, macOS, and Linux by the EnterpriseDB company, a commercial entity that provides paid support for PostgreSQL. These packages include the server, command-line client, and pgAdmin graphical client all in one package.
To install the software, launch the installer using an account with administrative rights and follow the screens in the installation wizard.
Once installed, launch pgAdmin and create a new admin user for yourself by selecting Object | Create | Login/Group Role. Make sure to visit the Privileges tab to check Superuser, and the Definition tab to set a password. Then, create a database by selecting Object | Create | Database. Make sure to set your user as an owner. To run SQL commands on your database, select your database and click Tools | Query Tool.
MacOS or Linux users who prefer the command line can also use the following these commands:
sudo -u postgres createuser -sP myusername sudo -u postgres createdb -O myusername mydatabasename
psql -d mydatabasename -U myusername
Although Enterprise DB provides binary installers for Linux, most Linux users will prefer to use packages supplied by their distribution. You may end up with a slightly older version of PostgreSQL, but that won't matter for most basic use cases. Be aware that pgAdmin is usually part of a separate package, and that the latest version (pgAdmin 4) may not be available. Regardless, you should have no trouble following this chapter with the older version.

Connecting with psycopg2

To make SQL queries from our application, we'll need to install a Python library that can talk directly to our database. The most popular choice is psycopg2. The psycopg2 library is not a part of the Python standard library. You can find the most current installation instructions at; however, the preferred method is to use pip.
For Windows, macOS, and Linux, the following command should work:
pip install --user psycopg2-binary
If that doesn't work, or if you'd rather install it from the source, check the requirements on the website. The psycopg2 library is written in C, not Python, so it requires a C compiler and a few other development packages. Linux users can usually install psycopg2 from their distribution's package management system. We'll get in-depth with the use of psycopg2 later in the chapter.

SQL and relational database basics

Before we can start using PostgreSQL with Python, you'll need to have at least a basic understanding of SQL. If you already have one, you can skip to the next section; otherwise, brace yourself for a super-short crash course on relational databases and SQL.
For over three decades, relational database systems have remained a de-facto standard for storing business data. They are more commonly known as SQL databases, after the Structured Query Language (SQL) used to interact with them.
SQL databases are made up of tables. A table is something like our CSV file, in that it has rows representing individual items and columns representing data values associated with each item. A SQL table has some important differences from our CSV file. First, each column in the table is assigned a data type which is strictly enforced; just as Python will produce an error when you try to use abcd as an int, a SQL database will complain if you try to insert letters into a numeric or other non-string column. SQL databases typically support data types for text, numbers, dates and times, boolean values, binary data, and more.
SQL tables can also have constraints, which further enforce the validity of data inserted into the table. For example, a column can be given a unique constraint, which prevents two rows having the same value, or a not null constraint, which means that every row must have a value.
SQL databases commonly contain many tables; these tables can be joined together to represent much more complicated data structures. By breaking data into multiple linked tables, it can be stored in a way that is much more efficient and resilient than our two-dimensional plaintext CSV files.

Basic SQL operations

SQL is a powerful and expressive language for doing mass manipulations of tabular data, but the basics can be grasped quickly. SQL is executed as individual queries which either define or manipulate data in the database. SQL dialects vary somewhat between different relational database products, but most of them support ANSI/ISO-standard SQL for core operations. While we'll be using PostgreSQL in this chapter, most of the SQL statements we write will be portable to different databases.
To follow this section, connect to an empty database on your PostgreSQL database server, either using the psql command-line tool, the pgAdmin 4 graphical tool, or another database client software of your choosing.

Syntax differences from Python

If you've only ever programmed in Python, SQL may feel odd at first, as the rules and syntax are very different.
We'll be going over the individual commands and keywords, but the following are some general differences from Python:
  • SQL is (mostly) case-insensitive: Although it's conventional for readability purposes to type the SQL keywords in all-caps, most SQL implementations are not case-sensitive. There are a few small exceptions here and there, but, for the most part, you can type SQL in whatever case is easiest for you.
  • Whitespace is not significant: In Python, new lines and indentation can change the meaning of a piece of code. In SQL, whitespace is not significant and statements are terminated with a semicolon. Indents and new lines in a query are only there for readability.
  • SQL is declarative: Python could be described as an imperative programming language: we tell Python what we want it to do by telling it how to do it. SQL is more of a declarative language: we describe what we want, and the SQL engine figures out how to do it.
We'll encounter additional syntax differences as we look at specific SQL code examples.

Defining tables and inserting data

SQL tables are created using the CREATE TABLE command as shown in the following SQL query:
CREATE TABLE musicians (id SERIAL PRIMARY KEY, name TEXT NOT NULL, born DATE, died DATE CHECK(died > born));
In this example, we're creating a table called musicians. After the name, we specify a list of column definitions. Each column definition follows the format column_name data_type constraints.
In this case, we have the following four columns:
  • The id column will be an arbitrary row ID. It's type is SERIAL, which means it will be an autoincrementing integer field, and its constraint is PRIMARY KEY, which means it will be used as the unique identifier for the row.
  • The name field is of type TEXT, so it can hold a string of any length. Its constraint of NOT NULL means that the NULL values are not allowed in this field.
  • The born and died fields are the DATE fields, so they can only hold a date value. The born field has no constraints, but died has a CHECK constraint enforcing that its value must be greater than the value of born for any given row.
Although it's not required, it's a good practice to specify a primary key for each table. Primary keys can be one...

Indice dei contenuti