66

How do I set the default text for a Tkinter Entry widget in the constructor? I checked the documentation, but I do not see a something like a "string=" option to set in the constructor?

There is a similar answer out there for using tables and lists, but this is for a simple Entry widget.

Big Al
  • 980
  • 1
  • 8
  • 20

2 Answers2

103

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 6
    what is the significance of END in e.insert? – sky_bird Aug 29 '17 at 14:35
  • 1
    @sky_bird, `END` denote putting the new string at the end of the entry widget. If there's no string there, it doesn't matter whether you specify `0` or `END`. – falsetru Aug 29 '17 at 16:37
  • @meatspace, I made the codes run in both Python 2.x / Python 3.x. – falsetru Oct 26 '18 at 07:12
  • 6
    To be honest it's really inconsistent of Tkinter developers not to allow using of e = Entry(root, text='default text') constructor, as they already do with Label etc. – Anatoly Alekseev Nov 23 '18 at 23:14
  • 1
    @AnatolyAlekseev I agree. I've noticed Tkinter does a lot of simple stuff in contrived, unintuitive ways, often that seem to be targeted mainly toward certain types of use cases, and often that's the only way to do that thing. – flarn2006 Jul 18 '19 at 18:26
3

For me,

Entry.insert(END, 'your text')

didn't worked.

I used Entry.insert(-1, 'your text').

Thanks.

  • 8
    If you did e.g. `import tkinter as tk` then you would use `tk.END`. If you use `from tkinter import *`, then simply `END` should work. – Edward Falk May 12 '21 at 19:27