1

I have some weird behavior working with ttk.Button. I have a variable n defined outside the function 'click_me()'. This code runs fine, and shows "Count: 1". But when I uncomment the line "n=n+1", I get the following error:

File "***.py", line **, in click_me
    action.configure(text="Count: {}".format(n))
UnboundLocalError: local variable 'n' referenced before assignment

How is it that "click_me()" can access n when 'n=n+1' is commented, but shows an error when it is not commented? And why is the error in the action.configure line, which worked fine when the other line was commented?

Btw, the location of "n=1" does not seem to affect the result.

import tkinter as tk
from tkinter import ttk

win = tk.Tk()

n=1

def click_me():
    action.configure(text="Count: {}".format(n))
    #n=n+1

action = ttk.Button(win, text="Click!", command=click_me)
action.grid(column=0, row=0)

n=1

win.mainloop()
Ananth
  • 11
  • 1
  • If a function modifies a variable, that variable becomes local for the entire function body, unless you declare it as `global` (or `nonlocal` for up-level references). – Tom Karzes May 15 '19 at 18:21
  • It was answered in linked post. The behavior is unintuitive, but rational: https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python – Ananth May 15 '19 at 18:24

0 Answers0