Python Forum

Full Version: clear button destroy can't work
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
why my destroy can't work when click clear
from tkinter import *

a=Tk()
a.title('Window')
a.geometry('500x500+300+100')
b=StringVar() #this will store value of textbox, now we have to print it so
def com():
    c=b.get() #this will get the value in C
    lab12=Label(text=c, font=20, fg='green').pack() #it will now print value in c
	
def com1():

   #clear.destroy()
   #c=b.get()
   #text11.destroy()
   #text11.delete(0, 'end')
   destroy()

labl1=Label(text='Functionalityh to a button', font=30).pack() #label
button1=Button(text='Press to print', command=com).pack()
button2=Button(text='clear', command=com1).pack()
text11 = Entry(textvariable=b).pack()



a.mainloop()
Star imports are bad.
You need also better names, a, b, com, com1 are meaningless names.
Better names are textbox_var or label_destroy.
What I did not know before, that you can let out the root and it still works, but it's bad.
Later if you work with Frames, you have to pass the right reference.

Here an example:

#/usr/env/bin python3
"""
Description of program
"""

from tkinter import (
    Tk, Button, Label,
    StringVar, Entry, END,
)
 

def label_create():
    """
    Description ...
    """
    text = textbox_var.get()
    # you need the reference of labels to destroy them later
    # using pack method on label, returns None
    label = Label(root, text=text, font=20, fg='green')
    label.pack()
    label_references.append(label)


def label_destroy():
    """
    Description ...
    """
    for label in label_references:
        label.destroy()
    label_references.clear()
    entry.delete(0, END)


label_references = []
root = Tk()
root.title('Window')
root.geometry('500x500+300+100')
textbox_var = StringVar()
Label(root, text='Functionalityh to a button', font=30).pack()
Button(root, text='Press to print', command=label_create).pack()
Button(root, text='Clear', command=label_destroy).pack()
Button(root, text='Exit', command=root.destroy).pack()
# reference for Entry
entry = Entry(root, textvariable=textbox_var)
entry.pack()
root.mainloop()
So everything is still on module level, imports have been changed and better names are given.
Later you want to isolate everything. But I guess you are not so far to use classes with inheritance.