-1

I have a text field as so:

 input_field = tkinter.Entry(root).pack()

How would I go about setting the text of it in another area of the code? Let's say I wanted to make that text field have its text as "hi" upon a button click.

Nae
  • 14,209
  • 7
  • 52
  • 79
AzuLX
  • 19
  • 4
  • This is a duplicate of either https://stackoverflow.com/q/47619074/7032856 or https://stackoverflow.com/q/16373887/7032856 – Nae Feb 09 '18 at 22:26
  • 1
    Possible duplicate of [Why is Tkinter widget stored as None? (AttributeError: 'NoneType' object ...)(TypeError: 'NoneType' object ...)](https://stackoverflow.com/questions/47619074/why-is-tkinter-widget-stored-as-none-attributeerror-nonetype-object-ty) – DYZ Feb 09 '18 at 22:27
  • For the sake of being literal, you're trying to set the string displayed in an entry widget. – Nae Feb 09 '18 at 22:29

3 Answers3

1

Do not assign the result of packing to a variable, it is useless. Create a widget, store it in a variable, then pack it and control it:

input_field = tkinter.Entry(root)
input_field.pack()
input_field.insert(0,text)
DYZ
  • 55,249
  • 10
  • 64
  • 93
1

First, separate your layout manager call:

input_field = tkinter.Entry(root)
input_field.pack()

Then, when you want to set it, remove its content:

input_field.delete('0', 'end')

then add your string:

input_field.insert('0', "hi")
Nae
  • 14,209
  • 7
  • 52
  • 79
1

Both answers provided are sufficient but another tip that may come in handy is to make use of Tkinters variable wrappers. CODE:

from tkinter import *

def setText():
    var.set("set text here")

root = Tk()
var = StringVar()

input_field = Entry(root, text= var)
input_field.pack()

button = Button(root,text = "changes entry text", command=setText)
button.pack()


root.mainloop()

So this is really simple all we are doing is creating a string variable called var NOTE. this can be called anything. we then set the text of the entry widget to the variablke var. Then to set the text just pass the var to any function and use the code .set("") to set text.

NOTE. syntax above is not accurate depends on how you imported tkinter

Using this method is also beneficial when maintaining or updating code. Below are screenshots of the executed code: Before clcik

After click

Moller Rodrigues
  • 780
  • 5
  • 16