Tkinter GUI Programming by Example
Total Page:16
File Type:pdf, Size:1020Kb
Tkinter GUI Programming by Example Learn to create modern GUIs using Tkinter by building real-world projects in Python David Love BIRMINGHAM - MUMBAI Tkinter GUI Programming by Example Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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. Commissioning Editor: Aaron Lazar Acquisition Editor: Denim Pinto Content Development Editor: Anugraha Arunagiri Technical Editor: Subhalaxmi Nadar Copy Editor: Safis Editing Project Coordinator: Ulhas Kambali Proofreader: Safis Editing Indexer: Aishwarya Gangawane Graphics: Tania Dutta Production Coordinator: Arvindkumar Gupta First published: April 2018 Production reference: 1240418 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78862-748-1 www.packtpub.com mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content 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 [email protected] 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. Contributors About the author David Love is a web developer from Kent, England. He has worked on a multitude of different systems over his career. Programming languages in his arsenal include Python, PHP, and JavaScript. He is well-trained in Linux server management and its relevant technologies, including MySQL, PostgreSQL, NGINX, and supervisor. David has written an e-book called Tkinter By Example, which is available for free under a Creative Commons licenses and maintains an ever-growing blog post named The Tkinter Cookbook, full of small examples on how to perform some specific tasks. About the reviewer Erik S. Rapert is a programmer and a twin who loves Linux and video games. He lives in Dallas with his wife, who is also a software engineer. Erik has a wide range of experience, which includes creating blinking LEDs using Arduino, building small desktop apps using Python and Tkinter, web development with PHP or Ruby, and developing cutting-edge virtual reality using C++. He has used a very broad range of programming languages, but Python is one of his favorites. Thank you William C. Slater for teaching me how to write software. Thank you Andrew Closson for being a teacher. Thank you Ashley N. Tharp for being you. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Table of Contents Preface 1 Chapter 1: Meet Tkinter 6 Installation 7 How will the code be structured? 7 Geometry managers 8 pack 8 grid 9 place 10 To pack or to grid? 11 Getting going 12 Adding interactivity 14 Using variables 16 Our first try 16 Creating Tkinter-compatible variables 17 Using and updating 18 Fixing our application 18 Showing messages 19 Showing information with showinfo 19 Showing warnings or errors 20 Getting feedback from the user 21 Getting text input 22 Summary 24 Chapter 2: Back to the Command Line – Basic Blackjack 25 Python's class system 26 Instances 26 Inheritance 28 Blackjack's classes 30 The Card class 30 The Deck class 31 The Hand class 32 The Game class and main loop 33 Command line versus GUI 38 Interactivity 38 Familiarity 39 Ease of use 39 Size and portability 40 Summary 40 Table of Contents Chapter 3: Jack is Back in Style – the Blackjack GUI 41 Moving from the command line to a graphical interface 41 The Canvas widget 43 Creating a graphical blackjack game 46 Card, Deck, and Hand 48 The GameState class 49 The GameScreen class 53 Playing our game 62 Summary 64 Chapter 4: The Finishing Touches – Sound and Animation 65 Python's module system 66 The blackjack packages 71 The casino package 71 The casino_sounds package 74 Setting up a virtual environment 75 Creating the package 76 The blackjack.py file 77 Initializing the GameWindow class 78 The GameScreen class 80 The GameState class 90 Choosing to hit 91 Choosing to stick 95 Running out of money 96 Finishing off 97 Summary 98 Chapter 5: Creating a Highly Customizable Python Editor 99 The ttk submodule 100 Styling a tk widget 101 Styling a ttk widget 103 Ttk style inheritance 105 Beginning our text editor 109 Tkinter's event system 112 Binding an event 112 Overwriting default events 115 Generating events 116 Events in our text editor 118 A second top-level window 123 Summary 125 Chapter 6: Color Me Impressed! – Adding Syntax Highlighting 127 Tkinter's indexing system 127 Getting the cursor's position 128 Named indexes 130 [ ii ] Table of Contents Special strings 130 Line endings 130 Horizontal movement 130 Vertical movement 131 Line beginning and end 131 Word beginning and end 131 Expanding our demo 132 Using tags 134 Searching text 137 Adding syntax highlighting to our text editor 140 The Highlighter class 140 Using our Highlighter class 150 The LineNumbers class 151 Using our LineNumbers class 153 Integrating our FindWindow class 153 Using our FindWindow class 158 Summary 159 Chapter 7: Not Just for Restaurants – All About Menus 160 The Menu widget 160 A menu bar 161 A floating menu 164 Adding a menu bar to our text editor 165 Adding a context menu to our text editor 170 Handling files 172 Changing the syntax highlighting 177 Changing the editor's font 180 The Listbox widget 181 The Spinbox widget 183 Saving the user's choices 183 Changing the editor's color scheme 186 Summary 198 Chapter 8: Talk Python to Me – a Chat Application 200 Creating a scrollable frame 200 Creating our FriendsList class 206 Creating our ChatWindow class 210 Creating our SmilieSelect class 218 Summary 226 Chapter 9: Connecting – Getting Our Chat Client Online 227 Introduction to flask 227 Our first web page 228 Using JSON 230 The requests module 232 [ iii ] Table of Contents Sending a GET request 232 Sending a POST request 233 The sqlite3 module 235 Creating a database and table 235 Adding data to a SQLite database 236 Selecting data from a SQLite database 238 Linking flask and sqlite 239 Updating our FriendsList class 243 Creating the Requester class 246 Connecting our FriendsList to our web service 248 Connecting our ChatWindow 251 Updating our server to store conversations 252 Creating the Conversation class 252 Using the Conversation class in our server 254 Adding the new endpoints to our Requester 257 Updating our ChatWindow class to send requests to the server 258 Summary 260 Chapter 10: Making Friends – Finishing Our Chat Application 262 Using threads 262 Why use a thread with a GUI application? 263 Using a thread 265 Adding a Thread to our ChatWindow 266 Creating new endpoints 266 The ListeningThread class 268 Implementing the ListeningThread class in our ChatWindow 270 Allowing users to upload avatars 272 The AvatarWindow class 273 Adjusting the database 275 Adding server endpoints 276 Updating the FriendsList class 277 Manipulating images with PIL 278 Adding and blocking other users 280 New database table 280 Creating the server endpoints 282 Tying it all together 285 Summary 289 Chapter 11: Wrapping Up – Packaging Our Applications to Share 291 Unexplored widgets 291 The LabelFrame widget 292 The Checkbutton and Radiobutton widgets 293 The OptionMenu and Combobox widgets 295 The Notebook widget 296 Packaging applications 298 [ iv ] Table of Contents Adjusting our text editor for portability 298 Preparing to package with setup.py 302 Installing our text editor 303 Cross-platform using Pip 304 Windows 304 Linux 306 macOS 308 Summary 310 Other Books You May Enjoy 312 Index 315 [ v ] Preface Welcome to Tkinter GUI Programming by Example. We will be exploring how to use the Tkinter library, which is included alongside most Python installs. This framework is very simple to use, and has a powerful event-handling system and an open license, perfect for anyone who wishes to quickly write and share graphical applications.