I'm trying to build a GUI for a simple application with Tkinter on Python 3.3.0. I have stumbled upon a little programming quirk that at first sight it seems wrong. Although it isn't a problem per se (it isn't affecting my objective) it doesn't make sense in a Pythonic way.
So, here is the source:
from tkinter import *
from tkinter import ttk
def foo():
def bar():
root.destroy()
root = Tk()
mainframe = ttk.Frame(root).grid(column=0, row=0)
ttk.Button(mainframe,text="Goodbye",command=bar).grid(column=1, row=1)
root.mainloop()
foo()
Running this and clicking the "Goodbye"
button closes the window, as expected... however here resides the problem. If I run this simplified version of the code:
def foo():
def bar():
hee = "spam"
hee = "eggs"
print(hee)
bar()
print(hee)
foo()
>>> eggs
>>> eggs
I don't access the hee
defined in foo()
and create a new hee
in bar()
, as it should. If I were now to add nonlocal hee
to the beginning of the bar()
def, the output:
>>> eggs
>>> spam
Would be the expected one.
So, my question here is why I am able to call the root
object in the first example without first declaring it nonlocal?