pythontkintertoplevel

Tkinter toplevel window is not defined


I wonder if someone could tell me if its possible to update toplevel windows using external functions. I've replicated my issue below what I need to do is update the Toplevel(master) using the function updatelabel(). I have used similar external function to update items in root which works like a dream. However, with the top level window I always get the

NameError: name 'newWindow' is not defined

The only work around I found was to kill the newWindow using newWindow.destroy() on each load but this method makes the screen pop up and then close again which doesn't look pretty. Any help most welcome thanks.

from tkinter import *
from tkinter.ttk import *   
master = Tk()
master.geometry("200x200")

def updatelabel():
    Label(newWindow,
          text="I changed").pack()

def openNewWindow():
    # Toplevel object which will
    # be treated as a new window
    newWindow = Toplevel(master)

    # sets the title of the
    # Toplevel widget
    newWindow.title("New Window")

    # sets the geometry of toplevel
    newWindow.geometry("200x200")

    # A Label widget to show in toplevel
    Label(newWindow,
          text="I want to change").pack()

    button1 = Button(newWindow,
                 text="Click me to change label", command=updatelabel).pack()


btn = Button(master,
             text="open a new window",
             command=openNewWindow)
btn.pack(pady=10)

mainloop()

Solution

  • Your “newWindow” is defined in your “openNewWindow” function and so it basically only exists in there, you could probably fix this by either defining “newWindow” outside of the function, or by using it as an argument(just add it to the brackets and give it a name in the function itself’s brackets) calling “updateLabel”

    I think this should work, though I haven’t worked with tkinter in a bit so don’t blame me if it doesn’t

    from tkinter import *
    from tkinter.ttk import *   
    master = Tk()
    master.geometry("200x200")
    
    def updatelabel(newWindow):
        Label(newWindow,
              text="I changed").pack()
    
    def openNewWindow():
        # Toplevel object which will
        # be treated as a new window
        newWindow = Toplevel(master)
    
        # sets the title of the
        # Toplevel widget
        newWindow.title("New Window")
    
        # sets the geometry of toplevel
        newWindow.geometry("200x200")
    
        # A Label widget to show in toplevel
        Label(newWindow,
              text="I want to change").pack()
    
        button1 = Button(newWindow,
                     text="Click me to change label", command= lambda: updatelabel(newWindow)).pack()
    
    
    btn = Button(master,
                 text="open a new window",
                 command=openNewWindow)
    btn.pack(pady=10)
    
    mainloop()