Entry Widget

What is Tkinter Entry Widget

Tkinter Entry Widget is a tkinter class that is used to get input (text string) from the user. The Entry Widget allows the user to enter a single line of text in a single font.

Entry Widget can be used anywhere the user needs to provide a single-line string such as a name, address, password, etc. To enter multiple lines of text, Tkinter has another widget called Text.

The Entry Function

The Entry widget is created using Entry function:

name = StringVar()
entryWidgetName = Entry(parent, textvariable=name)

StringVar() is the text you want to appear on the Entry widget. StringVar()is stored in the variable “name“.

textvariable specifies the name of a global variable, whose value is a text string. This text string is displayed in the entry widget. A textvariable is a variable linked to the Entry. When the variable is changed, the entry will be updated.  Also, when the user changes the entry, the variable will be updated.

parent“: On this website, we use “root” as the “parent”. “root” represents the widget’s parent window and is the highest-level GUI component.

Entry Widget Common Options

The Tkinter Entry widget provides many options that allow the programmer to define the look and format of the entry widget. These options are passed as parameters separated by commas when the entry widget is created. 

Some of the common configuration options for Entry widget are the following:

  • Width:  The “width” configuration option lets you specify the width of the Entry widget. The width of the Entry widget is the number of characters you would like to have in the Entry widget.
  •  bd: Sets the border width in pixels.
  • bg: Sets the normal background color.

The .grid Geometry Manager

A Geometry Manager tells Tkinter how to show the containers and the widgets on the screen and where the user can input the data. 

You got an introduction to the Geometry Manager in the Tkinter Graphics Programming chapter. The Geometry Manager is discussed in more detail in this section.

Python has three Geometry Managers (pack, grid, and place). We used the pack() method in the earlier tkinter programs. For the Entry widget program, we will use the grid method.

The grid method divides the Frame window similar to graph paper.  The following Table shows the grid numbering scheme.  Each intersection of a row and column is called a cell as indicated in the table below.

You will see how we use the grids and cells in the program below.

Table Showing Tkinter Grids

COLUMN 0COLUMN 1COLUMN 2
Row 0Cell Column 0, Row0Cell Column 1, Row0Cell Column 2, Row0
Row 1Cell Column 0, Row1Cell Column 1, Row1Cell Column 2, Row1
Row 2Cell Column 0, Row2Cell Column 1, Row2Cell Column 2, Row2
Geometry Manger Grid

.grid has the following syntax to display a widget named ‘widget1’  on your application screen :

    Widget1.grid(option=value, option = value …)

option is described in the argument list below.

Arguments for .grid Geometry Manager

The .grid Geometry Manager has many arguments. The table below lists some of them.

The program example in this section uses some of the arguments described in the Table.

Table: List of .Grid Arguments

ARGUMENTDESCRIPTION
ColumnColumn number where you want to place the widget
RowRow number where you want to place the widget
IpadxPadding added inside the widget in the x-direction
IpadyPadding added inside the widget in the y-direction
padxPadding added external to the widget in the x-direction
padyPadding added external to the widget in the y-direction
StickyThis option determines how to put the text in the cell.
N: top-center;
S: bottom-center,
E: right-center;
W: left-center;
NE: top-right;
SE: bottom-right;
SW: bottom-left;
NW: top-left.
Geometry Manager .grid Arguments

Entry Widget Use Example

You may have filled out forms or an application on the Internet. These forms generally have specific locations where you enter your name, address, etc. These locations are called entry boxes.

The following is a simple program that creates an Entry widget. The program makes a simple form with two locations for you to enter your first and last names using the Entry widget.

PROGRAM EXAMPLE: ENTRY WIDGET USE EXAMPLE
from tkinter import *
root = Tk() # set up main window 'root'.
# Give the main window a title 'Entry Widget'.	#1)
root.title('Entry Widget')  
# Set up frame widget to hold contents of our user interface 
# and put it in our main window.
frm = Frame(root)   				#2)
frm.grid(column=0, row = 0, sticky =(N, W, E, S)) #3)
# Create Entry widget where the user can type text
Entry(frm, width = 16, background =
      'red').grid(column=2, row=1, sticky=(W, E)) #4)
Entry(frm, width = 16, background =
      'lightgreen').grid(column=2, row=2, sticky=(W, E)) #5)
