Python/Tkinter:函数中的随机数



我想一直按按钮得到一个随机数(在"boucle"中(,但当我这样做时,它会给我相同的数字

def boucledef(boucle=random.randint(0,10)):
global copienom, listprob
if boucle>0:
nom=selectRandom(listprob)
while copienom == nom:
nom=selectRandom(listprob)
copienom=nom
global myLabel

if boucle >1:
delete_label()
myLabel = Label(root, text=nom, font=("Arial",20), bg = couleur_bg, fg = "#2C2E75")
myLabel.pack(pady=10)

if boucle ==1:
delete_label()
myLabel = Label(root, text=nom+" is choosen", font=("Arial",20), bg = couleur_bg, fg = "#2C2E75")
myLabel.pack(pady=10)
DeleteButton["state"]=NORMAL
file_menu.entryconfig("New", state="normal")
listprob=[]
root.after(1000,boucledef, boucle-1)

python中的默认参数。。。一旦设置好,这个arg就有内存空间,所以其他时候不需要调用random.randint(0,10)。。。

这里有一个变通方法:

def boucledef(boucle=None):
global copienom, listprob
if boucle == None :
boucle = random.randint(0,10)
if boucle>0:
...

有关更多信息,python默认参数是在创建函数时计算的,而不是在调用它时计算的。如果你想更仔细地了解,这个线程可以帮助你。

最新更新