[SOLVED] Python / Tkinter : Random number in function

Issue

I want to get a random number (in "boucle") all the time i press the button, but when i do it, it gives me the same number

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)

Solution

Default parameter in python … Once set, this arg has a memory space, so it wont need to call random.randint(0,10) the other times …

Here’s a workaround :

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

For more information, python default argument are evaluated when the function is created, not when you call it. If you want to have a closer look, this thread can help you.

Answered By – Titouan L

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.