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 *

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():

   #text11.delete(0, 'end')

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()

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')

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

label_references = []
root = Tk()
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)
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.