Tkinter entry widget

Text input box for tkinter


The Python tkinter entry widget is typically used to obtain text input from the user.

The Entry component only allows a single line of text to be entered if the string used for entry is longer than the widget can display. , that content will be scrolled.

If you want to receive input from multiple lines of text, you can use the Text widget. For more examples follow this link.

Related course: Python Desktop Apps with Tkinter

tkinter text input

To add text to the Entry widget using code, use the insert() method. If you want to replace the current text, you can use the delete() method and then the insert() method. Achieving.

import tkinter as tk
master = tk.Tk()

e = tk.Entry(master)
e.pack(padx=20, pady=20)
e.delete(0, "end")
e.insert(0, "Default text...")
master.mainloop()

tkinter entry widget in python

To get the text of the current input box, you can use the get() method.

s = e.get()

You can also bind the Entry widget to the Tkinter variable (StringVar) and set and get the text of the input box via that variable.

v = tk.StringVar()
e = tk.Entry(master, textvariable=v)
e.pack()

v.set("I love Python!")
s = v.get()

tkinter entry widget

The following example demonstrates how the Entry widget and the Button widget work together to automatically clear the input field and output the contents when the "Get Info" button is clicked.

import tkinter as tk
master = tk.Tk()

tk.Label(master, text="artwork:").grid(row=0)       
tk.Label(master, text="Author:").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)
e1.grid(row=0, column=1, padx=10, pady=5)
e2.grid(row=1, column=1, padx=10, pady=5)


def show():
    print("Work: "%s"" % e1.get())
    print("author:%s" % e2.get())
    e1.delete(0, "end")
    e2.delete(0, "end")

tk.Button(master, text="Get Info", width=10, command=show).grid(row=3, column=0, sticky= "w", padx=10, pady=5)
tk.Button(master, text="Exit", width=10, command=master.quit).grid(row=3, column=1, sticky="e", padx=10, pady=5)

master.mainloop()

python tkinter text input with entry widget