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)
CodePudding user response:
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
CodePudding user response:
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())
CodePudding user response:
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)