0

I'm trying to build a GUI for a random dice simulator, with the intended goal of the simulator being to change the die size to different polyhedral dice (ex. a 20 sided die, a 10 sided die, etc.). My problem is that for the random.randint (1, b), I'm having trouble using a button to change the variable to a different number. What can I do?

I've tried having a command for the button such as:

def d4():
    b = 4

and

def d4():
    b.set(4)

Code setup:

a = 1
b = 20

def rollagain():
    result = random.randint(a, b)
def d4():
    b = 4

# a bunch of buttons and labels

b_d4 = Button(bones, text = "D4", height = 1, width = 8, command = d4)
b_roll = Button(bones, text = "Roll Dice", width = 8, command = rollagain)

# button placements

bones.mainloop

The starting value for b is 20, as I would like the result to be a value for a 20 sided die. When I click the d4 button, I would like to change b to 4, to represent a 4-sided die. But everything I've tried so far has resulted

Prune
  • 76,765
  • 14
  • 60
  • 81
  • You *are* changing `b` to `4` when you click the `d4` button. Try adding the statement `print(b)` both right before you call the main loop, and at the end of `d4()`. Your problem here is that *you're not displaying `b` anywhere in your GUI* so you're not seeing it. You might have to do something like `b_d4.text = b` in the method `d4()` after setting `b` to 4. – Green Cloak Guy Mar 25 '19 at 23:33

1 Answers1

0

You are trying to change a variable b in the function d4() that is outside of the function scope. Therefore, assigning a new value to b does not change the variable b that is present outside of the function. It would simply make a new, local variable b inside your d4() function.

b = 20

def d4():
    b = 4
    print(b)


print(b) # returns 20 as initial value
d4() # shows the value 4, as this is b within the function
print(b) # returns value 20, as the outside b is not changed

To fix this: use the keyword global to inform the Python interpreter that you want to use a variable from outside the function scope.

b = 20

def d4():
    global b
    b = 4

print(b) # returns 20 as initial value
d4()
print(b) # returns 4 as new value
0x0B1
  • 330
  • 1
  • 2
  • 10