# Create three Label instances, and place them
# on screen in the appropriate cell in the grid.
Label(frm, text="Entry Widget").grid(column=1, row=0, sticky=E) #6)
Label(frm, text="First Name").grid(column=1, row=1, sticky=W)   #7)				
Label(frm, text="Last Name").grid(column=1, row=2, sticky=W)    #8)
root.mainloop()

The following is the program’s output.

Entry Widget to Ask the User to Enter First Name and Last Name
Tkinter Entry Widget

Detailed Line-by-line Explanation of the Program

  1. root.title('Entry Widget')
    • Give the main window a name “Entry Widget”.
  2. frm = Frame(root)
    • Create a Frame widget (named “frm”) as a child of the parent “root” to hold the contents of our GUI.
  3. frm.grid(column=0, row = 0, sticky =(N, W, E, S))
    • Locate the “frm” widget on the grid at column = 0, row=0 centered in the main window “root”.
    • The sticky option places the “frm” widget in the center of the window equidistant from the North (N), West (W), East (E), and South (S) edges of the window.
  4. Entry(frm, width = 16, background = 'red').grid(column=2, row=1, sticky=(W, E))
    • Create an Entry widget instance as a child of the parent “frm” widget.
    • The width of the Entry widget is 16 characters wide.
    • The Entry widget background is red.
    • The position of this Entry widget is at grid location column=2 and row=1.
    • The “sticky” option (W, E) centers the widget in the cell equal distance from the West edge of the frame and the East edge of the frame.
  5. Entry(frm, width = 16, background = 'lightgreen') .grid(column=2, row=2, sticky=(W, E))
    • Create a second Entry widget.
    • Same as step 4), except the color is “lightgreen” and the widget is located at grid column=2 and row=2.
    • The “sticky” option (W, E) centers the widget in the cell equal distance from the West edge of the frame and the East edge of the frame.
  6. Label(frm, text="Entry Widget") .grid(column=1, row=0, sticky=E)
    • Create a Label instance as a child of “frm” widget.
    • Place the label widget on the screen at grid location column=1, row=0.
    • The “sticky” option (E) justifies the Label widget to the East edge of the frame.
    • The Text option Text = “Entry Widget” enters the words “Entry Widget” on the Label.
  7. Label(frm, text="First Name").grid(column=1, row=1, sticky=W)
    • Create a Label instance as a child of “frm” widget.
    • Place the label widget on the screen at grid location column=1, row=1.
    • The “sticky” option (W) justifies the Label widget to the West edge of the frame.
    • The Text option Text = "First Name" enters the words "First Name" on the Label.
  8. Label(frm, text="Last Name").grid(column=1, row=2, sticky=W)
    • Create a Label instance as a child of the “frm” widget.
    • Place the label widget on the screen at grid location column=1, row=2.
    • The “sticky” option (W) justifies the Label widget to the West edge of the frame.
    • The Text option Text = "Last Name" enters the words "Last Name" on the Label.

Entry Widget – Pythagoras Theorem

We are going to write a slightly more complex program to further explain the Entry widget.  We will use a simple problem from Geometry related to Pythagoras Theorem.

The students from middle/high school class may be already familiar with Pythagoras Theorem. For information on Pythagoras Theorem, refer to the section Pythagoras Theorem discussed in the Enrichment: Basic Geometry section below.

To understand the Geometry concepts in the program below, refer to the Enrichment: Basic Geometry – Triangles section at the end of this chapter.

The Program Example below calculates the hypotenuse of a right-angle triangle whose two sides are specified. The program is based on Pythagoras Theorem.

PROGRAM EXAMPLE: ENTRY WIDGET TO CALCULATE HYPOTENUSE LENGTH OF A RIGHT-ANGLE TRIANGLE
from tkinter import *
# Define a function, named 'calculate' 
# that calculates the hypotenuse of a right-angle triangle.
# This function is called by Button widget by using 
# the option command=calculate.
def calculate():
    side_a_length = float(side_a.get())
    side_b_length = float(side_b.get())
    result.set((side_a_length**2 + side_b_length**2)**(0.5)) #1)

