<div dir="ltr">Hello,
<br>
<br>I would like to suggest that nonlocal should be given the same creating
power as global.
<br>If I do
<br>global a_var
<br>it creates the global a_var if it doesn't exist.
<br>
<br>I think it would be great that nonlocal maintained that power.
<br>
<br>This way when I do
<br>nonlocal a_var
<br>it would create a_var in the imediate parent environment, if it didn't
exist.
<br>
<br>Without nonlocal creation powers I have to create global variables or
local variables after master=Tk() (in the following example):
<br>
<br>from tkinter import StringVar, Tk
<br>from tkinter.ttk import Label
<br>
<br>
<br>def start_gui():
<br> def change_label():
<br> _label_sv.set('Bye Bye')
<br>
<br> def create_vars():
<br> global _label_sv
<br>
<br> _label_sv = StringVar(value='Hello World')
<br>
<br> def create_layout():
<br> Label(master, textvariable=_label_sv).grid()
<br>
<br> def create_bindings():
<br> master.bind('<Escape>', lambda _: master.destroy())
<br> master.bind('<Return>', lambda _: change_label())
<br>
<br> master = Tk()
<br>
<br> create_vars()
<br> create_layout()
<br> create_bindings()
<br>
<br> master.mainloop()
<br>
<br>
<br>if __name__ == '__main__':
<br> start_gui()
<br>
<br>
<br>With nonlocal creation powers it would become a start_gui local variable
(no global) but I could have a function to create the vars instead of
having to add them after master=Tk():
<br>
<br>from tkinter import StringVar, Tk
<br>from tkinter.ttk import Label
<br>
<br>
<br>def start_gui():
<br> def change_label():
<br> label_sv.set('Bye Bye')
<br>
<br> def create_vars():
<br> nonlocal label_sv
<br>
<br> label_sv = StringVar(value='Hello World')
<br>
<br> def create_layout():
<br> Label(master, textvariable=label_sv).grid()
<br>
<br> def create_bindings():
<br> master.bind('<Escape>', lambda _: master.destroy())
<br> master.bind('<Return>', lambda _: change_label())
<br>
<br> master = Tk()
<br>
<br> create_vars()
<br> create_layout()
<br> create_bindings()
<br>
<br> master.mainloop()
<br>
<br>
<br>if __name__ == '__main__':
<br> start_gui()
<br>
<br>
<br>
<br>I know that I could also do it with OOP, but this way is more concise
(OOP would add more lines and increase the lines length, which I
personally dislike)
<br>
<br>
<br>This example is very simple, but if you imagine a GUI with several
widgets, then the separation between vars, layout and bindings becomes
useful for code organization.
<br>
<br>
<br>Best regards,
<br>
<br>João Matos
<br><br>
</div>