Search code examples
pythontkinterlabel

TKinter Python make label only appear once


I wonder if someone could point me in the right direction please below is a small example of a press me app. Once pressed the app displays text to a Tkinter label. My issue is as the button is pressed the GUI fills up with multiple lines of the label. How would one just make the label appear just the once no matter how many times the button is clicked.

Thank you

import tkinter as tk

def testapp():
    w = tk.Label(root, text="Hello again!")
    w.pack()

root = tk.Tk()
w = tk.Button(root, text="Press Me!",command=testapp)
w.pack()

root.mainloop() 

Solution

  • import tkinter as tk
    
    global_label = None
    
    
    def testapp():
        global global_label
        if not global_label:
            global_label = tk.Label(root, text="Hello again!")
            global_label.pack()
    
    
    root = tk.Tk()
    w = tk.Button(root, text="Press Me!", command=testapp)
    w.pack()
    
    root.mainloop()