root = Tk() # set up main window 'root'.
# Give the main window a title 'Pythagoras Theorem'. #2)
root.title("Pythagoras Theorem")  #2)
# Set up frame widget to hold contents of our user #3)
frm = Frame(root) 
# interface and put it in our main window. 
# 'frm' is child of 'root'.
# Place 'frm' on screen in the cell 
# in the grid column=0, row=0 and center it in the window.
frm.grid(column=0, row=0, sticky=(N, W, E, S), pady=10) #4)
# Padding of 10 pixels in y-direction

side_a = StringVar()				#5)
side_b = StringVar()
result = StringVar()
# Create Entry widget where the user 
# will enter length of side_a.	                #6)
side_a_entry = Entry(frm, width=10,textvariable=side_a) 
side_a_entry.grid(column=2, row=1, sticky=(W, E), padx = 10) 
# 
# Create Entry widget where the user will enter length of side_b.
side_b_entry = Entry(frm, width=10,textvariable=side_b) #7)
side_b_entry.grid(column=3, row=1, sticky=W, padx = 10)

# Create Label widget where function ‘calculate’ 
# will put resulting hypotenuse length.
Label(frm, textvariable=result).grid(column=2, row=2, sticky=(W, E)) #8)
# Create Button widget for the user 
# to press to start the calculation.
Button(frm, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W) #9)
# Create Label widget with text ‘Enter sides length’ 
# and place it in the cell column=1, row = 1 
# and justify it on the West side. 
Label(frm, text="Enter sides length").grid(column=1, row=1, sticky=W) #10)
# Create Label widget with text 'Hypotenuse length is' 
# and place it in the cell column=1, row = 2
# Position the label on the West side of the frame.
Label(frm, text="Hypotenuse length is").grid(column=1, row=2, sticky=W) #11)

root.mainloop()

The following is the result of the program. As you enter the side lengths in the two Entry widget boxes and then press the “calculate” button, the program will print the hypotenuse length in the appropriate grid.

Entry Wudget Pythagoras Theorem
Tkinter Entry Widget to Calculate the Hypotenuse of a Right Angle Triangle

Detailed Line-by-line Explanation of the Program:

1) def calculate():

Define a function named “calculate” using the formula for the hypotenuse of a right-angle triangle.

The function .get() gets the triangle sides’ length.

side_a_length = float(side_a.get())

.get() [#] function gets the current contents of the entry field and returns the widget contents as a string.

We convert the string to a float so that we can do the calculation.

On the function definition, we use Pythagoras theorem formula:

Hypotenuse**2 = side_a**2 + side_b**2.

2) root.title(“Pythagoras Theorem”)

  • This line of code gives the main window a title “Pythagoras Theorem”.

3) frm = Frame(root)

  • This line sets up frame widget (frm) as a child of the parent “root”.
  • “frm” holds the child widgets (Label and Entry) that are created in the subsequent steps below.

4) frm.grid(column=0, row=0, sticky=(N, W, E, S), pady=10)

  • This line puts the “frm” widget in the cell at column=0, row=0 with a padding of 10 pixels in the y-direction to provide space between the widgets and the “frm” widget boundary.

5) side_a = StringVar(); side_b = StringVar(); result = StringVar()

  • This line sets up variables “side_a”, “side_b”, and “result” as StringVar()
  • The variable “result” stores the contents of Pythagoras Theorem calculations.
  • StringVar() is discussed below.

6) side_a_entry = Entry(frm, width=10,textvariable=side_a)

and

side_a_entry.grid(column=2, row=1, sticky=(W, E), padx = 10)

  • The above two lines of code create an Entry widget for side_a of the triangle and place it on the screen in the cell on grids column=2, row=1 equal distance from the West edge and the East edge of the frame.

7) Same as item 6) for the second side of the triangle, side_b

8) Label(frm, textvariable=result).grid(column=2, row=2, sticky=(W, E))

  • The code in line 8) creates a Label widget to place the result of the calculation of hypotenuse length.
  • In this step, we introduce a configuration option called “textvariable” explained below.

Textvariable and StringVar

textvariable configuration option:

textvariable” is a variable linked to the text in the entry widget. The value of the variable is a text string to be displayed inside the widget. The value of the entry widget is accessed through the textvariable. The variable is usually a StringVar().

StringVar:

In step 8, the text “result” is the Tkinter variable defined as StringVar() in step 5), which holds the contents of the entry field.

