dave
dave

Reputation: 53

Why does the variable revert back to original value after button is pressed (Tkinter)?

from tkinter import *
import random as r
import time as t

top = Tk()
top.resizable(0,0)
top.title("Dice Roll")
C = Canvas(top,height=500,width=370,bg="lawn green")
v = StringVar()
r4 = StringVar()
r6 = StringVar()
r12 = StringVar()
diceR = 0
def SetR(newR):
    diceR=newR
def GetR():
    return diceR
class Menu():
    def choose4():
        v.set("You have chosen: 4 sided die")
        SetR(1)
    def choose6():
        v.set("You have chosen: 6 sided die")
        SetR(2)
    def choose12():
        v.set("You have chosen: 12 sided die")
        SetR(3)
    def exitB():
        top.destroy()
class Dice():
    def roll():
        print(diceR)
        if diceR == 1:
            print("Test for 1")
        elif diceR == 2:
            print("Test for 2")
        elif diceR == 3:
            print("Test for 3")

choose4 = Button(text="Choose 4 sided die",command=Menu.choose4,wraplength=50)
choose6 = Button(text="Choose 6 sided die",command=Menu.choose6,wraplength=50)
choose12 = Button(text="Choose 12 sided die",command=Menu.choose12,wraplength=50)
exitB = Button(text="Exit",command=Menu.exitB)
roll = Button(text="Roll",command=Dice.roll,font=("calibri",20))
youChose = Label(top,textvariable=v)
rolled4 = Label(top,textvariable=r4)


C.pack()
choose4.place(height=76,width=75,x=1,y=425)
choose6.place(height=76,width=75,x=75,y=425)
choose12.place(height=76,width=75,x=149,y=425)
exitB.place(height=76,width=75,x=298,y=425)
youChose.place(x=1,y=1)
roll.place(height=76,width=75,x=223,y=425)
top.mainloop()

For some reason, the variable diceR reverts back to 0 after a button is pressed - and I want this button to set the variable to 1, 2 or 3 (see code)

I want a button to set the variable diceR to a number so I can use this new variable to change the function of the "roll" button - but the variable keeps getting set back to 0.

I don't know what I'm doing wrong nor does the person who loves python the most, so can you shed any light on the situation?

Upvotes: 1

Views: 592

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122036

Because you are assigning a new, local name diceR inside SetR, not the "global" diceR. This value is then discarded when the function ends. You need to be explicit about the name you want to assign:

def SetR(newR):
    global diceR
    diceR = newR

Here is a minimal example you can run to demonstrate this:

val = 1

def local_val():
    val = 2

def global_val():
    global val 
    val = 3

print(val) # will be 1

local_val()
print(val) # will still be 1

global_val()
print(val) # will be 3

Upvotes: 1

Related Questions