Building Modern GUIs with tkinter and Python (2023).pdf

Full Transcript

Building Modern GUIs with tkinter and Python Building user-friendly GUI applications with ease Saurabh Chandrakar Dr. Nilesh Bhaskarrao Bahadure www.bpbonline.com Copyright © 2023 BPB Online All right...

Building Modern GUIs with tkinter and Python Building user-friendly GUI applications with ease Saurabh Chandrakar Dr. Nilesh Bhaskarrao Bahadure www.bpbonline.com 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 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 About the Authors 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.” 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. 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. Acknowledgements 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 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 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 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. 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 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. 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 : [email protected] 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 : [email protected] 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. 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 [email protected] 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 Table of Contents 1. tkinter Introduction Introduction Structure Objectives Introduction to tkinter Basic Python GUI program Some standard attributes of Python tkinter GUI Dimensions borderwidth highlightthickness padX, padY wraplength height underline width Colors activebackground background activeforeground foreground disabledforeground highlightbackground selectbackground selectforeground Fonts By creating a font object By using tuple Anchors Placing widget position when anchor = N Placing widget position when anchor = S Placing widget position when anchor = E Placing widget position when anchor = W Placing widget position when anchor = NE Placing widget position when anchor = NW Placing widget position when anchor = SE Placing widget position when anchor = SW Placing widget position when anchor = CENTER Relief styles Bitmaps Cursors Python tkinter geometry management pack() grid() place() Geometry method in tkinter Conclusion Points to remember Questions 2. Inbuilt Variable Classes for Python tkinter GUI Widgets Introduction Structure Objectives Inbuilt variable classes StringVar() BooleanVar() IntVar() DoubleVar() GUI creation using classes and objects Conclusion Points to remember Questions 3. Getting Insights of Button Widgets in tkinter Introduction Structure Objectives tkinter Button Widget Events and bindings event type tkinter Checkbutton widget tkinter Radiobutton widget tkinter OptionMenu widget Conclusion Points of remember Questions 4. Getting Insights of Input Widgets in tkinter Introduction Structure Objectives tkinter Entry widget Validation in the Entry widget tkinter Scrollbar widget Scrollbar attached to Listbox Scrollbar attached to Text Scrollbar attached to Canvas Scrollbar attached to Entry tkinter Spinbox widget tkinter Scale widget tkinter Text widget tkinter Combobox Widget Conclusion Points to remember Questions 5. Getting Insights of Display Widgets in tkinter Introduction Structure Objectives tkinter Label Widget tkinter Message Widget tkinter MessageBox Widget showinfo() showwarning() showerror() askquestion() askokcancel() askyesno() askretrycancel() Conclusion Points of remember Questions 6. Getting Insights of Container Widgets in tkinter Introduction Structure Objectives tkinter Frame Widget tkinter LabelFrame Widget tkinter Tabbed/Notebook Widget tkinter PanedWindow widget tkinter Toplevel widget Conclusion Points of remember Questions 7. Getting Insights of Item Widgets in tkinter Introduction Structure Objectives tkinter Listbox widget Conclusion Points of remember Questions 8. Getting Insights of tkinter User Interactive Widgets Introduction Structure Objectives tkinter Menu widget tkinter Menubutton widget tkinter Canvas widget Conclusion Points to remember Questions 9. Handling File Selection in tkinter Introduction Structure Objectives Handling file selection in tkinter Conclusion Points of remember Questions 10. Getting Widget Information and Trace in tkinter Introduction Structure Objectives Getting widget information Trace in tkinter trace_add() trace_remove() trace_info() Conclusion Points to remember Questions 11. UserLogin Project in tkinter GUI Library with sqlite3 Database Introduction Structure Objectives GUI interaction with sqlite3 database Displaying a GUI application Conclusion Points to remember Questions Index CHAPTER 1 tkinter Introduction Introduction We have learned in our previous book Python for Everyone, about the concepts in Python which are procedure oriented or object oriented. However, these concepts will be used as indispensable salt for our next learning, which is related to Graphical User Interface (GUI). We are surrounded by GUI apps in day-to-day life. Whenever we are using our mobile phone/Desktop applications and accessing any app or software, the first thing which we look forward to is how to access these apps or software. Any app on mobile phone or a computer system consists of hardware and is controlled by an operating system. The high-level languages will be sitting on top of the operating system and Python is no exception. So, in this chapter, we will learn about tkinter library in Python. Structure In this chapter, we will discuss the following topics: Introduction to tkinter Basic Python GUI Program Some standard attributes of Python tkinter GUI Colors Fonts Anchors Relief Styles Bitmaps Cursors Python tkinter Geometry Manager Objectives By the end of this chapter, the reader will learn about creating basic GUI Python program using the tkinter library. In addition to that, we will also explore some standard attributes of Python tkinter GUI such as dimensions, colors or fonts with various options with examples. It is important to know how to position the text with a list of constants, relative to the reference point using anchor attribute. Moreover, we shall see how with the usage of relief attribute 3-D, simulated effects around the outside of the widget can be provided. We will also learn about bitmap and cursor attribute with examples. Finally, at the end of this chapter, we will learn accessing tkinter widgets using inbuilt layout geometry managers viz pack, grid and place. Introduction to tkinter Whenever we write any program in Python to control the hardware, Python will show the output with the help of operating system. However, if we desire to make an executable with the help of GUI, then just having the need of hardware and operating system is insufficient. Python requires some services which come from a number of resources and one such resource which is of interest to many Python programmers is Tcl/Tk. Tcl stands for Tool Command Language and it is a scripting language with its own interpreter. On the other hand, Tk is a toolkit for building GUIs. An important point to note is that Tcl/Tk is not Python and we cannot control and access the services of Tcl/Tk using Python. So, another package is introduced and is referred to as tkinter, and it is an intermediator between Python and Tcl/Tk. tkinter will allow us to use the services of Tcl/Tk using the syntax of Python. As Python code developers, we will not be directly concerned with the Tcl/Tk. Binding of Python to the Tk GUI toolkit will be done by tkinter. tkinter will make everything appear as an object. We can create GUI, knowing that we can regard the window as an object, a label place on window as an object and so on. Applications can be built from a view point of an object-oriented programming paradigm. All we need to make sure is that we write our code in such a way that it allows us access tkinter, as shown in the following Figure 1.1: Figure 1.1: tkinter access hierarchy So, GUI applications can be easily and quickly created when Python is combined with tkinter. Although Python offers multiple options for developing GUI such as PyQT, Kivy, Jython, WxPython, and pyGUI; tkinter is the most commonly used. In this book, we will focus only on the tkinter usage of GUI creation. Just like we import any other module, tkinter can be imported in the same way in Python code: import tkinter This will import the tkinter module. The module name in Python 3.x is tkinter, whereas in Python 2.x, it is Tkinter. More often, we can use: from tkinter import * Here, the ‘*’ symbol means everything, as Python now can build Graphical User Interfaces by treating all of the widgets like Buttons, Labels, Menus and so on, as if they were objects. It is like importing tkinter submodule. However, there are some important methods which the user needs to know while creating Python GUI application, and they are as follows: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1) tkinter offers this method in order to create a main window. For any application, a main window code can be created by using: import tkinter myroot = tkinter.Tk() Here, Tk class is instantiated without any arguments. myroot is the main window object name. This method will allow blank parent window creation with close, maximize and minimize buttons on the top. mainloop() tkinter offers this method when our application is ready to run. This method is an infinite loop used to run the application. It will wait for an event to occur and as long as the window is not closed, the event is processed. Basic Python GUI program Let us see a basic Python program which will create a window: Output: The output can be seen in Figure 1.2: Figure 1.2: Output of Chap1_Example1.py Note: The preceding code is covered in Program Name: Chap1_Example1.py In the preceding code, we have imported tkinter submodule and created a parent widget which usually will be the main window of an application. A blank parent window is created with close, maximize and minimize buttons on the top. An infinite loop will be called to run the application, as long as the window is not closed. The moment the window is closed, the statements after myroot.mainloop() will be executed, as shown in the following Figure 1.3: Figure 1.3: Output on running the code The moment the window is closed by clicking on the ‘X’ mark, we will get the output as shown in Figure 1.4: Figure 1.4: Execution of print statement after clicking ‘X’ mark In the preceding example, we can maximize the window in both horizontal and vertical directions by using both height and width attributes. However, we can restrict the expansion of window in any direction. Suppose we want to maximize the width only. Then, the code is as follows: Output: The output can be seen in Figure 1.5: Figure 1.5: Output of Chap1_Example2.py Note: The preceding code is covered in Program Name: Chap1_Example2.py Suppose, we want to maximize the height only. Then the code is as follows: Output: The output can be seen in Figure 1.6: Figure 1.6: Output of Chap1_Example3.py Note: The preceding code is covered in Program Name: Chap1_Example3.py Now, there is a need to maximize neither height nor width. Then the following code will be used: Output: The output can be seen in Figure 1.7: Figure 1.7: Output of Chap1_Example4.py Note: The preceding code is covered in Program Name: Chap1_Example4.py An important point to observe is that when we are maximizing the window in either of the directions, then the maximize button was enabled. Whereas in this case, the maximize button is disabled. Some standard attributes of Python tkinter GUI Now, we shall see how some of the standard attributes such as sizes, colors or fonts are specified. Just observe the standard attributes as mentioned. We shall see their usage when we will be dealing with widgets. Dimensions Whenever we set a dimension to an integer, it is assumed to be in pixels. A length is expressed as an integer number of pixels by tkinter. The list of common options are discussed as follows. borderwidth This option will give a 3-D look to the widget. It can also be represented as bd: Output: The output can be seen in Figure 1.8: Figure 1.8: Output of Chap1_Example5.py Note: The preceding code is covered in Program Name: Chap1_Example5.py highlightthickness This option represents the width of the highlighted rectangle when the widget has focus. Refer to the following code: Output: The output can be seen in Figure 1.9: Figure 1.9: Output of Chap1_Example6.py Note: The preceding code is covered in Program Name: Chap1_Example6.py padX, padY This option will provide extra space that the widget requests from its layout manager, beyond the minimum, for the display of widget contents in x and y directions. We can see in the previous example, that we have used padding in x and y direction for better look and display. wraplength This option will provide maximum length of line for widgets which will be performing word wrapping. Refer to the following code: Output: The output can be seen in Figure 1.10: Figure 1.10: Output of Chap1_Example7.py Note: The preceding code is covered in Program Name: Chap1_Example7.py height This option will set the desired height of the widget as per need. It must be greater than 1. underline This option represents character index to underline in the widget’s text. The 1st character will be 0, the 2nd character will be, 1 and so on. width This option will set the desired width of the widget as per need, as shown: Output: The output can be seen in Figure 1.11: Figure 1.11: Output of Chap1_Example8.py Note: The preceding code is covered in Program Name: Chap1_Example8.py In the above code, we have set width as 20, height as 2 and underline the 3rd character which is ‘t’. Colors Colors can be represented in tkinter using hexadecimal digits or by standard name. For example, #ff0000 is for Red color or it can be represented by using color = ‘Red’. The different options available for color is are discussed as follows. activebackground This option will set the widget background color when it is active. background This option will set the widget background color and can also be represented as bg, as follows: Output Initially: The output can be seen in Figure 1.12: Figure 1.12: Initial Output Output when button is clicked: The output can be seen in Figure 1.13: Figure 1.13: Output of Chap1_Example9.py Note: The preceding code is covered in Program Name: Chap1_Example9.py On running the preceding code, initially the background color of button is Green and when it is clicked, that is, when the button is active, the background color is changed to Red. activeforeground This option will set the widget foreground color when it is active. foreground This option will set the widget foreground color and can also be represented as fg. Output initially: The output can be seen in Figure 1.14: Figure 1.14: Initial output Output when button is clicked: The output can be seen in Figure 1.15: Figure 1.15: Output of Chap1_Example10.py Note: The preceding code is covered in Program Name: Chap1_Example10.py On running the preceding code, initially the foreground color of button is Blue and when it is clicked, that is, when the button is active, the foreground color is changed to Red. disabledforeground This option will set the widget foreground color when it is disabled, as shown: Output: The output can be seen in Figure 1.16: Figure 1.16: Output of Chap1_Example11.py Note: The preceding code is covered in Program Name: Chap1_Example11.py In the preceding code, the button is disabled and the button's foreground color when it is disabled is Magenta. highlightbackground When the widget does not have any focus, this option will focus on the highlight color. highlightcolor When the widget has focus, this option will set the foreground color of the highlighted region, as shown: Output when there is no focus on Entry: The output can be seen in Figure 1.17: Figure 1.17: Initial output Output when there is focus on Entry: The output can be seen in Figure 1.18: Figure 1.18: Output of Chap1_Example12.py Note: The preceding code is covered in Program Name: Chap1_Example12.py In the preceding example, when there is no focus in Entry, the focus highlight’s color is Red and when there is a focus on Entry, then the color in the focus highlight is Yellow. selectbackground This option will set the background color for the selected items of the widget. selectforeground This option will set the foreground color for the selected items of the widget, as shown: Output: The output can be seen in Figure 1.19: Figure 1.19: Output of Chap1_Example13.py Note: The preceding code is covered in Program Name: Chap1_Example13.py From the preceding code, we can observe that when the text ‘python’ is selected, it is highlighted in Green color in the background and Red color in the foreground. Fonts We can access the font in tkinter by creating a font object or by using a tuple. By creating a font object Suppose we have a text. We can underline the text, change the size, give some font family, overstrike it, and so on. To create a font object, first, we need to import a tkinter.font module and use the Font class constructor: from tkinter.font import Font myobj_font = Font(options,…) The options are: family: This option represents the name of the font family as a string. size: This option represents an integer in points for font height. weight: This option represents ‘bold’ and ‘normal’. slant: This option represents ‘italic’ and ‘unslanted’. underline: This option represents whether the text is to be underlined or not. 1 represents for underline text and 0 for normal. overstrike: This option represents whether the text is overstruck or not. 1 represents overstruck text and 0 for normal. Refer to the following code: Output: The output can be seen in Figure 1.20: Figure 1.20: Output of Chap1_Example14.py Note: The preceding code is covered in Program Name: Chap1_Example14.py We can also view the font family which we can access based on our requirement, as follows: Output: The output is as follows: Note: The preceding code is covered in Program Name: Chap1_Example15.py By using tuple The first element in the tuple is a font family, and the 2nd element is a size in points which is optionally followed by a string having one or more of the style modifiers such as bold, italic, overstrike, and underline. Refer to the following code: Output: The output can be seen in Figure 1.21: Figure 1.21: Output of Chap1_Example16.py Note: The preceding code is covered in Program Name: Chap1_Example16.py Anchors If there is a requirement to position the text relative to the reference point, then we should go for anchors. The possible list of constants used for anchor attributes are: N, S, E, W, NE, NW, SE, SW, CENTER Here, N stands for North, S for South, E for East and W for West. Refer to Figure 1.22: Figure 1.22: Anchor Constants Whenever we are creating a small widget inside a large frame and use anchor = SW option, then the widget will be placed in the bottom left corner of the frame. If we use anchor = S, then the widget would be centered along the bottom edge. Placing widget position when anchor = N Refer to the following code: Output: The output can be seen in Figure 1.23: Figure 1.23: Output of Chap1_Example17.py when anchor position is N Note: The preceding code is covered in Program Name: Chap1_Example17.py Note: From Figure 1.24 to Figure 1.31, the code will be the same except the option at anchor position will be changed. Placing widget position when anchor = S Refer to Figure 1.24: Figure 1.24: Output when anchor position is S Placing widget position when anchor = E Refer to Figure 1.25: Figure 1.25: Output when anchor position is E Placing widget position when anchor = W Refer to Figure 1.26: Figure 1.26: Output when anchor position is W Placing widget position when anchor = NE Refer to Figure 1.27: Figure 1.27: Output when anchor position is NE Placing widget position when anchor = NW Refer to Figure 1.28: Figure 1.28: Output when anchor position is NW Placing widget position when anchor = SE Refer to Figure 1.29: Figure 1.29: Output when anchor position is SE Placing widget position when anchor = SW Refer to Figure 1.30: Figure 1.30: Output when anchor position is SW Placing widget position when anchor = CENTER Refer to Figure 1.31: Figure 1.31: Output when anchor position is CENTER Relief styles Whenever we desire to have 3-D simulated effects around the outside of the widget, then we will go for the relief style of a widget. Relief attributes can have a possible list of constants such as flat, raised, groove, sunken, and ridge. Refer to the following code: Output: Refer to Figure 1.32: Figure 1.32: Output of Chap1_Example18.py Note: The preceding code is covered in Program Name: Chap1_Example18.py Bitmaps This attribute is used to display a bitmap and the available bitmaps are ‘error’, ‘gray12’, ‘gray25’, ‘gray50’, ‘gray75’, ‘info’, ’hourglass’, ‘warning’, ‘question’, and ’questhead’. Refer to the following code: Output: Refer to Figure 1.33: Figure 1.33: Output of Chap1_Example19.py Note: The preceding code is covered in Program Name: Chap1_Example19.py Cursors Whenever there is a requirement to show different mouse cursors based on the need whose exact graphic may vary depending on the operating system, then there is an option of cursor attribute, out of which, some useful ones are ‘arrow’, ‘clock, ‘cross, ‘circle’, ‘heart’, ‘mouse’, ‘plus’, ‘star’, ‘spider’, ‘sizing’, ‘shuttle’, ‘target’, ‘tcross’, ‘trek’, ‘watch’ and so on. Refer to the following code: Output: Refer to Figure 1.34: Figure 1.34: Output of Chap1_Example20.py Note: The preceding code is covered in Program Name: Chap1_Example20.py Python tkinter geometry management All widgets in the tkinter can access geometry management methods. To organize the widgets in the parent windows, the geometry configuration of the widgets is to be accessed, which is offered by tkinter. It will help in managing the display of widgets on the screen. The geometry manager classes are discussed as follows. pack() It is one of the easiest to use, compared to the other 2 geometry managers. Before placing the widgets in the parent widget, the geometry manager will organize the widgets in blocks. Whenever there is a simple application requirement, such as arranging the number of widgets on top of each other or placing them side by side, then we can go for the preceding geometry manager. As compared to the other two geometry managers, it comes with limited options. The syntax is widget.pack(options,…) The options are: fill: This option will determine whether the widgets can increase or grow in size or not. By default, it is NONE. If we want to fill vertically, then it is Y. If horizontally, then it is X. If required both horizontally or vertically, then BOTH. expand: This option will expand the widget to fill any space when set to true or 1. When the window is resized, the widget will expand. side: This option will decide the widget alignment, that is, against which side of the parent widget packs. By default, it is TOP. The others are BOTTOM, LEFT, or RIGHT. The other options are anchor, internal (ipadx, ipady) or external padding (padx, pady) which all have defaulted to 0. Refer to the following code: Output: The output can be seen in Figure 1.35: Figure 1.35: Output of Chap1_Example21.py Note: The preceding code is covered in Program Name: Chap1_Example21.py grid() This geometry manager will organize the widgets into a 2-Dimensional table, into a number of rows and columns in the parent widget. An intersection of imaginary rows and columns is a cell where each cell in the table can hold a widget. The syntax is widget.grid(options,…) The options are as follows: column: This option will use a cell which will be identified with a given column, whose default value is the leftmost column with a numeric value of 0. columnspan: This option will indicate the number of columns the widget occupies; whose default value is 1. padx: This option will add padding to the widget horizontally outside the border of the widget. pady: This option will add padding to the widget vertically outside the border of the widget. ipadx: This option will add padding to the widget horizontally inside the border of the widget. ipady: This option will add padding to the widget vertically inside the border of the widget. row: This option will use a cell that will be identified with a given row whose default value is the first row with numeric value of 0. rowspan: This option will indicate the number of rows the widget occupies whose default value is 1. sticky: Whenever the cell is larger than the widget, an indication is required for the sides and cell corners to which the widget sticks. It may be a string concatenation of 0 or more of compass directions: M, E, S, W, NE, NW, SE, SW, and 0. The widget is centered in the cell with sticky = " and will take up the full cell area when NESW. Kindly observe the given code: Output: The output can be seen in Figure 1.36: Figure 1.36: Output of Chap1_Example22.py Note: The preceding code is covered in Program Name: Chap1_Example22.py Note: It is not recommended to mix grid() and pack() in the same master window. place() It simpler than the other 2 geometry managers. This geometry manager will organize the widgets in a specific position in the parent widget. It is placed at some specific position in the parent widget. It can be used with pack() as well as grid() method. The syntax is widget.place(options,…) The options are: anchor: This option will indicate where the widget is anchored to and has compass directions as: N, S, E, W, NE, NW, SE, or SW, which are related to the sides and corners of the parent widget. The default compass direction is NW. bordermode: This option will indicate whether the widget border portion is included in the coordinate system or not. The default is INSIDE and the other is OUTSIDE. relheight: This option will specify the height as a float between 0.0 and 1.0, which is a fraction of the parent widget height, that is, the widget’s height relates to the parent’s widget height by ratio. relwidth: This option will specify the width as a float between 0.0 and 1.0, which is a fraction of the parent widget width, that is, the widget’s width relates to the parent’s widget width by ratio. height: This option will specify the widget height in pixels. width: This option will specify the widget width in pixels. relx: This option will specify the horizontal offset as a float between 0.0 and 1.0 which is a fraction of the parent widget width, that is, widget will be placed by x ratio relative to its parent. rely: This option will specify the vertical offset as a float between 0.0 and 1.0, which is a fraction of the parent widget height, that is, widget will be placed by y ratio relative to its parent. x: This option will specify the horizontal offset in pixels. y: This option will specify the vertical offset in pixels. Note: In the above geometry manager, at least 2 options are required when invoked. Just observe the following example: Output: The output can be seen in Figure 1.37: Figure 1.37: Output of Chap1_Example23.py Note: The preceding code is covered in Program Name: Chap1_Example23.py Geometry method in tkinter Whenever there is a requirement to set tkinter window dimensions as well as set the main window position, then tkinter provides a geometry method, as follows: Output: The output can be seen in Figure 1.38: Figure 1.38: Output of Chap1_Example24.py Note: The preceding code is covered in Program Name: Chap1_Example24.py When we will run the preceding code, a fixed geometry of the tkinter window is created with dimensions ‘300x150’. Moreover, the tkinter window size will be changed but the screen position will be the same. What if we are in need to change the position? We can do it by preforming a little tweaking in the code as shown: Output: The output can be seen in Figure 1.39: Figure 1.39: Output of Chap1_Example25.py Note: The preceding code is covered in Program Name: Chap1_Example25.py Now, when we will run the preceding code, then both the position and size are changed. We can see that the tkinter window is appearing in a different position (400 shifted on each X and Y axis). An important point to note is that the variable argument must be in the form of (variable1)x(variable2), otherwise an error will be raised. Conclusion In this chapter, we learned initially about basic GUI python program creation using tkinter library. Then we saw standard attributes of Python tkinter GUI such as dimensions, colors or fonts, along with various options with examples. We learned how to position the text with list of constants relative to the reference point using anchor attribute. We also saw an example of relief attribute, which brings 3-D simulated effects around the outside of the widget. The bitmap and cursor attribute were also explored with a crystal- clear example. Finally, towards the end of this chapter, we learned how to access tkinter widgets using inbuilt layout geometry managers viz pack, grid and place with syntax and its various options. Points to remember Import tkinter library first for creation GUI applications using this library. Dimension set to an integer is assumed to be in pixels. Representation of colors in tkinter can be done in hexadecimal digits or by standard name. Font in tkinter can be accessed using a font object or by using a tuple. The text position relative to the reference point can be done using anchor attribute. 3-D simulated effects around the outside of the widget can be done using relief style. Widgets position using absolute positioning can be done using place geometry manager. Widgets in horizontal and vertical position is organized using pack geometry manager. Widgets in a 2-D grid can be positioned using grid geometry manager. Questions 1. Write short note on GUI designing using the tkinter package. 2. Draw and explain the application level of Python. 3. Write a basic Python GUI program and explain its structure. 4. Explain any five standard attributes of Python tkinter GUI. 5. Explain in detail how the color is represented in tkinter, and explain any 5 options available for color representation. 6. Explain how fonts access is done in tkinter library of Python. 7. Draw and explain anchor constant in Python. 8. To have 3-D simulated effects around the outside of the widget, what style of a widget should be used? Explain in detail. 9. Write short notes on the following: a. Bitmaps b. Cursors 10. Explain Python tkinter Geometry Manager and its classes. 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 CHAPTER 2 Inbuilt Variable Classes for Python tkinter GUI Widgets Introduction This chapter will deal with inbuilt variable classes for Python tkinter GUI widgets and will also demonstrate the creation of a simple GUI Windows app using classes and object concepts. We will also be learning how to access and set pre-defined variables sub- classed from the tkinter variable class viz StringVar, IntVar, DoubleVar, and BooleanVar. Structure In this chapter, we will discuss the following topics: Inbuilt variable classes StringVar() BooleanVar() IntVar() DoubleVar() GUI creation using classes and objects Objectives By the end of this chapter, the reader will learn how to store data associated with widgets in tkinter, by using variable classes such as StringVar(), BooleanVar(), IntVar() and DoubleVar() for storing string, Boolean, integer and floating point values respectively. Finally, we shall see the importance of Tkinter's classes and objects which can be used to create GUIs, thus improving the code's organization, maintainability, and reusability, which also offers flexibility and aids in lowering the complexity of the code. Inbuilt variable classes A variable is needed with a wide variety of widgets. Whenever a user enters some text in the Entry widget or Text widget, a string variable is needed to track the written text. If there is a Checkbox widget, a Boolean variable is needed to track whether the user has checked or not. If the user requires some value in the Spinbox or Slider widget, then an integer variable is required to track the value. There is a Variable class in the tkinter which responds to changes in widget-specific variables. The commonly used pre- defined variables which are subclassed from the tkinter variable class are StringVar, BooleanVar, IntVar, and DoubleVar. We can associate one variable with more than one widget so that the same information can be displayed by more than one widget. Moreover, when the values are changed, the functions can be binded which are to be called. Methods such as get() and set() will be used to retrieve and set the values of these variables. StringVar() This variable will hold a string and the default value is an empty string, as follows: Output initially and when text is written: The output can be seen in Figure 2.1: Figure 2.1: Initial Output Output when Get Data! button is clicked: The output can be seen in Figure 2.2: Figure 2.2: Output of Chap2_Example1.py Note: The preceding code is covered in Program Name: Chap2_Example1.py Output when a program is stopped or when ‘x’ is clicked: The output is as follows: In the preceding code, we have created two widgets: Entry and Button, in the parent widget and we are demonstrating the usage of the tkinter StringVar() type. In S1, an instance of StringVar() type is created and is assigned to the Python mystr variable. In S2, the type is. Then we are writing some text in the Entry widget and click the button Get Data! In S3, we are using the variable mystr to get the value, saving it to a new variable named mydata and then displaying its value. In S4, we are using the variable mystr to call the set() method on StringVar() and setting it to an empty string "". An important point to observe is that we have used textvariable option, as it will associate a tkinter variable to the entry field contents. We will learn about other options associated when we will be dealing with the widgets in detail. BooleanVar() This variable will hold a Boolean and will return 1 for True and 0 for False, as shown: Output when checkbutton is checked: The output can be seen in Figure 2.3: Figure 2.3: Output Output when checkbutton is Unchecked: Refer to Figure 2.4: Figure 2.4: Output of Chap2_Example2.py Note: The preceding code is covered in Program Name: Chap2_Example2.py In the preceding code, when the user checks, the output will return True. Otherwise, on unchecking, it will return False. IntVar() This variable will hold an integer and the default value is 0, as shown below. If values are entered in fraction, the value will be truncated to an integer. Output when no data is entered: Refer to Figure 2.5: Figure 2.5: Output Output when data is entered: Refer to Figure 2.6: Figure 2.6: Output of Chap2_Example3.py Note: The preceding code is covered in Program Name: Chap2_Example3.py DoubleVar() This variable will hold a float and the default value is 0.0, as shown: Output when no data is entered: Refer to Figure 2.7: Figure 2.7: Output Output when data is entered: Refer to Figure 2.8: Figure 2.8: Output of Chap2_Example4.py Note: The preceding code is covered in Program Name: Chap2_Example4.py However, in the preceding code and the previous code of IntVar() variable class, we are entering numbers only. However, the user may enter anything in the Entry widget. So, we need to provide some checks such that the user may validate the Entry widget with numeric values only. We will learn when we will be dealing with widgets. For some time now, just observe the concept of variables. GUI creation using classes and objects As we have seen till now, it is very easy to create a basic GUI with a code of few lines only using tkinter. However, when the programs become complex, it is quite difficult to separate logic from each part. We need to make our code clean with an organized structure. Consider the following code: Output: Refer to Figure 2.9: Figure 2.9: Output Output on clicking Display button: Refer to Figure 2.10: Figure 2.10: Output of Chap2_Example5.py Note: The preceding code is covered in Program Name: Chap2_Example5.py In the preceding code, a main window is created having a Button widget. A message is being displayed as ‘Python’ when the Display button is clicked. The button widget is placed with a padding of 20px on the horizontal axis and 30px on the vertical axis. On executing the preceding code, we can verify that it is working as expected. We can see that all the variables are defined in the global namespace. However, it becomes and more difficult to reason about the parts usage when more widgets are added. Such type of issues can be addressed with basic OOP techniques. Now, we will define a class that will wrap up our global variables: Output: Refer to Figure 2.11: Figure 2.11: Output Output on clicking Display button, output will be: Refer to Figure 2.12: Figure 2.12: Output of Chap2_Example6.py Note: The preceding code is covered in Program Name: Chap2_Example6.py In the preceding code, we defined MyBtn class as a Tk subclass. To initialize the base class properly, the __init__() method of the Tk class is called with the built-in super() function. We have a reference to the MyBtn instance with the self-variable, and so the Button widget is added as an attribute of our class. The instantiation of the Button is separated from the callback, which gets executed when it is clicked. It is a common practice in executable Python scripts to use if __name__ == "__main__" which is an entry point of any program. To show the main window itself, we are calling the mainloop method inside if __name__ == "__main__" block. So, we can make any large Python code by taking note of the usage of classes and objects to create GUI applications. The advantages of GUI creation using classes and objects in tkinter are as follows: Encapsulation: By using classes, we may encapsulate a GUI's functionality in a single class, simplifying the organization and maintenance of the code. Additionally, it lessens the complexity of the code and prevents naming disputes. Reusability: We can construct reusable code that can be utilised in other apps or sections of an application by defining classes and objects. Modularity: Classes and objects facilitate code modularization by making it simpler to divide different elements of a GUI, such as the design and the functionality. Inheritance: Subclasses that are created through inheritance will take on the parent class's attributes and functions. When building similar GUI elements with somewhat differing functionality, this can save time and effort. Flexibility: Classes and objects give us the ability to tweak and update GUIs since they let us make code changes without having an impact on other areas of the program. Code organization: It helps us in organizing the code more clearly and makes it understandable by using classes and objects. When problems develop, it could also make it simpler to troubleshoot the code. Conclusion In this chapter, we learned different approaches of data storage associated with widgets in tkinter by using variable classes such as StringVar(), BooleanVar(), IntVar() and DoubleVar() for storing string, Boolean, integer and floating point values respectively with python code. We have seen two approaches of displaying an application with and without usage of Tkinter's classes and objects for creating GUIs. Finally, we can say that the approach of using classes and objects for GUI creation helps us in improving the code's organization, maintainability, reusability and aids in lowering the complexity of the code. Points to remember For storing and manipulating string values and for representing the text or widgets value like Entry and label, we may use StringVar() variable. For storing Boolean values and for representing the state of Checkbuttons or radiobuttons, we may use BooleanVar() variable. For storing integer values and for representing the widget’s value like Spinbox or Scale, we may use IntVar() variable. For storing floating point values and for representing the widget’s value like Spinbox or Scale, we may use DoubleVar() variable. GUI application creating in tkinter using classes and objects offers several advantages such as encapsulation, reusability, modularity, inheritance, flexibility and code organization. Questions 1. Explain in detail about inbuilt variable classes for Python tkinter GUI widgets. 2. Explain the use of inbuilt variable classes for designing GUI in Python. 3. Explain the use of StringVar() in Python with a suitable example. 4. Which variable is used to return 1 for True and 0 for False values in Python for GUI? Explain in detail. 5. Explain IntVar() in detail with a suitable example. 6. Explain DoubleVar() in detail with a suitable example. 7. Write a short code for GUI Creation using Classes and Objects. What are its advantages? 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 CHAPTER 3 Getting Insights of Button Widgets in tkinter Introduction A standard Graphical User Interface (GUI) element, which are basic building blocks of any GUI program are termed as widgets. We have observed till now that a top-level root window object contains different small window objects which are part of our developed GUI application. We put all the widgets in top-level window. We can have more than one top- level window, but can have only one root window. We shall see different widgets one by one now with starting from different widgets related to button in tkinter. Structure In this chapter, we will discuss the following topics: tkinter Button Widget tkinter Checkbutton Widget tkinter Radiobutton Widget tkinter OptionMenu Widget Objectives By the end of this chapter, the reader will learn about one of the most commonly used GUI widgets viz tkinter Button widget. We will be viewing the binding of events to the above widget with multiple examples and different methods including lambda expressions. Next, we shall look into the Checkbutton widget, which will give the provision to the user to select more than one option. Users will also view different options to get the image in this widget. Next, we will see how to use the tkinter Radiobutton widget. Users will view various examples where exactly one of the predefined sets of options will be chosen. Last but not the least, we will explore the tkinter Option-Menu 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. tkinter Button Widget One of the most commonly used GUI widgets in tkinter Python is the Button widget. A method or a function can be associated with this widget when clicked. Different options can be set or reset as per need. This widget is generally used for interaction with the user. The syntax is: mybtn1= Button(myroot , options…) where, myroot is the parent window. Some of the lists of options that can be used as key-value pairs and are separated by commas are activebackground, activeforeground, bg, bd, command, fg, font, height, highlightcolor, justify, image, padx, pady, state, relief, width, wraplength, and underline. We have seen most of the options but some undiscussed options are as follows: command: This option will call the function or method whenever the button is clicked. So, by using the command option, we are adding functionality to the button. justify: This option will define the alignment of multiple lines of text with respect to each other. The default is CENTER and the other is LEFT or RIGHT. Refer to the following code: Output: The output can be seen in Figure 3.1: Figure 3.1: Output Output when JUSTIFY LEFT button is clicked: Refer to Figure 3.2: Figure 3.2: Output Output when JUSTIFY RIGHT button is clicked: Refer to Figure 3.3: Figure 3.3: Output Output when JUSTIFY CENTER button is clicked: Refer to Figure 3.4: Figure 3.4: Output Note: The preceding code is covered in Program Name: Chap3_Example1.py Let us go over the various options now: image: This option will set the image to be displayed on the button instead of text. state: This option, by default, is NORMAL. When this option is set to DISABLED, the button becomes unresponsive and will gray out the button. Note: User may use 'Add-icon.png' or any other icon file as per need in their active directory. Here, we have added ‘Add-icon.png’ file as a reference. Refer to the following code: Output: Refer to Figure 3.5: Figure 3.5: Output Output when button is clicked: Refer to Figure 3.6: Figure 3.6: Output Note: The preceding code is covered in Program Name: Chap3_Example2.py In the above code, we have added an image with a ‘+’ symbol to a button and when it is clicked, the button becomes disabled. An important point to note is that only the image will appear on the screen when both text and image are given on the Button, as the text will be dominated by the image. But what if we want to display both text and image on the button? In such cases, we will be using the compound option in the button widget. Suppose we want the image to appear at bottom of the button. In this case, compound = BOTTOM. Similarly, when compound = LEFT, the image will appear on the left side of the button widget; when compound = RIGHT, the image will appear on the right side of the button widget, and when compound = TOP, the image will appear on the top side of the button widget. Let us see the code for a better understanding: Output: Refer to Figure 3.7: Figure 3.7: Output of Chap3_Example3.py Note: The preceding code is covered in Program Name: Chap3_Example3.py Now, we will discuss events and bindings before moving on to the next widgets. Events and bindings We have seen in all the examples till now that until and unless we press the ‘X’ mark of a parent widget, a tkinter code is spending most of the time inside an event loop (the mainloop method). We can see events such as mouse click, focusin, focusout, keypress events, and so on. In order to bind an event with a function, a bind() function is used, which is included in all the widgets whose syntax is given as: widget.bind(event,handler, add = '') Here, an event can be attached binding to a widget using the bind method. The first argument event is a representative string that must be in the following format: : Here, the modifier and detail sections are optional and the only mandatory part is the type section which represents the event type to listen for. We will discuss each section one by one. event modifiers: They can change the circumstances in which an event’s handler is activated and is an optional component for creating an event binding. We should note that most of the event handlers are platform specific and will not work on all platforms. Shift: While the event is occurring, the shift button needs to be pressed. Control: While the event is occurring, the Control button needs to be pressed. Alt: While the event is occurring, the Alt button needs to be pressed. Lock: When the event occurs, the caps lock button needs to be activated. Double: The event will be happening twice in quick succession, say double-click. Triple: The event will be happening thrice in quick succession. Quadruple: The event will be happening four times in quick sucession. event type The different event types in tkinter are as follows: ButtonPress or Button: An event will be generated or activated when a mouse button has been clicked. Event defines the left mouse button, Event defines the middle button, Event defines the right mouse button, Event defines scroll-up on mice with wheel support, Event defines scroll-down on mice with wheel support. ButtonRelease: An event will be generated or activated when a mouse button has been released. Events , and will specify the left, middle, or right mouse button. Keypress or Key: An event will be generated or activated when a keyboard button has been pressed. KeyRelease: An event will be generated or activated when a keyboard button is released. Motion: An event will be generated or activated when the mouse cursor is moved across the widget. Events , and will specify the left, middle, or right mouse button. The mouse pointer's current position will be provided in the x and y members of the event object passed to the callback, that is, event.x, event.y. Enter: An event will be generated or activated when the mouse cursor enters the widget. Leave: An event will be generated or activated when the mouse cursor leaves the widget. FocusIn: An event will be generated or activated when the widget gains the input focus. FocusOut: An event will be generated or activated when the widget loses the input focus. Configure: An event will be generated or activated when the widget configurations are changed such as width, height, or border width being adjusted by the user, and so on. Mousewheel: An event will be generated or activated when the mouse wheel is scrolled. Event details: It is an optional section and will serve as either a mouse button or a certain key on the keyboard being pressed. For keyboard events: The keyboard event detail is captured such that each key pressed on the keyboard will be represented by a key symbol or key letter itself. The ASCII value of the specific key is given for triggering the event when using Key, KeyPress, or KeyRelease. For mouse events: The mouse event detail is captured such that numeric detail from 1 to 5 will represent the specific mouse button we wish to have to handle the trigger. The second argument is a handler which represents the function name to call (callback function) when the event occurs. It takes an event parameter. The attributes for the mouse events are as follows: x and y: It will return the x and y coordinate mouse position in pixels where events such as Buttons occur. x_root and y_root: It is similar to x and y but is relative to the upper- left screen corner. num: It returns the mouse button number. The attributes for the keyboard events are: char: It is for keyboard events only and pressed character as a string. keysym: It is for keyboard events only and pressed key symbol. keycode: It is for keyboard events only and pressed key code. As the event handler, the function included will be passed as an event object which will describe the events and include details about the event which was triggered. So, a parameter is to be included which will be assigned to this object in the function. The third parameter, which can be None, is added to replace the callback if there was a previous binding or ‘+’ to preserve the old ones and add the callback. Now, if we want to bind an event to a widget instance, then it is called instance-level binding. There are times when it is needed to bind events to an entire application, which is called application-level binding where the same binding is used across all the windows and application widgets as long as any one application window is in focus. The syntax of application-level binding is: widget.bind_all(event,callback) For example: myroot.bind_all('', show_help) Here, if we press the F1 key and then the show_help callback will always trigger, irrespective of any widget the focus as long as the application is under active focus. Another is class-level binding where the events can be bound at a particular class level. The syntax of class-level binding is: widget.bind_class(classname, event,callback) For example, mye1.bind_class('', '', copy) Here, all the Entry widgets will be bound to the event which would call a method called 'copy (event)'. We shall see some examples related to buttons, events, and bindings for a better understanding of the concepts. Initial output: Refer to Figure 3.8: Figure 3.8: Output Output when LeftClick button is clicked using the left side of the mouse: Refer to Figure 3.9: Figure 3.9: Output Output when RightClick button is clicked using the mouse right side after clicking the mouse left side: Refer to Figure 3.10: Figure 3.10: Output Note: The preceding code is covered in Program Name: Chap3_Example4.py In this code, we bind the button widget to the event which corresponds to the mouse left click. Whenever this event will occur, the method mycall will be called, which will be passing an object instance as its argument. The method mycall(event) will take an event object generated by the event as its argument. So, when the left button of the mouse is clicked on LeftClick button, then the Left Clicked message will be displayed. We bind the button widget to the event

Use Quizgecko on...
Browser
Browser