2017-02-20 81 views
0

我正在写一个简单的游戏,当'calculate'按钮被点击时,它执行必要的计算并向用户显示一个消息框。用户可以继续玩。但是,跟踪用户所拥有金额的变量'开始',每次单击该按钮时都不会更新,并且它使用的起始值为1000.如何更新它?谢谢!在tkinter中使用按钮时如何更新变量?

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)) 
+0

该代码缺少'bet_entry'和'roll_entry'的定义,您能否更新? – void

回答

0

您不应该从按钮的回调中返回一个值,因为它没有要返回的变量。

您可以使用global更新方法中的变量或使用IntVar()。我会建议使用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) 

如果你真的想使用全局,

starting = 1000 

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

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

注意,在这两种方法,你不需要通过starting作为参数传递给你的方法。

1

您可以在计算函数中声明开始为全局变量,以便它在全局范围内更新。 如果你想避免全局变量的话,你也可以使可变对象的“开始”部分。