user3081954 user3081954 - 2 months ago 17
Python Question

Updating label keeps previous text

In the program I made, the user presses enter and the text typed is then shown as a label in the program. So the label keeps getting updated and then written on the next line. The problem is that in the textbox the previous line the user typed stays there, which means u have to keep manually deleting the string in the textbox to write a new line. How can I make it so that you start out with a cleared textbox? Also, the enter button works but it seems that when i click on the "Return" button it gives me an error:

TypeError: evaluate() missing 1 required positional argument: 'event'

Here's the code:

from tkinter import *

window = Tk()
window.geometry("200x300")

def evaluate(event):
thetext = StringVar()
labeloutput = Label(app, textvariable = thetext)
n = e.get()
thetext.set(n)
labeloutput.grid()

app = Frame(window)
app.pack()

e = Entry(window)
e.pack()

b= Button(window, text="Return", command=evaluate)
b.pack()

window.bind("<Return>", evaluate)

mainloop()

Answer

Since you bind evaluate as a callback and you use it as a button command, when you use it in the button you have to use a lambda and pass None to the event. event argument is needed because of the binding, but there is no event when you call it from button click, so just pass None to get rid of the error. You can delete by doing entry.delete(0, 'end').

from tkinter import *

window = Tk()
window.geometry("200x300")

def evaluate(event):
    thetext = StringVar()
    labeloutput = Label(app, textvariable = thetext)
    n = e.get()
    thetext.set(n)
    labeloutput.grid()
    e.delete(0, 'end') # Here we remove text inside the entry

app = Frame(window)
app.pack()

e = Entry(window)
e.pack()

b = Button(window, text="Return", command=lambda: evaluate(None)) # Here we have a lambda to pass None to the event
b.pack()

window.bind("<Return>", evaluate)

mainloop()

Of course, if you want to prevent the lambda from being used, you would have to create a function to handle the key binding, and a separate one for the button click.