I would use IntVar in a slightly different way. This code subclasses IntVar to make an IntVar that has a click() method.
import tkinter as tk
class Score(tk.IntVar):
"""Add click() method to IntVar class."""
def click(self):
self.set(self.get() + 1)
window = tk.Tk()
score_variable = Score(window)
score_display = tk.Label(textvariable=score_variable)
score_display.pack()
button = tk.Button(text="Click me!", command=score_variable.click)
button.pack()
score_display.pack()
window.mainloop()
But you can also just make a global IntVar and use it like this.
import tkinter as tk
def clicked():
score.set(score.get() + 1)
window = tk.Tk()
score = tk.IntVar(window, 0)
score_display = tk.Label(textvariable=score)
score_display.pack()
button = tk.Button(text="Click me!", command=clicked)
button.pack()
score_display.pack()
window.mainloop()
In this code the "score" in line 5 is the same "score" as in lines 9 and 10. Because there is not assignment in "clicked()", python does not create any local variables for the function. When clicked() executes it looks for a variable named "score" in the local variables, doesn't find one, and looks for a global variable named "score".
Takeaways:
assignment (=) creates variables in python. When the python code parser encounters an assignment, it creates a variable in the local scope.
global name circumvents the creation of local variables. When a function has "global name" it does not create a local variable with that name.
When a variable is encountered in a function, python first looks for a local variable with that name. If it doesn't find a matching local variable it looks for a matching global variable. If there is not a matching global variable, python looks for the variable in the builtins (built in functions like print, list...). There is an additional scope named "enclosed" that sits between local and global.
Global variables should be avoided. Because global variables can be seen by everything in the module, changes that affect the use of global variables require a code review of all code in the module.