how to get label to update based on input in entry?

Question:

was trying to implement a feature in a project i was doing where you enter text into an entry box and then it would times the amount of charaters in the entry by 0.02. i wanted to make it so there is a label and it would update automaticly as the user typed in the entry box but i cant seem to get it working

window = Tk()
window.geometry("600x500")
message_label = Label(window, text= "enter message").pack()
message_entry = Entry(window)
message_entry.pack()
message_length = (len(message_entry.get()))
message_price = message_length * 0.02


msg_price = Label(window)
msg_price.pack()
msg_price.config(text=message_price)

(i know this could be done easily with a button but im not trying to do this with a button)

Asked By: matt gaming

||

Answers:

You can add a StringVar to an Entry and then use the trace function to get updates when it has been written to using the "w" mode.

myvar = StringVar()
myEntry = Entry(master, textvariable=myvar)
myvar.trace("w", lambda a, b, c, e=Event(), v=myvar, en=entry: get_output(a, b, c, e, v, en))
myEntry.pack(side=TOP)

def get_output(a, b, c, e, v, en): #a, b and c are autogenerated name, index and mode
   #Event() might not be needed but best to include it as it can sometimes be automatically passed
    print(en.get(0, END))
    print(sv.get())
Answered By: Scott Paterson

I would propose binding the KeyRelease event for the entry widget to a function. This, in my opinion, is simpler than using trace on a StringVar.

from tkinter import *

def updateLabel(e):
    message_length = (len(message_entry.get()))
    message_price = message_length * 0.02
    msg_price.config(text=message_price)

window = Tk()
window.geometry("600x500")
message_label = Label(window, text= "enter message")
message_label.pack()

message_entry = Entry(window)
message_entry.pack()
message_entry.bind('<KeyRelease>',updateLabel)

msg_price = Label(window)
msg_price.pack()


window.mainloop()

The updateLabel function will be updated after each key is released inside the message_entry widget

Answered By: scotty3785

You can use this code (entry is named "e" and label is named "l")

var = StringVar()
e = Entry(root, textvariable=var)
l = Label(root, textvariable=var)
Answered By: szachy-a
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.