Home > Net >  add a clear button to the GUI which clears the output formatted by the user
add a clear button to the GUI which clears the output formatted by the user

Time:12-05

I am trying to clear the output displayed When clicked the CLEAR button should 'clear' or remove any text written in the Entry box and any text displayed on the Label. While attempting this on my own I tried using the delete method and del both of which did not remove the output when the button is pressed

from tkinter import *
import random


def generate_name_box():
    n = input_string_var.get()

    s = ""
    s  = " "   "-"*len(n)   " \n"
    s  = "|"   n   "|\n"
    s  = " "   "-"*len(n)   " \n"

    name_string_var.set(s)
    
def clear_name_box():


    
#MAIN
#Generate holding structures for GUI

root = Tk()
mainframe = Frame(root)

#Other variables
font_colour = '#EE34A2'

#Create the widgets and associated Vars

name_string_var = StringVar()
name_label = Label(mainframe, text = "", font = ("Courier", 50), textvariable=name_string_var, fg=font_colour)

instruction_label = Label(mainframe, text="Enter your name", font=("Courier", 20))

greeting_button = Button(mainframe, text ="FORMAT", font=("Courier", 20), command=generate_name_box)
clear_button = Button(mainframe, text="CLEAR", font=("Courier",20), command= clear_name_box)
input_string_var = StringVar()
input_entry = Entry(mainframe, textvariable=input_string_var)




#Grid the widgets
#############
root.minsize(450, 400)
mainframe.grid(padx = 50, pady = 50)

instruction_label.grid(row = 1, column = 1, sticky=W)
input_entry.grid(row = 2, column = 1, sticky=W)
greeting_button.grid(row = 3, column = 1, ipadx=55, ipady=10, sticky=W)
clear_button.grid(row=4,column = 1, ipadx= 55, ipady= 20, sticky=W)

name_label.grid(row = 5, column = 1, sticky=W)


root.mainloop()

CodePudding user response:

To clear the text in the Entry widget, you can use the delete method and specify the indices of the characters that you want to delete. For example, to delete all the text in the Entry widget, you can use the following code:

def clear_name_box():
    input_entry.delete(0, 'end')

This code will delete all the text from the beginning (index 0) to the end ('end') of the text in the Entry widget.

To clear the text in the Label widget, you can use the config method to change the text attribute of the Label to an empty string. For example:

def clear_name_box():
    input_entry.delete(0, 'end')
    name_label.config(text="")

This code will clear the text in both the Entry and Label widgets when the clear_name_box function is called.

CodePudding user response:

Since you have used tkinter StringVar for both the formatted output and entry box, just set them to empty string to clear the entry box and the formatted output:

def clear_name_box():
    input_string_var.set('')
    name_string_var.set('')
  • Related