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()
出于某种原因,按下按钮后变量diceR
恢复为0 - 我希望此按钮将变量设置为1,2或3(参见代码)
我想要一个按钮将变量diceR
设置为一个数字,这样我就可以使用这个新变量来改变" roll"的功能。按钮 - 但变量仍然设置回0。
我不知道我做错了什么,也不是最喜欢蟒蛇的人,所以你能否对这种情况有所了解?
答案 0 :(得分:1)
因为您要在diceR
内分配新的本地名称SetR
,而不是“全局”diceR
。然后在函数结束时丢弃该值。您需要明确指定要分配的名称:
def SetR(newR):
global diceR
diceR = newR
以下是您可以运行以演示此内容的最小示例:
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