如何更改random.randint的变量?

时间:2019-03-25 23:27:00

标签: python

我正在尝试为随机骰子模拟器构建GUI,模拟器的预期目标是将芯片尺寸更改为不同的多面体骰子(例如20面骰子,10面骰子等)。 。我的问题是对于random.randint(1,b),我无法使用按钮将变量更改为其他数字。我该怎么办?

我尝试为按钮设置命令,例如:

def d4():
    b = 4

def d4():
    b.set(4)

代码设置:

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

b的起始值为20,因为我希望结果为20面模具的值。当我单击d4按钮时,我想将b更改为4,以表示4面骰子。但是到目前为止我尝试过的一切都已经产生

1 个答案:

答案 0 :(得分:0)

您正在尝试在函数b中更改超出函数范围的变量d4()。因此,为b分配新值不会更改函数外部存在的变量b。只需在b函数内创建一个新的局部变量d4()

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

要解决此问题,请使用关键字global通知Python解释器您要使用函数范围之外的变量。

b = 20

def d4():
    global b
    b = 4

print(b) # returns 20 as initial value
d4()
print(b) # returns 4 as new value