(This page has no text content)
i Building Modern GUIs with tkinter and Python Building user-friendly GUI applications with ease Saurabh Chandrakar Dr. Nilesh Bhaskarrao Bahadure www.bpbonline.com
ii Copyright © 2023 BPB Online 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 BPB Online 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. BPB Online has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, BPB Online cannot guarantee the accuracy of this information. First published: 2023 Published by BPB Online WeWork 119 Marylebone Road London NW1 5PU UK | UAE | INDIA | SINGAPORE ISBN 978-93-55518-569 www.bpbonline.com
iii Dedicated to My Parents Dr Surendra Kumar Chandrakar and Smt. Bhuneshwari Chandrakar Brother Shri Pranav Chandrakar to my wife Priyanka Chandrakar and to my lovely son Yathartha Chandrakar - Saurabh Chandrakar My Parents Smt. Kamal B. Bahadure and Late Bhaskarrao M. Bahadure to my in-laws Smt. Saroj R. Lokhande and Shri. Ravikant A. Lokhande and to my wife Shilpa N. Bahadure and to beautiful daughters Nishita and Mrunmayee And to all my beloved students. - Dr. Nilesh Bhaskarrao Bahadure
iv About the Authors l Saurabh Chandrakar is a Research & Development Engineer (Dy. Manager) at Bharat Heavy Electricals Limited (BHEL) Hyderabad. He is the winner of the best executive award on Operations Division by BHEL Hyderabad. Recently, he has been awarded the prestigious BHEL Excellence Award under Anusandhan category for Redundant Composite Monitoring System of Power Transformers project. He has 20 copyrights and 1 patent granted. Additionally, he has 6 patents filed. Moreover, he has published 3 books in reputed publications such as BPB New Delhi (Programming Techniques using Python), Scitech Publications Chennai (Programming Techniques using matlab) and IK International publishers (Microcontrollers and Embedded System Design). He has also launched 1 video course on BPB titled “First Time Play with Basic, Advanced Python concepts and complete guide for different python certification exams all in one umbrella.” l Nilesh Bhaskarrao Bahadure received his Bachelor of Engineering degree in Electronics Engineering in 2000, his Master of Engineering degree in Digital Electronics in 2005, and the Ph.D. degree in Electronics in 2017 from KIIT Deemed to be University, Bhubaneswar, India. He is currently an Associate Professor in the Department of Computer Science and Engineering at Symbiosis Institute of Technology (SIT), Nagpur, Symbiosis International (Deemed University) (SIU), Pune, Maharashtra, India. He has more than 20 years of experience. Dr. Bahadure is a life member of IE(I), IETE, ISTE, ISCA, SESI, ISRS, and IAENG professional organizations. He has published more than 40 articles in reputed international journals and conferences, and has 5 books to his credit. He is the reviewer of many indexed journals such as IEEE Access, IET, Springer, Elsevier, Wiley and so on. His research interests are in the areas of Sensor Technology, the Internet of Things, and Biomedical Image Processing.
v About the Reviewer Dr. Prasenjeet Damodar Patil received B.E in E&TC Engineering from Sant Gadgebaba Amravati University and M. Tech. from Walchand College of Engineering Sangli, India. He did his Ph.D. degree in E&TC Engineering from Sant Gadgebaba Amravati University. He has 14+ years of teaching experience. Currently, he is working as Associate Professor at School of Computing, M.I.T A.D.T University, Pune. He has published more than 15 papers in reputed Journals. His research interest includes Computational Electromagnetics applications in Integrated Optics, IoT & Digital Image Processing.
vi Acknowledgements m First and foremost, I would like to thank you all for selecting this book. It has been written with the beginner reader in mind. First of all, I take this opportunity to greet and thank my mentor Prof. Nilesh Bahadure Sir for motivating me and always communicating his expertise fully on topics related to Python. I am very thankful for being his protégé. I appreciate his belief in me, for always standing behind me and pushing me to achieve more. The phrase "Journey of Thousand Miles Begins with a Single Step" is something he always reminds me of. Thank you to my parents, Dr. Surendra Kumar Chandrakar and Smt. Bhuneshwari Chandrakar, my brother, Shri Pranav Chandrakar, my beloved wife, Mrs. Priyanka Chandrakar, my adorable son Yathartha Chandrakar, and all of my friends have inspired me and given me confidence over the years. Last but not least, I would like to express my sincere gratitude to the staff at BPB Publications for their contributions and insights that made parts of this book possible. - Saurabh Chandrakar m It was my privilege to thank Dr. S. B. Mujumdar, Chancellor of the Symbiosis International University, Pune, and Shri. Vijay Kumar Gupta, Chairman of Beekay Industries Bhilai and BIT Trust, for his encouragement and support. I would like to thank my mentors Dr. Arun Kumar Ray, Dean, School of Electronics Engineering, KIIT Deemed to be University, Bhubaneswar, and Dr. Anupam Shukla, Director, SVNIT Surat. I would like to thank Dr. Vidya Yeravdekar, Principal Director of Symbiosis Society, and the Pro-Chancellor of Symbiosis International University, Pune, Dr. Rajani R. Gupte, Vice Chancellor of the Symbiosis International University, Pune, Dr. Ketan Kotecha, Dean, Faculty of Engineering, Symbiosis International University, Pune, and Dr. Mukesh M. Raghuwanshi, Director, SIT Nagpur, for their advice, and encouragement throughout the preparation of the book. I would also like to thank Dr. Sanjeev Khandal, HOD, Department of Aeronautical Engineering, SGU Kolhapur, my well-wisher Dr. Prasenjeet D. Patil, Associate Professor, MIT ADT University, Pune, and my colleagues in
vii Symbiosis Institute of Technology Nagpur for providing valuable suggestions and lots of encouragement throughout the project. I am thankful to Prof. Dr. N. Raju, Sr. Assistant Professor, SASTRA University, Thanjavur, Tamil Nadu, for his support, assistance during writing, and for his valuable suggestions. I would also like to thank Dr. Ravi M. Potdar, Sr. Associate Professor, BIT Durg, and Dr. Md. Khwaja Mohiddin, Associate Professor, BIT Raipur for providing valuable suggestions and lots of encouragement throughout the project. Writing a beautiful, well-balanced, and acquainted book is not a work of one or two days or a month; it takes a lot of time and patience, as well as hours of hard work. Many thanks to my family members, parents, wife, children, and well-wishers for their kind support. Without them and their faith and support, writing this classic book would have remained just a dream. I also like to thank my students, who have always been with me, for relating problems and finding solutions too. Perfection in any work does not come in a day. It needs a lot of effort, time and hard work, and sometimes, proper guidance. It is my privilege to thank Prof. (Dr.) Ram Dhekekar, Professor, Department of Electronics & Telecommunication Engineering, SSGMCE Shegaon, and Dr. C. G. Dethe, Director UGC Staff College Nagpur. Last, but not least, I would like to offer an extra special thanks to the staff at “BPB Publications" for their insight and contribution to polishing this book. Most significantly, I want to thank Lord Ganesha for all of the work I was able to put into the book's preparation. I would not be as zealous as I am now if it weren't for God's amazing creation of the universe. "For since the creation of the world God’s invisible qualities - his eternal power and divine nature - have been clearly seen, being understood from what has been made, so that men are without excuse." -Dr. Nilesh Bhaskarrao Bahadure
viii Preface The purpose of this book is to introduce readers with little to no programming experience, to Python Graphical User Interface (GUI). A GUI application can be created in any programming language, say VB.Net, C#.Net etc. In this book, we shall see how to create a GUI application using Python tkinter library. We will provide the readers with the foundational knowledge and skills which is required to start writing code for creating any desktop GUI app in Python language. By mastering Python tkinter library, readers will be able to apply this technology to solve real-world problems and create various useful applications according to their needs. The first part of the book covers basic GUI tkinter concepts followed by a touch of inbuilt variable classes for creating different tkinter GUI widgets. Then we shall see some insights of different widgets viz button, input, display, container, item and user-interactive widgets. Finally, in the later part of the book, we shall explore handling file selection and getting widget along with trace information in tkinter. This book covers a wide range of topics, from basic definition of different widgets along with various solved examples and well explanatory code. Overall, the book provides a solid foundation for beginners to start their journey for getting trained in python GUI using tkinter library. This book is divided into 11 chapters. Each chapter description is listed as follows. Chapter 1: tkinter Introduction – will cover the basic GUI example of creating a parent window along with its size maximizing by adjusting the width or height. It will also introduce about each standard attribute of python tkinter GUI, which is, dimensions, colors, fonts, cursors and so on. The concept of tkinter geometry manager with examples will be covered. Finally, we will learn how to access and set pre-defined variables sub classed from the tkinter variable class viz StringVar, IntVar, DoubleVar and BooleanVar. Chapter 2: Inbuilt Variable Classes for Python tkinter GUI Widgets – will cover the concept of creating of a simple GUI windows app using classes and objects concepts.
ix Chapter 3: Getting Insights of Button Widgets in tkinter – is dedicated to the concept of dealing with one of the most commonly used GUI widgets viz tkinter Button widget. We will view the binding of events to the above widget with multiple examples and different methods, including lambda expressions. Next, we shall see the Checkbutton widget which will give the provision to the user to select more than one option. The user will also view different options to get the image in the above widget. Next, we will see how to use tkinter Radiobutton widget. The user will see different examples where exactly one of the predefined set of options will be chosen. Last but not the least, we will explore tkinter OptionMenu widget where the user views how a pop menu and button widget will be created for an individual option selection from a list of options. Chapter 4: Getting Insights of Input Widgets in tkinter – is dedicated to cover the concept of creating a simple GUI app using tkinter Entry widget with very neat way of various options explanations, followed by different solved examples. Moreover, the validation concept in Entry widget is very neatly explained. Next, we shall see about scrollbar widget where user will look into the scrolling capability in vertical or horizontal direction with different widgets such as List Box, Entry and Text. Another one is tkinter Spinbox widget, where the range of input values will be fed to the user, out of which, the user can select the one. Next, we will be looking into how to implement a graphical slider to any Python application program by using tkinter Scale widget. Next is the concept of tkinter Text widget where the user can insert multiple text fields. Finally, we will be dealing with tkinter Combobox widget and its applications. Chapter 5: Getting Insights of Display Widgets in tkinter – is dedicated to the concept of creating a simple GUI app using tkinter Label widget, which depicts the ways of displaying a text or image on a window form. We shall also learn about the display of prompt unedited text messages to the user with tkinter Message widget. Moreover, we will look into multiple message boxes like information, warning, error and so on, in a Python application by using tkinter MessageBox widget. Chapter 6: Getting Insights of Container Widgets in tkinter – is dedicated to the concept of tkinter Frame widget, where the user can arrange different widgets position, can provide padding, can be used as geometry manager for other widgets and so on. We shall look into the variant of Frame widget, which is tkinter LabelFrame and is a container for complex window layouts. The user will be able to see frame features along with label display. Moreover, we shall view creating tabbed widget with the help of using tkinter Notebook widget. Here, user can
x select different pages of contents by clicking on tabs. The importance of tkinter PanedWindow widget will be explored where multiple examples will be seen containing horizontal or vertical stack of child widgets. Finally, we will look into tkinter Toplevel widget where the concepts are being explained for the creation and display of top level windows. Chapter 7: Getting Insights of Item Widgets in tkinter – is dedicated to tkinter Listbox widget where user can display different types of list of items and a number of items can be selected from the list. Different selectmode examples will be seen along with scrollbar attached to the above widget. Chapter 8: Getting Insights of tkinter User Interactive Widgets – focuses on the user to create different menus such as pop-up, top level and pull -down menu with the help of tkinter Menu widget. The user can create different applications such as Notepad, Wordpad, any management software and so on. Moreover, we will explore drop-down menu widget which is associated with a Menu widget called tkinter Menubutton widget, which can display the choices when user clicks on the above Menubutton. User can add checkbutton or radiobutton with the help of above Menubutton. Finally, we will study the concepts of drawing different graphics like line, rectangle and so on, with the help of tkinter Canvas widget. Chapter 9: Handling File Selection in tkinter – will handle file selection with different dialogs for opening a file, saving a file and so on, with the help of multiple examples using various Python examples. Chapter 10: Getting Widget Information and Trace in tkinter – is dedicated to getting widget information and different trace methods viz trace_add, trace_ remove, trace_info and so on, using various Python examples. Chapter 11: UserLogin Project in tkinter GUI Library with sqlite3 Database – will cover an application created using tkinter library along with interacting with sqlite3 database.
xi Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/dq4ctt8 The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/Building-Modern-GUIs-with-tkinter-and- Python. In case there's an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family. Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at : business@bpbonline.com for more details. At www.bpbonline.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 BPB books and eBooks.
xii Piracy If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at business@bpbonline.com with a link to the material. If you are interested in becoming an author If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights 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. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions. We at BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com. Join our book's Discord space Join the book's Discord Workspace for Latest updates, Offers, Tech happenings around the world, New Release and Sessions with the Authors: https://discord.bpbonline.com
xiii Table of Contents 1. tkinter Introduction .................................................................................................... 1 Introduction ............................................................................................................ 1 Structure .................................................................................................................. 1 Objectives ................................................................................................................ 2 Introduction to tkinter ........................................................................................... 2 Basic Python GUI program .................................................................................. 4 Some standard attributes of Python tkinter GUI .............................................. 8 Dimensions ........................................................................................................ 8 borderwidth ............................................................................................................. 8 highlightthickness .................................................................................................... 8 padX, padY .............................................................................................................. 9 wraplength ............................................................................................................. 10 height ..................................................................................................................... 10 underline ............................................................................................................... 10 width ...................................................................................................................... 11 Colors .................................................................................................................... 11 activebackground ................................................................................................... 11 background ............................................................................................................ 11 activeforeground .................................................................................................... 12 foreground ............................................................................................................. 12 disabledforeground ................................................................................................ 13 highlightbackground .............................................................................................. 14 selectbackground.................................................................................................... 15 selectforeground ..................................................................................................... 15 Fonts ...................................................................................................................... 16 By creating a font object .................................................................................. 16 By using tuple .................................................................................................. 19 Anchors ................................................................................................................. 19 Placing widget position when anchor = N ...................................................... 20
xiv Placing widget position when anchor = S ....................................................... 21 Placing widget position when anchor = E ....................................................... 21 Placing widget position when anchor = W ...................................................... 22 Placing widget position when anchor = NE .................................................... 22 Placing widget position when anchor = NW .................................................. 22 Placing widget position when anchor = SE ..................................................... 23 Placing widget position when anchor = SW ................................................... 23 Placing widget position when anchor = CENTER .......................................... 23 Relief styles ........................................................................................................... 24 Bitmaps .................................................................................................................. 25 Cursors .................................................................................................................. 26 Python tkinter geometry management ............................................................. 28 pack() ................................................................................................................ 28 grid() ................................................................................................................ 29 place() ............................................................................................................... 32 Geometry method in tkinter ............................................................................. 35 Conclusion ............................................................................................................ 36 Points to remember ............................................................................................. 37 Questions .............................................................................................................. 37 2. Inbuilt Variable Classes for Python tkinter GUI Widgets ................................ 39 Introduction .......................................................................................................... 39 Structure ................................................................................................................ 39 Objectives .............................................................................................................. 40 Inbuilt variable classes ........................................................................................ 40 StringVar() ............................................................................................................. 40 BooleanVar() ......................................................................................................... 42 IntVar() .................................................................................................................. 44 DoubleVar() .......................................................................................................... 45 GUI creation using classes and objects ............................................................. 47 Conclusion ............................................................................................................ 51 Points to remember ............................................................................................. 51 Questions .............................................................................................................. 51
xv 3. Getting Insights of Button Widgets in tkinter ..................................................... 53 Introduction .......................................................................................................... 53 Structure ................................................................................................................ 53 Objectives .............................................................................................................. 54 tkinter Button Widget.......................................................................................... 54 Events and bindings ........................................................................................ 60 event type .............................................................................................................. 60 tkinter Checkbutton widget ............................................................................... 81 tkinter Radiobutton widget ................................................................................ 91 tkinter OptionMenu widget ............................................................................. 100 Conclusion .......................................................................................................... 103 Points of remember ........................................................................................... 103 Questions ............................................................................................................ 103 4. Getting Insights of Input Widgets in tkinter ..................................................... 105 Introduction ........................................................................................................ 105 Structure .............................................................................................................. 105 Objectives ............................................................................................................ 106 tkinter Entry widget .......................................................................................... 106 Validation in the Entry widget ...................................................................... 121 tkinter Scrollbar widget .................................................................................... 126 Scrollbar attached to Listbox .......................................................................... 127 Scrollbar attached to Text............................................................................... 128 Scrollbar attached to Canvas ......................................................................... 130 Scrollbar attached to Entry ............................................................................ 131 tkinter Spinbox widget ..................................................................................... 132 tkinter Scale widget ........................................................................................... 138 tkinter Text widget ............................................................................................. 145 tkinter Combobox Widget ................................................................................ 164 Conclusion .......................................................................................................... 173 Points to remember ........................................................................................... 173 Questions ............................................................................................................ 174
xvi 5. Getting Insights of Display Widgets in tkinter ................................................. 175 Introduction ........................................................................................................ 175 Structure .............................................................................................................. 175 Objectives ............................................................................................................ 176 tkinter Label Widget .......................................................................................... 176 tkinter Message Widget .................................................................................... 191 tkinter MessageBox Widget .............................................................................. 193 showinfo() ...................................................................................................... 194 showwarning() ............................................................................................... 195 showerror() ..................................................................................................... 196 askquestion() .................................................................................................. 197 askokcancel() .................................................................................................. 198 askyesno() ....................................................................................................... 199 askretrycancel() .............................................................................................. 200 Conclusion .......................................................................................................... 201 Points of remember ........................................................................................... 201 Questions ............................................................................................................ 202 6. Getting Insights of Container Widgets in tkinter ............................................. 203 Introduction ........................................................................................................ 203 Structure .............................................................................................................. 204 Objectives ............................................................................................................ 204 tkinter Frame Widget ........................................................................................ 204 tkinter LabelFrame Widget .............................................................................. 209 tkinter Tabbed/Notebook Widget ................................................................... 212 tkinter PanedWindow widget .......................................................................... 214 tkinter Toplevel widget ..................................................................................... 221 Conclusion .......................................................................................................... 232 Points of remember ........................................................................................... 232 Questions ............................................................................................................ 232 7. Getting Insights of Item Widgets in tkinter ....................................................... 235 Introduction ........................................................................................................ 235
xvii Structure .............................................................................................................. 235 Objectives ............................................................................................................ 235 tkinter Listbox widget ....................................................................................... 236 Conclusion .......................................................................................................... 245 Points of remember ........................................................................................... 246 Questions ............................................................................................................ 246 8. Getting Insights of tkinter User Interactive Widgets .......................................247 Introduction .............................................................................................................247 Structure ...................................................................................................................247 Objectives .................................................................................................................248 tkinter Menu widget...............................................................................................248 tkinter Menubutton widget ...................................................................................263 tkinter Canvas widget ............................................................................................267 Conclusion ...............................................................................................................281 Points to remember ................................................................................................281 Questions .................................................................................................................282 9. Handling File Selection in tkinter ........................................................................283 Introduction .............................................................................................................283 Structure ...................................................................................................................284 Objectives .................................................................................................................284 Handling file selection in tkinter ..........................................................................284 Conclusion ...............................................................................................................299 Points of remember ................................................................................................300 Questions .................................................................................................................300 10. Getting Widget Information and Trace in tkinter .............................................301 Introduction .............................................................................................................301 Structure ...................................................................................................................301 Objectives .................................................................................................................302 Getting widget information ..................................................................................302 Trace in tkinter ........................................................................................................308
xviii trace_add()............................................................................................................309 trace_remove() ......................................................................................................309 trace_info() ...........................................................................................................309 Conclusion ............................................................................................................... 311 Points to remember ................................................................................................312 Questions .................................................................................................................312 11. UserLogin Project in tkinter GUI Library with sqlite3 Database ..................313 Introduction .............................................................................................................313 Structure ...................................................................................................................313 Objectives .................................................................................................................313 GUI interaction with sqlite3 database .................................................................314 Displaying a GUI application ...............................................................................314 Conclusion ...............................................................................................................339 Points to remember ................................................................................................339 Questions ...............................................................................................................340 Index ....................................................................................................................341-345
Comments 0
Loading comments...
Reply to Comment
Edit Comment