David Wernery
David Wernery

Reputation: 23

How do you update a variable when using a button in tkinter?

I am writing a simple game where when the 'calculate' button is clicked, it performs the necessary calculations and displays a messagebox to the user. The user can then keep playing. However, the variable that keeps track of the money the user has, 'starting', does not update each time the button is clicked and it uses the starting value of 1000. How can I have it update? Thank you!

starting = 1000
#calculation procedure
def calculate(starting):
    dice1 = random.randrange(1,7)
    get_bet_entry=float(bet_entry.get())
    get_roll_entry = float(roll_entry.get())
    if dice1 == get_roll_entry:
        starting = starting + get_bet_entry
        messagebox.showinfo("Answer","You won! Your new total is $" + str(starting))
        return(starting)
    else:
        starting = starting - get_bet_entry
        messagebox.showinfo("Answer","You are wrong, the number was " + str(dice1) + '. You have $' + str(starting)) 
        return(starting)


#designing bet button 
B2 = Button(root,text = "Bet", padx=50, command = lambda: calculate(starting))

Upvotes: 0

Views: 59

Answers (2)

Lafexlos
Lafexlos

Reputation: 7735

You shouldn't return a value from button's callback since it doesn't have a variable to return.

You can either use global to update your variable within a method or use IntVar(). I would suggest using IntVar().

starting = IntVar(root)
starting.set(1000) 

def calculate():
    #calculations
    starting.set(calculation_result)
    messagebox.showinfo("Answer","You won! Your new total is $" + str(starting.get()))

B2 = Button(......, command = calculate) 

If you really want to use global,

starting = 1000

def calculate():
    global starting
    #calculations
    starting = calculation_result

B2 = Button(......, command = calculate) 

Note that in both approaches, you don't need to pass starting as parameter to your method.

Upvotes: 0

czr
czr

Reputation: 658

You can declare starting as a global variable inside your calculate function, so it gets updated in the global scope. You could also make "starting" part of a mutable object if you want to avoid globals.

Upvotes: 1

Related Questions