9) Button(frm, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)

  • Create a Button widget with the text “Calculate”.
  • This is the button that the user clicks to start the calculation.  The option command=calculate calls the function we defined in step 1).

10) Label(frm, text="Enter sides length").grid(column=1, row=1, sticky=W)

  • Create a Label widget with the text “Enter sides length” and place it in the cell at grid column=1 and row=1 and justify it on the West side of the frame.

11) Label(frm, text="Hypotenuse length is").grid(column=1, row=2, sticky=W)

  • Create a Label widget with the text “Hypotenuse length is” and place it in the cell at grid column=1 and row=2 and justify it on the West side of the frame.

Entry Widget – Calculate the Factorial of Any Number

We calculated factorials of numbers in the Math Applications chapter. Now we use the entry widget to do the same.

The following Entry widget program calculates the factorial of any number.

PROGRAM EXAMPLE: ENTRY WIDGET TO CALCULATE THE FACTORIAL OF ANY NUMBER

Program Name: tkinter_entry_factorial.py

from tkinter import *
# Define a function, named 'factorial(n)' that calculates the factorial of a number.
# This function is called by procedure 'calculate()'.
def factorial(n):
    if n == 0:
        return 1
    else:
        result = n * factorial(n - 1) # Recursive call to function 'factorial' within the function.
        return result
# Define a function, named 'calculate' that calculates the factorial of a number.
# This function is called by Button widget by using the option command=calculate
def calculate():
    number = int(num.get())
    result.set(factorial(number))

root = Tk() # set up topmost level main window "root"
root.title("Factorial") # Give the main window a title "Factorial".
frm = Frame(root)# Set up Frame widget called "frm" as the child of top window "root".
# "frm" holds contents of the Entry widget and Label widgets.
# Put "frm" inside our main "root" window.
# Place 'frm' on the screen in the cell in the grid column=0, row=0.
frm.grid(column=0, row=0, sticky=(N, W, E, S), padx = 10, pady=10)
# Padding of 10 pixels in the x-direction and y-direction.

num = StringVar()
result = StringVar()
# Create Entry widget where we type the number,
# whose factorial is to be calculated.
number_entry = Entry(frm, width=10,textvariable=num)
number_entry.grid(column=2, row=1, sticky=(W, E), padx = 10) # Justify Entry widget left.

# Create Label widget to hold text "Enter Number" and place it onscreen
# in the cell in the grid row = 1, column = 1. 
Label(frm, text="Enter number").grid(column=1, row=1, sticky=W)

# Create Label widget for text "The Factorial is:" and place it onscreen
# in the grid column = 1, row = 2
Label(frm, text= "The Factorial is:").grid(column=1, row=2, sticky=W)

# Create Label widget where we will put the factorial result.
Label(frm, textvariable=result).grid(column=2, row=2, sticky=(W, E))

# Create Button widget, which we will press to start the calculation.
Button(frm, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W) 

root.mainloop()

The description of the program is the same as the program to calculate the hypotenuse.

If you type any number in the ENTRY box and click the ‘Calculate’ Label, the program will calculate the factorial of the number and print it on the widget. Below is the program’s output.

Entry Widget to Calculate the Factorial of Any Number
Tkinter Entry Widget to Calculate the Factorial of Any Number

Entry Widget – Number of Combinations nCr

In the Math Applications chapter, we developed techniques to find the number of combinations possible if we choose ‘r’ items out of a total of ‘n’ items.

Let us now develop a program to do the same using the Tkinter Entry widget. The following is the program.

from tkinter import *

####### FUNCTION DEFINITIONS #######
# Define a function, named "factorial(n)" that calculates the factorial of a number.
# This function is called by procedure "calculate()".
def factorial(n):
    if n == 0:
        return 1
    else:
        result = n * factorial(n - 1) # Recursive call to function 'factorial' within the function.
        return result

