0

This is my code for a simple Tkinter project:

from Tkinter import *

root = Tk()

global cookie_count
cookie_count = "0"
cookies = Label(root, text=cookie_count)
cookies.grid(row=0, column=0, columnspan=3)

def addCookie(multiplier):
    global cookie_count
    before = cookie_count
    after = int(before) + (1 * multiplier)
    cookie_count = after
    root.update()

add = Button(root, text="Click me!", command=lambda: addCookie(1))
add.grid(row=1, column=1, columnspan=3)

root.mainloop()

How can I make it so that the cookies label's value changes when I click the button?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153

2 Answers2

3

If you use a tkinter IntVar and set the textvariable= option of the Label to it, all your Button callback function has to do is update the Intvar's value (and the Label will update automatically):

try:
    import tkinter as tk
except ModuleNotFoundError:  # Python 2.x
    import Tkinter as tk

root = tk.Tk()

cookie_count = tk.IntVar(root, value=0)

cookies = tk.Label(root, textvariable=cookie_count)
cookies.grid(row=0, column=0, columnspan=3)

def add_cookie(multiplier):
    cookie_count.set(cookie_count.get() + multiplier)

add = tk.Button(root, text="Click me!", command=lambda: add_cookie(1))
add.grid(row=1, column=1, columnspan=3)

root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Edit: I apologized. This code is written in Python 3.x, not Python 2.

I added the import namespace partial. Then I added a parameter in the function. Then, in the command button keyword, I added +1. Added textvariable in Label.

from tkinter import *
from functools import partial


root = Tk()

variable = IntVar()
cookies = Label(root, textvariable=variable)
cookies.grid(row=0, column=0, columnspan=3)


def increment_counter(var: int, amount: int) -> int:
   result=var.get()
   result += amount  
   var.set(result)

add = Button(root, text="Click me!", command=partial(increment_counter, variable, +1))
add.grid(row=1, column=1, columnspan=3)

root.mainloop()

Output:

enter image description here

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
  • Aside from the capitalization of the module name, everything else should work the same between 2.x and 3.x here. – Karl Knechtel Jul 06 '22 at 07:21
  • 1
    @Karl: Won't work the same in Python 2.x because of the type hints (first introduced into Python in version 3.5). Seems to works OK if they are removed the capitalization of the module name is fixed — although PEP 8 recommends avoiding wildcard imports (`from import *`). – martineau Jul 07 '22 at 15:51
  • Totally overlooked those, somehow. – Karl Knechtel Jul 07 '22 at 17:42