Press enter to skip the top menu

Python Advanced

NCEA Compatibility

For the module "AS91906: Use complex programming techniques to develop a computer program" this lesson meets the following requirements

Go to top

Learning Outcomes

By the end of this lesson, you will be able to:

Go to top

Introduction

This lesson focuses on building a Graphical User Interface (GUI) to collect data, specifically employee information, and then save that data. It uses Python's tkinter library to create the GUI elements such as labels, entry fields, and buttons. The lesson will guide you through the process of setting up the GUI, explaining the purpose of different widgets and how they interact. You'll learn how to create entry fields for data input, labels to guide the user, and buttons to trigger actions like saving data to a list or a file. The lesson also touches on the use of StringVar and DoubleVar to manage data within the GUI, as well as how to link button actions to specific functions.

Go to top

Building your first GUI

This lesson concentrates of building a GUI form that will collect payroll data from a user. The data collected will be the employee's name, their IRD number, the hours they worked and their hourly rate.

For this to take place controls will be added to the form. In Python parlance these controls are referred to as widgets. The widgets to be added are:

Now let us start examining the code.

Importing libraries

Listing 2-1
                        import tkinter as tk
                        from tkinter import *
                    

This section of the code imports the resources required for our program. Line1 imports the module tkinter. This module contains all the required classes for building a GUI form.

Line 2 imports other modules from tkinter that are also requred for our form.

Go to top

GUI and and bridging objects

Listing 2-2
                        def createPayroll(): 
                            root = Tk()                        
                            frame1 = Frame(root, width = 420, height = 240)
                            frame1.pack()
                        
                            varName=StringVar()              
                            varIRD=StringVar()              
                            varHours=DoubleVar()                    
                            varRate=DoubleVar()                   
                            
                    

At line 8 an object of the class Tk() is created and a pointer to it is stored in root. This is to be the overall controller of our GUI element.

At line 6 an object of the class Frame is created. This is controlled by the Tk() object. Its width and height parameters specify the width and height of the form in pixels.

At line 7 the pack() method is used to position the Frame object.

Before we discuss lines 9 - 12 we need to digress a little and discuss some of Python's data types and how they relate to GUI forms.

Here is a list of the most common Python data types:

...and the list goes on.

In a Python form we are provided with widgets for entering data directly from the keyboard. These widgets are objects of the class Entry. This class has only one data type: text. Whether you type in letters or numbers, they are all stored as text. To complicate things further text data itself differently in Entry objects than in Python.

To solve this issue we have a number of classes that act as intermediaries between the Entry objects and Python. These classes are StringVar() and DoubleVar(). The former is used for text data and the latter for numbers. These classes are used to bridge the gap between the text data in the Entry objects and the Python data types.

At lines 9 - 12 we create four objects of the classes StringVar() and DoubleVar(). These objects are used to bridge the gap between the Entry objects and Python.

Go to top

Labels

Listing 2-3
                          nameLabel=tk.Label(master=frame1,text='Full Name',width=15, anchor=E) 
                          nameLabel.place(x = 40, y = 10)                        
                          irdLabel=tk.Label(master=frame1,text='IRD Number',width=15, anchor=E)                        
                          irdLabel.place(x = 40, y = 45)                                            
                          hoursLabel=tk.Label(master=frame1,text='Hours Worked',width=15, anchor=E)                        
                          hoursLabel.place(x = 40, y = 80)                        
                          rateLabel=tk.Label(master=frame1,text='Hourly Rate',width=15, anchor=E)                   
                          rateLabel.place(x = 40, y = 115)                        
                    

In the above block we are creating four Label widgets. As you can see the creation of each Label widget takes 2 lines. The first line of the first widget is reproduced below.

nameLabel=tk.Label(master=frame1,text='Full Name',width=15, anchor=E)

What we have stated above also applies to lines 19 - 25

Go to top

Entry objects

Listing 2-4
  
                          txtName=tk.Entry(master=frame1,relief=RAISED, textvariable=varName,width=15,bg="#ffffff", bd=1)
                          txtName.place(x = 180, y = 10)                        
                          txtIRD=tk.Entry(master=frame1,relief=RAISED, textvariable=varIRD,width=15,bg="#ffffff", bd=1)                        
                          txtIRD.place(x = 180, y = 45)
                        
                          txtHours=tk.Entry(master=frame1,relief=RAISED, textvariable=varHours,width=15,bg="#ffffff", bd=1)                        
                          txtHours.place(x = 180, y = 80)                        
                        txtRate=tk.Entry(master=frame1,relief=RAISED, textvariable=varRate,width=15,bg="#ffffff", bd=1)                        
                          txtRate.place(x = 180, y = 115)
                    