# Define a function, named "calculate" that calculates the
# number of combinations of "n" things taken "r" things at a time.
# This function calls procedure "factorial".
# The function "calculate" is called by Button widget by using the option command=calculate.
def calculate():
    n = int(total_number_of_things.get())
    r = int(number_of_things_taken_at_a_time.get())
    result.set((factorial(n) //(factorial(n - r) * factorial(r))))
# "n" is the total number of things out of which "r" things are taken out at a time.
####### END OF FUNCTION DEFINITIONS  ##########

####### START OF MAIN PROGRAM #########
root = Tk() # set up main window 'root'
root.title("Combinations") # Give the main window a title "Combinations".
frm = Frame(root) # Set up frame widget and name it "frm" as a child of top level widget "root".
# "frm" holds the contents of other widgets like Label and Entry.
# Place "frm" on the screen in the cell in the grid column=0, row=0.
frm.grid(column=0, row=0, sticky=(N, W, E, S), pady=10) # Padding of 10 pixels in y-direction.

total_number_of_things = StringVar()
number_of_things_taken_at_a_time = StringVar()
result = StringVar()

# Create Entry widget where we type Total Number of Things "n".
total_number_of_things_entry = Entry(frm, width=10,textvariable = total_number_of_things) 
total_number_of_things_entry.grid(column=2, row=1, sticky=(W, E), padx = 10) # Left justify the Entry widget.
#
# Create Entry widget where we type the Number of Things Taken at a Time "r".
number_of_things_taken_at_a_time_entry = Entry(frm, width=10,textvariable=number_of_things_taken_at_a_time) 
number_of_things_taken_at_a_time_entry.grid(column=2, row=2, sticky=(W,E), padx = 10)
#
# Create Label widget for text "Enter Total Number of Things"
# and place it onscreen in the cell in the grid row = 1, column=1. 
Label(frm, text="Enter Total Number of Things").grid(column=1, row=1, sticky=W)
#
# Create Label widget for text "Enter Number of Things Taken at a Time"
# and place it onscreen in the cell in the grid row=2, column=1 and justify it to the right. 
Label(frm, text="Enter Number of Things Taken at a Time").grid(column=1, row=2, sticky=W)
#
# Create Label widget where we will put the result (Number of Combinataions).
Label(frm, textvariable=result).grid(column=2, row=3, sticky=(W, E))
#
# Create Label widget for text "Number of Combinations are:"
# and place it on screen in the cell in the grid row=3, column=1 and justify it to the right.
Label(frm, text="Number of Combinations are:").grid(column=1, row=3, sticky=W)
#
# Create Button widget, which we will press to start the calculation.
Button(frm, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W, padx = 10) 

root.mainloop()

The description of the program is very similar to the program to calculate the hypotenuse of the right-angle triangle.

If you enter the total number of items ‘n’ in the top box and enter the number of items taken at a time ‘r’ in the lower Entry box, and then click the “Calculate” Button, the program will calculate and print the number of combinations, nCr.

The following is the program’s output.

Entry Widget Number of combinations - 'r' Items Taken Out of 'n' items
Tkinter Entry Widget Number of combinations – ‘r’ Items Taken Out of ‘n’ items

Enrichment: Basic Geometry – Triangles

Triangles

A triangle is a polygon with three sides and three vertices. An Equilateral triangle has all three sides of the same length and all three angles are 60 degrees.  An Isosceles triangle has two sides equal and angles opposite the equal sides are equal. A scalene triangle has all three sides of different lengths and all three angles have different measures.

Rntry Widget Equilateral Triangle
Equilateral: All three sides are equal and all three angles are 60 degrees
Entry Widget Isoceles Triangle.
Isosceles Triangle: Two sides are equal and angles opposite equal sides are equal.
Entry Widget Scalene Triangle
Scalene Triangle: all three sides are unequal.

If one of the three angles of a triangle is 90°, then the triangle is called a right-angle triangle

Entry Widget Right Anglr Triangle
Right-angle Triangle. One angle is 90 degrees

Source: https://en.wikipedia.org/wiki/Triangle

Pythagoras Theorem

Pythagoras Theorem

In a right-angle triangle, the angle opposite the 90° angle is called the hypotenuse. The Pythagoras Theorem states that the length of the hypotenuse, c is given by the following equation:

   c2 = a2 + b2 where c = hypotenuse; a and b are the sides of the triangle.      hypotenuse, c = sqrt(a2 + b2)

Area of a Triangle:

The area of any triangle can be found by the following equation:

Area = (1/2) x b x h where = b is the base of the triangle

And h = length of the perpendicular from the opposite vertex to the base.  ‘h’ is also called the altitude.

Area of triangle = (1/2)*(base)*(height)

Copyright © 2019 – 2021 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights