2017-02-20 80 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

您可以在計算函數中聲明開始爲全局變量,以便它在全局範圍內更新。 如果你想避免全局變量的話,你也可以使可變對象的「開始」部分。