I am trying to set the text of an Entry
widget using a button in a GUI using the tkinter
module.
This GUI is to help me classify thousands of words into five categories. Each of the categories has a button. I was hoping that using a button would significantly speed me up and I want to double check the words every time otherwise I would just use the button and have the GUI process the current word and bring the next word.
The command buttons for some reason are not behaving like I want them to. This is an example:
import tkinter as tk from tkinter import ttk win = tk.Tk() v = tk.StringVar() def setText(word): v.set(word) a = ttk.Button(win, text="plant", command=setText("plant")) a.pack() b = ttk.Button(win, text="animal", command=setText("animal")) b.pack() c = ttk.Entry(win, textvariable=v) c.pack() win.mainloop()
So far, when I am able to compile, the click does nothing.
Buttons are a very useful widget in any Tkinter application. We can get the value of any button in the Entry widget by defining the function which inserts the value in the Entry widget. To get the value, we have to first define buttons having command for adding the specific value to be displayed on the Entry widget.
An Entry widget in Tkinter is nothing but an input widget that accepts single-line user input in a text field. To return the data entered in an Entry widget, we have to use the get() method. It returns the data of the entry widget which further can be printed on the console.
The Entry widget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget.
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) return win = 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" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With