Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 40 ยท Widgets Basics

The Tkinter Entry Widget

Use the Tkinter Entry widget for single-line input: read, insert and delete text with indexes, hide passwords, add placeholders and validate input as the user types.

The Entry widget is a single-line text box. It is how a Tkinter program asks for a name, a search term, a number or a password. Besides reading what the user typed, you will want to set initial text, clear the field, restrict what may be typed and show a hint when the box is empty. This lesson covers all of that.

Reading, inserting and deleting

Python
import tkinter as tk

root = tk.Tk()
entry = tk.Entry(root, width=30)
entry.pack(padx=20, pady=20)

entry.insert(0, "Ada")            # insert at position 0
entry.insert(tk.END, " Lovelace") # append
print(entry.get())                # Ada Lovelace
entry.delete(0, tk.END)           # clear everything
root.mainloop()
Method Meaning
get() Return the whole text as a string
insert(index, text) Insert before index
delete(first, last=None) Delete from first up to but not including last; omit last for one character
icursor(index) Move the text cursor
selection_range(start, end) Select a range
select_range, selection_clear() Same idea with other names
focus_set() Put the keyboard focus in the entry

An index can be a number (0 is before the first character), tk.END (after the last), tk.INSERT (at the cursor), or tk.SEL_FIRST/tk.SEL_LAST (the selection). delete(0, tk.END) is the standard "clear this field". The half-open rule means delete(0, 3) removes three characters.

A model of the indexes

Index arithmetic is the part people get wrong, so here is the entry's text-and-cursor behaviour in plain Python. It is a stand-in model, not Tk, but the rules are identical.

Python Stand-in: Entry insert, delete and indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Options worth knowing

Python
tk.Entry(root,
         width=30,                  # characters
         font=("Consolas", 12),
         fg="black", bg="white",
         justify="left",            # "left", "center", "right"
         show="*",                  # mask characters, for passwords
         state="normal",            # "disabled" or "readonly"
         relief="sunken", bd=2,
         insertbackground="black",  # cursor color
         selectbackground="#264653",
         textvariable=var)
  • Passwords: show="*" displays asterisks while get() still returns the real text. It only hides characters; it does not protect the text in memory.
  • state="readonly" lets users select and copy but not edit. state="disabled" blocks both, and in a disabled entry you cannot insert or delete from code either: switch to normal, change the text, then switch back.
  • width counts characters. The entry does not scroll the layout, so to fill a column use the layout manager (fill="x", sticky="ew").

Reading with a variable

Linking a StringVar (Tkinter Variables) is usually cleaner than calling get() on the widget:

Python
name = tk.StringVar()
tk.Entry(root, textvariable=name).pack()
tk.Button(root, text="Hello", command=lambda: print("Hi,", name.get())).pack()

Placeholder text

Tk has no placeholder option for Entry. The usual workaround writes grey hint text into the field and removes it on focus:

Python
class PlaceholderEntry(tk.Entry):
    def __init__(self, parent, placeholder, **kwargs):
        super().__init__(parent, **kwargs)
        self.placeholder = placeholder
        self.normal_fg = self.cget("fg")
        self.bind("<FocusIn>", self._clear)
        self.bind("<FocusOut>", self._restore)
        self._restore()

    def _clear(self, event=None):
        if self.cget("fg") == "grey":
            self.delete(0, tk.END)
            self.config(fg=self.normal_fg)

    def _restore(self, event=None):
        if not self.get():
            self.insert(0, self.placeholder)
            self.config(fg="grey")

    def value(self):
        return "" if self.cget("fg") == "grey" else self.get()

Use value() instead of get() so the hint is never mistaken for real input. The new ttk.Entry has no placeholder either; chapter 7 shows the same pattern with styles.

Validating input as the user types

An entry can check every edit before it is applied. You register a Python function with register() and pass it as validatecommand, along with validate (when to check) and substitution codes that tell Tk what to send.

Python
import tkinter as tk

def only_digits(proposed):
    return proposed == "" or proposed.isdigit()

root = tk.Tk()
vcmd = (root.register(only_digits), "%P")     # %P = the text after the edit
tk.Entry(root, validate="key", validatecommand=vcmd).pack(padx=20, pady=20)
root.mainloop()

Important details:

  • validate can be "key" (every keystroke), "focusout", "focusin", "focus" or "all".
  • The function must return True (accept) or False (reject the change).
  • Useful codes: %P text after the edit, %S the text being inserted or deleted, %d the action (1 insert, 0 delete, -1 other), %s the old text, %i index.
  • If the validator raises an exception or changes the variable linked to the entry, Tk silently turns validation off. Keep validators simple and pure.
  • invalidcommand runs when validation fails, a good place for a beep or a red border.

Here are two validators ready to test, a bounded integer and a price with at most two decimals. Because they take only the proposed text, you can run them here exactly as Tk would.

Python Stand-in: validation functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For a "validate when leaving the field" rule (for example, check an email format), use validate="focusout" and invalidcommand to show a message. Do not validate partial email text on every key: "a" is not a valid address, so a per-key validator would stop the user typing anything.

Selecting and focus

Python
entry.focus_set()                  # start with the cursor here
entry.select_range(0, tk.END)      # select all
entry.icursor(tk.END)              # cursor at the end
entry.bind("<Return>", lambda e: submit())
entry.bind("<Control-a>", lambda e: (entry.select_range(0, tk.END), "break")[1])

Returning the string "break" from a binding stops Tk's default handling (here, the default "go to start of line" for Ctrl+A on some platforms). Events are covered in Bind and Events.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call clears an Entry completely?

    delete(first, last) removes from first up to but not including last; END means the end of the text.
  2. 2. What does show='*' do?

    show only changes what is drawn. The text is still available through get().
  3. 3. A validatecommand returns what to reject a keystroke?

    Return True to accept the edit and False to reject it. Exceptions make Tk disable validation.
  4. 4. Why can't you insert() text into an Entry with state='disabled'?

    Disabled widgets reject edits from code as well as the user. Set state='normal', edit, then restore.

Summary

  • get(), insert(index, text) and delete(first, last) read and edit an Entry; END and INSERT are special indexes and delete excludes last.
  • show="*" masks input; state="readonly" allows selection but no edits; disabled blocks code edits too.
  • Placeholders must be built by hand with focus bindings.
  • Validate with register(), validate="key" and %P; return True or False and keep validators simple.
  • A linked StringVar makes reading and updating entries easier and enables trace.

Next: The Text Widget