i'm pretty new to python and i just created a small code to make sort of a click counter with the interface being made in Tkinter. My problem is that each time i press the button with the coin it adds 1 to the coin counter underneath, that's what it is supposed to do but for some reason it can add 1 coin only once, after clicking the first time it doesn't work anymore, clicking the button does nothing. I appreciate any help.
from tkinter import *
window=Tk()
window.maxsize(800,800)
window.minsize(800,800)
window.title("coins")
window.iconbitmap("coin.ico")
window.config(background="#7693c2")
coin = 0
def addcoin():
coin =+ 1
label.config(text=coin)
frame1 = Frame(window,bg="#7693c3")
frame2 = Frame(window,bg="#7693c2")
CoinImage = PhotoImage(file="coin.png").zoom(10).subsample(13)
CoinImage2 = PhotoImage(file="coin.png").zoom(10).subsample(60)
AddCoinButton = Button(frame1, borderwidth= 30, image=CoinImage, bg="#93aacf", command=addcoin)
AddCoinButton.grid(column= 0, row=0 ,padx=180,pady=40)
canvas = Canvas(frame2, width = 100, height= 100, bg="#7693c2", bd=0, highlightthickness=0 )
canvas.create_image(50,50, image = CoinImage2)
canvas.grid(column=0,row=0)
label = Label(frame2, text=coin,bg="#7693c2",font=("ASI_System",50))
label.grid(column=1,row=0)
frame1.grid(column=0,row=0)
frame2.grid(padx=300,column=0,row=1,sticky="w")
window.mainloop()
There are two issues with your code. First, you have a typo in addcoin()
, the augmented addition operator is +=
, not =+
. Your code is assigning the value +1
every time.
Second, the coin
variable you defined is a global one (defined at the top
level, outside any 'def' scope), but when you try to access coin
inside the
addcoin()
function, python assumes you want a local variable, and it will
complain that it's being referenced before assignment. To tell python that you
want the global variable, use the global
statement.
You can change you addcoin function like this:
def addcoin():
global coin
coin += 1
label.config(text=coin)