Python GUI Programming with Tkinter: Develop responsive and powerful GUI applications with Tkinter, 2nd Edition / Программирование графического интерфейса на Python с помощью Tkinter: Разрабатывайте адаптивные и мощные графические приложения с помощью Tkinter, 2-е издание
Год издания: 2021
Автор: Moore Alan D. / Мур Алан Д.
Издательство: Packt Publishing
ISBN: 978-1-80181-592-5
Язык: Английский
Формат: PDF, EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 665
Описание: Write feature-rich GUI applications from scratch to meet the demands of evolving user needs
Key Features
Take advantage of Tkinter’s lightweight, portable, and easy-to-use features
Transform your business requirements into efficient applications
Build better-organized code and learn to manage an evolving codebase
Book Description
Tkinter is widely used to build GUIs in Python due to its simplicity. In this book, you’ll discover Tkinter’s strengths and overcome its challenges as you learn to develop fully featured GUI applications.
Python GUI Programming with Tkinter, Second Edition will not only provide you with a working knowledge of the Tkinter GUI library, but also a valuable set of skills that will enable you to plan, implement, and maintain larger applications. Starting from a set of business requirements for a simple data entry form, you’ll build a full-blown application from the ground up, learning how to grow and improve your code in response to continually changing user and business needs.
You’ll develop a practical understanding of tools and techniques used to manage this evolving codebase, such as version control and unit testing, separation of concerns through the ubiquitous model-view-controller (MVC) design pattern, and object-oriented programming (OOP) to organize your code and go beyond the default Tkinter widget capabilities.
Throughout, the design choices you make are contextualized in important real-world terms. You’ll gain experience with technologies often used in workplace applications, such as SQL databases, network services, and data visualization libraries. You’ll also package your application for wider distribution and tackle the challenge of maintaining compatibility across multiple platforms.
What you will learn
Produce well-organized, functional, and responsive GUI applications
Extend the functionality of existing widgets using classes and OOP
Plan wisely for the expansion of your app using MVC and version control
Make sure your app works as intended through widget validation and unit testing
Use tools and processes to analyze and respond to user requests
Become familiar with technologies used in workplace applications, including SQL, HTTP, Matplotlib, threading, and CSV
Use PostgreSQL authentication to ensure data security for your application
Who This Book Is For
This book is for programmers who understand the syntax of Python, but do not yet have the skills, techniques, and knowledge to design and implement a complete software application. A fair grasp of basic Python syntax is required.
Создавайте многофункциональные приложения с графическим интерфейсом с нуля, чтобы соответствовать растущим потребностям пользователей
Ключевые функции
Воспользуйтесь преимуществами легких, портативных и простых в использовании функций Tkinter
Преобразуйте свои бизнес-требования в эффективные приложения
Создавайте лучше организованный код и учитесь управлять развивающейся кодовой базой
Описание книги
Tkinter широко используется для создания графических интерфейсов на Python благодаря своей простоте. В этой книге вы откроете для себя сильные стороны Tkinter и преодолеете его трудности, научившись разрабатывать полнофункциональные графические приложения.
Программирование графического интерфейса на Python с помощью Tkinter, второе издание не только даст вам практические знания о библиотеке графического интерфейса Tkinter, но и ценный набор навыков, которые позволят вам планировать, внедрять и поддерживать более крупные приложения. Начав с набора бизнес-требований к простой форме ввода данных, вы создадите полноценное приложение с нуля, научившись расширять и улучшать свой код в ответ на постоянно меняющиеся потребности пользователей и бизнеса.
Вы получите практическое представление об инструментах и методах, используемых для управления этой развивающейся кодовой базой, таких как контроль версий и модульное тестирование, разделение задач с помощью вездесущего шаблона проектирования модель, представление и контроллер (МПК) и объектно-ориентированного программирования (ООП) для организации вашего кода и выхода за рамки стандартного Tkinter возможности виджета.
На протяжении всего процесса выбор дизайна, который вы делаете, учитывается в контексте важных условий реального мира. Вы приобретете опыт работы с технологиями, часто используемыми в приложениях для рабочих мест, такими как базы данных SQL, сетевые службы и библиотеки визуализации данных. Вы также упакуете свое приложение для более широкого распространения и решите проблему обеспечения совместимости на нескольких платформах.
Чему вы научитесь
Создавать хорошо организованные, функциональные и отзывчивые приложения с графическим интерфейсом
Расширять функциональность существующих виджетов с помощью классов и ООП
Разумно планировать расширение вашего приложения с помощью МПК и контроля версий
Убедитесь, что ваше приложение работает должным образом с помощью проверки виджетов и модульного тестирования
Использовать инструменты и процессы для анализа запросов пользователей и реагирования на них
Познакомитесь с технологиями, используемыми в рабочих приложениях, включая SQL, HTTP, Matplotlib, многопоточность и CSV
Использовать аутентификацию PostgreSQL для обеспечения безопасности данных вашего приложения
Для кого предназначена эта книга
Эта книга предназначена для программистов, которые понимают синтаксис Python, но еще не обладают навыками, техниками и знаниями для разработки и реализации полноценного программного приложения. Требуется хорошее понимание базового синтаксиса Python.
Оглавление
Preface xvii
Chapter 1: Introduction to Tkinter 1
Introducing Tkinter and Tk 2
Choosing Tkinter 2
Installing Tkinter 3
Installing Python 3.9 on Windows 3
Installing Python 3 on macOS 4
Installing Python 3 and Tkinter on Linux 4
Introducing IDLE 4
Using the shell mode of IDLE 5
Using the editor mode of IDLE 5
IDLE as a Tkinter example 6
Creating a Tkinter Hello World 7
An overview of basic Tkinter 9
Building a GUI with Tkinter widgets 10
Arranging our widgets with geometry managers 14
Making the form actually do something 19
Handling data with Tkinter control variables 21
Using control variables in a callback function 26
The importance of control variables 28
Summary 28
Chapter 2: Designing GUI Applications 29
Analyzing a problem at ABQ AgriLabs 29
Assessing the problem 30
Gathering information about the problem 30
Interviewing the interested parties 31
Analyzing what we've found out 33
Information from the data originators 34
Information from the users of the application 35
Information from technical support 36
Information from the data consumer 36
Documenting specification requirements 37
Contents of a simple specification 38
Writing the ABQ data entry program specification 39
Designing the application 42
Deciding on input widgets 42
Grouping our fields 44
Laying out the form 45
Laying out the application 47
Evaluating technology options 49
Summary 50
Chapter 3: Creating Basic Forms with Tkinter and Ttk Widgets 51
The Ttk widget set 51
The Label widget 52
The Entry widget 53
The Spinbox widget 54
The Checkbutton widget 56
The Radiobutton widget 57
The Combobox widget 58
The Text widget 59
Text widget indices 60
The Button widget 62
The LabelFrame widget 62
Implementing the application 64
First steps 65
Building the data record form 66
The Record Information section 67
The Environment Data section 69
The Plant Data section 70
Finishing the GUI 72
Writing the callback functions 73
The Reset function 73
The Save callback 74
Finishing up and testing 78
Summary 79
Chapter 4: Organizing Our Code with Classes 81
A primer on Python classes 81
The advantages of using classes 82
Classes are an integral part of Python 82
Classes make relationships between data and functions explicit 82
Classes help create reusable code 83
Syntax of class creation 83
Attributes and methods 83
Magic attributes and methods 86
Public, private, and protected members 88
Inheritance and subclasses 90
Using classes with Tkinter 91
Improving Tkinter classes 91
Creating compound widgets 93
Building encapsulated components 95
Subclassing Tk 97
Rewriting our application using classes 100
Adding a StringVar to the Text widget 100
Passing in a variable 101
Synchronizing the widget to the variable 101
Synchronizing the variable to the widget 102
Creating a more advanced LabelInput() 103
Creating a form class 106
Creating an application class 112
Summary 114
Chapter 5: Reducing User Error with Validation and Automation 117
Validating user input 117
Strategies to prevent data errors 118
Validation in Tkinter 119
The validate argument 120
The validatecommand argument 120
The invalidcommand argument 122
Creating validated widget classes 123
Creating a Date field 125
Implementing validated widgets in our GUI 129
Introducing the power of multiple inheritance 129
Building a validating mixin class 132
Building validating input widgets with ValidatedMixin 136
Requiring data 136
Creating a Date widget 137
A better Combobox widget 138
A range-limited Spinbox widget 140
Validating Radiobutton widgets 144
Updating our form with validated widgets 146
Implementing validation interaction between form widgets 149
Dynamically updating the Spinbox range 149
Dynamic disabling of fields 154
Displaying errors 156
Preventing form submission on error 157
Automating input 159
Date automation 160
Automating Plot, Lab, Time, and Technician 161
Summary 162
Chapter 6: Planning for the Expansion of Our Application 163
Separating concerns 164
The MVC pattern 164
What is a model? 165
What is a view? 165
What is a controller? 166
Why complicate our design? 166
Structuring our application directory 167
Basic directory structure 167
The abq_data_entry.py file 168
The README.rst file 169
Populating the docs folder 170
Making a Python package 170
Splitting our application into multiple files 172
Creating the models module 172
Moving the widgets 179
Moving the views 180
Removing redundancy in our view logic 181
Using custom events to remove tight coupling 185
Creating the application file 186
Running the application 188
Using version control software 189
A super-quick guide to using Git 189
Initializing and configuring a Git repository 190
Adding and committing code 190
Viewing and using our commits 191
Summary 192
Chapter 7: Creating Menus with Menu and Tkinter Dialogs 193
Solving problems in our application 194
Planning solutions to the issues 194
Implementing Tkinter dialogs 196
Error dialogs with the Tkinter messagebox 196
Showing error dialogs in ABQ Data Entry 199
Using filedialog 201
Using simpledialog and creating a custom dialog 204
Creating a Login dialog using simpledialog 205
Incorporating the LoginDialog in our class 208
Designing the application menu 211
The Tkinter Menu widget 211
Using Checkbutton and Radiobutton items 213
Implementing the ABQ application menu 215
Adding a Help menu 216
Adding a File menu 217
Adding a settings menu 220
Finishing the menu 222
Persisting settings 223
Building a model for settings persistence 224
Using the settings model in our application 228
Summary 230
Chapter 8: Navigating Records with Treeview and Notebook 231
Implementing read and update in the model 231
Adding read and update to the CSVModel class 232
Implementing get_all_records() 233
Implementing get_record() 235
Adding update capability to save_record() 236
The Ttk Treeview 237
Anatomy of a Treeview 238
Building a file browser 239
Creating and configuring a Treeview 240
Populating a Treeview with data 242
Sorting Treeview records 244
Using Treeview virtual events 247
Implementing a record list with Treeview 248
Creating the RecordList class 249
Configuring a Treeview widget 250
Adding a scrollbar for the Treeview 252
Populating the Treeview 253
Adding the record list to the application 254
Modifying the record form for read and update 255
Adding a current record property 255
Adding a label to show what is being edited 255
Adding a load_record() method 256
Updating the application layout 257
The Ttk Notebook widget 259
Adding a notebook to our application 261
Adding and updating application callbacks 262
The _show_recordlist() method 263
The _populate_recordlist() method 264
The _new_record() method 265
The _open_record() method 266
The _on_save() method 267
Main menu changes 267
Testing our program 268
Summary 269
Chapter 9: Improving the Look with Styles and Themes 271
Working with images in Tkinter 272
Tkinter PhotoImage 272
PhotoImage and variable scope 273
Using Pillow for extended image support 274
Adding the company logo to ABQ Data Entry 277
Dealing with the image path problem 278
Setting a window icon 281
Adding icons to buttons and menus 282
Using BitmapImage 286
Styling Tkinter widgets 287
Widget color properties 287
Using widget properties on the MainMenu 288
Styling widget content with tags 291
Styling our record list with tags 294
Working with fonts in Tkinter 297
Configuring Tkinter fonts 297
Configuring fonts with strings and tuples 298
The font module 299
Giving users font options in ABQ Data Entry 302
Styling Ttk widgets 305
TTk styling breakdown 306
Exploring a Ttk widget 307
Using themes 312
Adding some color to ABQ Data Entry 313
Adding styles to individual form widgets 316
Fixing the error colors 318
Styling input widgets on error 319
Setting themes 321
Building a theme selector 321
Summary 325
Chapter 10: Maintaining Cross-Platform Compatibility 327
Writing cross-platform Python 327
Filenames and file paths across platforms 328
Path separators and drives 328
Case sensitivity 331
Symbolic links 332
Path variables 333
Inconsistent library and feature support 334
Python's platform-limited libraries 334
Checking low-level function compatibility 335
The dangers of the subprocess module 336
Text file encodings and formats 336
Graphical and console modes 337
Writing code that changes according to the platform 338
Writing cross-platform Tkinter 341
Tkinter version differences across platforms 341
Application menus across platforms 342
Menu widget capabilities 342
Menu guidelines and standards 346
Menus and accelerator keys 347
Cross-platform fonts 347
Cross-platform theme support 348
Window zoomed state 348
Improving our application's cross-platform compatibility 349
Storing preferences correctly 349
Specifying an encoding for our CSV file 351
Making platform-appropriate menus 351
Preparing our MainMenu class 351
Adding accelerators 355
Building the Windows menu 357
Building the Linux menu 359
Building the macOS menu 360
Creating and using our selector function 363
Summary 365
Chapter 11: Creating Automated Tests with unittest 367
Automated testing basics 367
A simple unit test 368
The unittest module 370
Writing a test case 371
TestCase assertion methods 373
Fixtures 374
Using Mock and patch 375
Running multiple unit tests 377
Testing Tkinter code 377
Managing asynchronous code 378
Simulating user actions 378
Specifying an event sequence 379
Managing focus and grab 380
Getting widget information 381
Writing tests for our application 381
Testing the data model 381
Testing file reading in get_all_records() 383
Testing file saving in save_record() 385
More tests on the models 387
Testing our Application object 387
Testing our widgets 392
Unit testing the ValidatedSpinbox widget 393
Integration testing the ValidatedSpinbox widget 395
Testing our mixin class 400
Summary 402
Chapter 12: Improving Data Storage with SQL 403
PostgreSQL 404
Installing and configuring PostgreSQL 404
Configuring PostgreSQL using the GUI utility 405
Configuring PostgreSQL using the command line 405
Modeling relational data 406
Primary keys 406
Using surrogate primary keys 407
Normalization 408
First normal form 409
Second normal form 410
Third normal form 411
More normalization forms 411
Entity-relationship diagrams 412
Assigning data types 414
Creating the ABQ database 415
Creating our tables 415
Creating the lookup tables 415
The lab_checks table 417
The plot_checks table 417
Creating a view 419
Populating the lookup tables 420
Connecting to PostgreSQL with psycopg2 420
psycopg2 basics 421
Parameterized queries 423
Special cursor classes 425
Integrating SQL into our application 426
Creating a new model 426
Saving data 431
Getting the current seed sample for the plot 434
Adjusting the Application class for the SQL backend 435
Implementing SQL logins 435
Updating the Application._on_save() method 437
Removing file-based code 438
Adjusting the DataRecordForm for SQL data 438
Reordering fields 438
Fixing the load_record() method 439
Improving auto-fill 440
Updating the RecordList for the SQLModel 441
We're done! 444
Summary 444
Chapter 13: Connecting to the Cloud 447
HTTP using urllib 447
HTTP transaction fundamentals 448
HTTP status codes 448
Basic downloading with urllib.request 449
Generating POST requests 450
Downloading weather data to ABQ Data Entry 451
Creating a weather data model 451
Parsing the XML weather data 453
Implementing weather data storage 456
Adding the GUI elements for weather download 458
RESTful HTTP using requests 461
Understanding RESTful web services 461
The Python requests library 462
Installing and using requests 462
Interacting with authenticated sites using Session 463
The requests.Response object 465
Implementing a REST backend 466
The authenticate() method 468
The upload_file() method 470
The check_file() method 470
The get_file() method 471
Integrating REST upload into the application 471
Creating a CSV extract 472
Creating the upload callback 473
Finishing up 476
SFTP using paramiko 478
Setting up SSH services for testing 478
Installing and using paramiko 479
Using paramiko 479
Inspecting our connection 481
Using SFTP 481
Implementing an SFTP model 482
Uploading files 485
Checking a file's existence 486
Using SFTPModel in our application 487
Finishing up 490
Summary 491
Chapter 14: Asynchronous Programming with
Thread and Queue 493
Tkinter's event queue 494
Event queue control 494
The update() methods 494
The after() methods 495
Common uses of event queue control 496
Smoothing out display changes 496
Mitigating GUI freezes 497
Running code in the background with threads 500
The threading module 500
Tkinter and thread safety 502
Converting our network functions to threaded execution 503
Using the threaded uploader 505
Passing messages using a queue 506
The Queue object 506
Using queues to communicate between threads 508
Adding a communication queue to our threaded uploader 510
Creating a communications protocol 511
Sending messages from the uploader 513
Handling queue messages 514
Using locks to protect shared resources 516
Understanding the Lock object 516
Using a Lock object to prevent concurrent uploads 518
Threading and the GIL 518
Summary 519
Chapter 15: Visualizing Data Using the Canvas Widget 521
Drawing and animation with Tkinter's Canvas 521
Drawing on the Canvas 522
Rectangles and squares 522
Ovals, circles, and arcs 524
Lines 525
Polygons 526
Text 526
Images 527
Tkinter widgets 527
Canvas items and state 528
Canvas object methods 528
Scrolling the Canvas 530
Animating Canvas objects 533
Setting up the playing field 533
Setting our players 534
Animating the racers 535
Running the game loop and detecting a win condition 539
Creating simple graphs using Canvas 542
Creating the model method 543
Creating the chart view 544
Updating the application 549
Advanced graphs using Matplotlib 551
Data model method 551
Creating the bubble chart view 552
Updating the Application class 555
Summary 558
Chapter 16: Packaging with setuptools and cxFreeze 559
Creating distributable packages with setuptools 559
Preparing our package for distribution 560
Creating a requirements.txt file 560
Creating a pyproject.toml file 562
Adding a license file 563
Making our package executable 564
Configuring a setup.py script 565
Basic metadata arguments 566
Packages and dependencies 567
Adding extra files 569
Defining commands 570
Testing the configuration 571
Creating and using source distributions 571
Testing our source distribution 572
Building a wheel distribution 573
Creating executables with cx_Freeze 575
First steps with cx_Freeze 575
The build_exe options 577
Including external files 578
Building executables 580
Cleaning up the build 580
Building Windows executables with cx_Freeze 581
Building a Windows installer file 582
Building macOS executables with cx_Freeze 586
Building macOS application bundles 586
Building macOS .dmg files 587
Summary 588
Appendices 589
A: A Quick Primer on reStructuredText 591
B: A Quick SQL Tutorial 603
Other Books You May Enjoy 619
Index 625