How to Add an Entry with tkinter in Python


In this example, we will get to know how to add an entry with tkinter library with Python.
The Entry control is used to create a single-line text box within a form or window. It has Textvariable property and the get() method:

  • Textvariable: This property is the text entered by the user or the text to be displayed in the Entry control.
  • Get(): This method can read the text in the Entry widget.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# addEntry.py

from tkinter import *

win = Tk()
frame = Frame(win)

# create a calculater
def calculator():
    # calculate the expression input by user
    result = "= " + str(eval(expression.get()))
    # display the results in the label
    label.config(text = result)

# create a Label control
label = Label(frame)
# create a Entry control
entry = Entry(frame)
	
# read in users' input
expression = StringVar()
# display users' input in Entry control
entry["textvariable"] = expression

# create a button
# click this button to calculate the result
button1 = Button(frame, text="Calculate", command=calculator)

entry.focus()
frame.pack()
entry.pack()
label.pack(side=LEFT)
button1.pack(side=RIGHT)

frame.mainloop()

The figure shows the result when a user inputs 5*12 and then clicks the button.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments