pythonpython-3.xtkintertkinter-button

Access the tkinter widget properties from callback function


I have a function, lets call it create_window,where I created a tkinter window with only a label and a button. I have a command which calls a callback function, lets call it change. I can not access window components from change function. This is a sample:

import tkinter as tk
def create_window():
    window = tk.Tk()
    label = tk.Label(window, text="Label!")
    label.pack()
    button = tk.Button(window, text="Change", command=change)
    button.pack()
    window.mainloop()
def change():
    label.config(text="Label changed from click!")
create_window()

If I create window in main code, I can access the window widget normally. Any ideas?

I got this error when I click a button: NameError: name 'label' is not defined


Solution

  • Local variables inside a function cannot be accessed outside that function.

    For you case, you can pass the label to change():

    def create_window():
        ...
        button = tk.Button(window, text="Change", command=lambda: change(label))
        ...
    
    def change(label):
        label.config(text="Label changed from click!")