Home > front end >  Tkinter Text widget not clearing
Tkinter Text widget not clearing

Time:03-31

I am trying trying to get user input from a text box in tkinter. I cannot use an Entry, as I can not add padding to them, and because I can not get them to match the aesthetics of the rest of the GUI.

So, I used bind with the return key, once to clear the text box, and then to print the contents.

This is my code:

customInput = Text(redCanvas,bg=yellow,highlightthickness=0,padx=10,pady=10,font=font)
customInput.bind('<Return>', lambda e: e.widget.delete('1.0','end'))
customInput.bind('<Return>', lambda e: print(e.widget.get('1.0', 'end')))
customInput.place(relx=0.5,rely=0.925,relheight=0.075,relwidth=0.75,anchor=CENTER)

The problem is that the old input doesn't get deleted: I can scroll back up to it in customInput, and all the old input is also printed when I press enter.

Example:

input: Input1
>> Input1
input: Input2
>> Input1
>> Input2
input: Input3
>> Input1
>> Input2
>> Input3

I might have been missing something blindingly obvious (happens to me), and I apologize if this question is a duplicate, but nothing that I have tried works yet.

Answers appreciated.

CodePudding user response:

The second binding statement overrides the first one. Therefore, the contents of the text box never get deleted and the output is cumulative.

You need to first print the contents and then delete it as given below:

customInput = Text(redCanvas,bg=yellow,highlightthickness=0,padx=10,pady=10,font=font)
customInput.bind('<Return>', lambda e: (print(e.widget.get('1.0', 'end')), e.widget.delete('1.0','end')))
customInput.place(relx=0.5,rely=0.925,relheight=0.075,relwidth=0.75,anchor=CENTER)
  • Related