'set text of text widget later in code

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.



Solution 1:[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)

Solution 2:[2]

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")

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DYZ
Solution 2
Solution 3