What we have stated above also applies to lines 29 - 37

Go to top

Buttons

Buttons are widgets that we are all familiar with. We click on one of them and something happens: a new window pops up, data is saved to a file or the current application is terminated. Here we have two buttons: one to add our newly created objects to a list and a second one for serialising the contents of that list to a file.

Listing 2-5
                          calculateButton=Button(master=frame1,text='Save to list', width = 20, command=lambda:saveToList(varName.get(), varIRD.get(), varHours.get(),varRate.get()))  
                          calculateButton.place(x = 120, y= 150)                        
                        
                          calculateButton=Button(master=frame1,text='Save to File', width = 20, command=lambda:saveToFile())                        
                          calculateButton.place(x = 120, y= 180)                                              
                        
                    

At line 33 we create a button object. Like all the other widgets the button is placed in the frame1 frame. The text, 'Save to list' specifies what appears on the button. The width parameter uses character width to specify the width of the button. The command parameter specifies which of the two functions spanninng lines is to run when the button is clicked. The lambda keword specifies that the function will run only when the button is clicked. The attachment to lambda is the name of the function and the parameters that are to be passed to it. In this case the parameters will be the values of the employee name, IRD number, hours worked and hourly rate.These values are extracted from the StringVar and DoubleVar objects that are linked to the Entry objects.

Line 34 positions the buttons on the form, using pixels as measuring units.

The code at lines 36 and 37 is is explained in the same way.

Go to top

Form Functions

Listing 2-6: creating functions
                            def saveToList(name, ird, hours, rate):
                                print(name, ird, hours, rate)
                                return
                        
                            def saveToFile():
                                print("Save to file")
                                return 
                        
                            root.title("Payroll")
                            root.mainloop()   
                        
                        createPayroll() 
                    

The above code finishes our form

The function saveToList() is the function that runs when the button labelled "Save to List" is clicked. We shall be using this function later when we expand our program to save data to a list. Here,however, we are using it print the values entered by the user as a demonstration that the form we have just built is working correctly. We pass it the values entered by the user for the employee's name, their IRD number, hours worked and hourly rate. The functions simply prints those values.

The function saveToFile() hardly needs and explanation.

At line 47 the heading on the window is set to "Payroll"

At line 48 we have the mainloop() function. This simply allows the form to stay on the screen until the user deliverately closes it. Without it each ine of code would be executed once and then stop.

The code spanning lines 1 - 48 is one single function named "createPayroll()". As a function it can't run unless it is called. This call is made at line 50.

GUI Form
Figure 2-1: The data entry form
Go to top

Summary

The file is a lesson focused on creating Graphical User Interfaces (GUIs) in Python, specifically for data input. It's designed to teach the basics of building a GUI using the tkinter library.

Key Concepts and Skills Covered:

  • GUI Creation with tkinter: The lesson guides the user through the process of creating a basic GUI window and adding elements to it.
  • Widgets: It explains the use of various tkinter widgets, including:
    • Frame: To organize and group other widgets.
    • Label: To display text for the user.
    • Entry: To allow users to input text.
    • Button: To trigger actions when clicked.
  • Data Handling: The lesson demonstrates how to use StringVar and DoubleVar to manage data associated with Entry widgets, bridging the gap between tkinter's text-based data and Python's data types.
  • Layout Management: It shows how to use the place() method to position widgets within the GUI.
  • Event Handling: The lesson introduces the concept of event handling by linking button clicks to functions that are executed when the button is pressed.
  • Application Context: The example used in the lesson is building a simple payroll application, where the GUI is used to collect employee data (name, IRD number, hours worked, hourly rate).
  • NCEA Compatibility: The file notes that the lesson is compatible with specific requirements for the NCEA (National Certificate of Educational Achievement) in New Zealand, specifically relating to GUI programming and data collection.

In essence, the file provides a hands-on introduction to building a basic GUI application in Python using tkinter, focusing on the fundamental elements needed for data input.

Go to top

Revision

Go to top

Multi choice

Fill in the blanks

Go to top

Assignment

Go to top