Python / Tkinter:函数中的随机数

Python / Tkinter : Random number in function

我想在每次按下按钮时得到一个随机数(在“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 具有内存 space,因此其他时间不需要调用 random.randint(0,10)...

这是一个解决方法:

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

有关详细信息,python 默认参数是在创建函数时计算的,而不是在您调用它时计算的。如果你想仔细看看,this thread可以帮到你。