How to set the text/value/content of an `Entry` widget using a button in tkinter How to set the text/value/content of an `Entry` widget using a button in tkinter tkinter tkinter

How to set the text/value/content of an `Entry` widget using a button in tkinter


You might want to use insert method. You can find the documentation for the Tkinter Entry Widget here.

This script inserts a text into Entry. The inserted text can be changed in command parameter of the Button.

from tkinter import *def set_text(text):    e.delete(0,END)    e.insert(0,text)    returnwin = Tk()e = Entry(win,width=10)e.pack()b1 = Button(win,text="animal",command=lambda:set_text("animal"))b1.pack()b2 = Button(win,text="plant",command=lambda:set_text("plant"))b2.pack()win.mainloop()


If you use a "text variable" tk.StringVar(), you can just set() that.

No need to use the Entry delete and insert. Moreover, those functions don't work when the Entry is disabled or readonly! The text variable method, however, does work under those conditions as well.

import Tkinter as tk...entryText = tk.StringVar()entry = tk.Entry( master, textvariable=entryText )entryText.set( "Hello World" )


Your problem is that when you do this:

a = Button(win, text="plant", command=setText("plant"))

it tries to evaluate what to set for the command. So when instantiating the Button object, it actually calls setText("plant"). This is wrong, because you don't want to call the setText method yet. Then it takes the return value of this call (which is None), and sets that to the command of the button. That's why clicking the button does nothing, because there is no command set for it.

If you do as Milan Skála suggested and use a lambda expression instead, then your code will work (assuming you fix the indentation and the parentheses).

Instead of command=setText("plant"), which actually calls the function, you can set command=lambda:setText("plant") which specifies something which will call the function later, when you want to call it.

If you don't like lambdas, another (slightly more cumbersome) way would be to define a pair of functions to do what you want:

def set_to_plant():    set_text("plant")def set_to_animal():    set_text("animal")

and then you can use command=set_to_plant and command=set_to_animal - these will evaluate to the corresponding functions, but are definitely not the same as command=set_to_plant() which would of course evaluate to None again.