I am making a simple clicker game but I cannot get the points to update. When I press the button the points show 1 but then it doesn't change again.
from functools import partial
from tkinter import *
#Set up the window
screen = Tk()
screen.title("Clicker game")
screen.geometry("700x700")
#Variables
points = 0
pointsAdded = 1
#Actual game
def click(points, pointsAdded):
points = pointsAdded
stringVar.set(str(points))
stringVar = StringVar()
textPoints = Label(screen, textvariable = stringVar, font=("Courier", 20))
textPoints.grid(row=0, column=0)
#Buttons
myButton = Button(screen, text = " ", padx=50, pady=50, command=lambda: click(points, pointsAdded))
myButton.grid(row=5, column=1)
CodePudding user response:
The reason this happens is explained well here. Basically, when you pass points
and pointsAdded
to click
Python makes a new reference to the variables inside the function, so when you change the value inside of the function the original variables remain unchanged. To fix this, you can make use of global variables:
#Variables
points = 0
pointsAdded = 1
#Actual game
def click():
global points
points = pointsAdded
stringVar.set(str(points))
stringVar = StringVar()
textPoints = Label(screen, textvariable = stringVar, font=("Courier", 20))
textPoints.grid(row=0, column=0)
#Buttons
myButton = Button(screen, text = " ", padx=50, pady=50, command= click)
myButton.grid(row=5, column=1)
The global
keyword tells Python to check the global scope for these variables as they are defined outside the click
function. Because it is directly changing the value of the variable instead of being passed as a reference the variable is incremented as you want it to.