简体   繁体   中英

How do I get rid of a label in TkInter?

I have looked for ways to do this but most of them are for instances that don't help me.

Here is my code -

import os
import time
import tkinter
from tkinter import *

root = Tk()
root.title('Interpreter')
Label(text='What is your name?').pack(side=TOP,padx=10,pady=10)

entry = Entry(root, width=30)
entry.pack(side=TOP,padx=10,pady=10)

def onOkay():
    print = str(entry.get())
    myName = Label(text='Your name is '+print+'.').pack(side=BOTTOM,padx=15,pady=10)
    myName


def onClose():
    #Nothing here yet

Button(root, text='OK', command=onOkay).pack(side=LEFT,padx=5,pady=5)
Button(root, text='CLOSE', command=onClose).pack(side= RIGHT,padx=5,pady=5)

root.mainloop()

You can use the pack_forget() method on a widget to hide it.

However, you should change a couple of things in your onOkay() function:

def onOkay():
    global myName #make myName a global so it's accessible in other functions
    name = entry.get() #print shouldn't be a variable name. Also, .get() returns a string, so str() is redundant
    myName = Label(root, text='Your name is '+name+'.')
    myName.pack(side=BOTTOM,padx=15,pady=10) #put this on a new line so myName is a valid variable

And onClose:

def onClose():
    myName.pack_forget()

Edit: It's unclear if this is what you want your program to do (ie, forget the myName label when the Close button is pressed), but hopefully you can work it out from here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM