0

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))
1
  • The code lacks definitions for bet_entry and roll_entry, could you please update? Commented Feb 20, 2017 at 6:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.