-2

first time using Tkinter and I am trying to make a simple message system. The user puts in their message and name and presses the button to 'send it'. I want to clear the entry boxes ones the button is pressed. Here is my code:

import tkinter
    
window = tkinter.Tk()
window.geometry("400x200")

window.title("NS Twitter")

label = tkinter.Label(window, text = "Welcome!").pack()

label = tkinter.Label(window, text = "Leave a message.").pack()

message = tkinter.Entry(window).pack()

label = tkinter.Label(window, text = "Put in your name.").pack()

name = tkinter.Entry(window).pack()

button = tkinter.Button(window, text = "Send.").pack()

window.mainloop()

The question: How do I clear the entry boxes ones the button is pressed?

David
  • 69
  • 1
  • 8

1 Answers1

0
  1. So start by "properly" declaring your widgets.
label1 = tkinter.Label(window, text = "Welcome!")
label1.pack()

label2 = tkinter.Label(window, text = "Leave a message.")
label2.pack()

message = tkinter.Entry(window)
message.pack()

label3 = tkinter.Label(window, text = "Put in your name.")
label3.pack()

name = tkinter.Entry(window)
name.pack()

button1 = tkinter.Button(window, text = "Send.")
button1.pack()

What this does is that it allows you to configure or later make some use of the entry widgets. Or else your variables will return None as the result of what is returned by pack(). To understand better, take a look here. Also notice that I changed all the variables names to unique ones to avoid their repetition.

  1. Now add a command(keyword argument) to your button:
button1 = tkinter.Button(window, text = "Send.",command=clear)
  1. Now define the function clear():
def clear():
    name.delete(0,'end')
    message.delete(0,'end')

Here, delete(0,'end) will remove everything in between the 0 index and the end of the respective entry widget. Also notice that you wont say command=clear() as this will call(invoke) the functions directly.

Also notice that saying tkinter.Label() and tkinter.Entry() can be tiresome to type at times, so I recommend to change your import statement to import tkinter as tk, so now you just have to say tk.Label() or tk.Entry() instead of the other longer ones.

So your final code would be:

import tkinter as tk

window = tk.Tk()

def clear():
    name.delete(0,'end')
    message.delete(0,'end')

label1 = tk.Label(window, text = "Welcome!")
label1.pack()

label2 = tk.Label(window, text = "Leave a message.")
label2.pack()

message = tk.Entry(window)
message.pack()

label3 = tk.Label(window, text = "Put in your name.")
label3.pack()

name = tk.Entry(window)
name.pack()

button1 = tk.Button(window, text = "Send.",command=clear)
button1.pack()

window.mainloop()

All these are just recommendations as you are just starting out tkinter and it is important to have a correct and better knowledge at the very beginning.

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46