简体   繁体   中英

How do I restart the function?

I'm trying to print random integers each time the button is clicked and the function is executed, however, I only get the same result, unless I restart the program.

Here's my code:

num1= randint(0,9)

testbtn_txt = tk.StringVar()
testbtn = tk.Button(root, textvariable=testbtn_txt, command=lambda:testfunc(), font="Arial", bg="#808080", fg="white", height=1, width=10)
testbtn_txt.set("Test")
testbtn.grid(row=10, column=0, columnspan=2, pady=5, padx=5)

def testfunc():
    print(num1)

So how do I do this?

Move the random number generation to the function. randint isn't magic - you'll have to call it again to get a new random number.

def testfunc():
    num1 = randint(0,9)
    print(num1)

num1 is initialized to a random value, but that value is kept for the duration of the program. Instead you could move the randomizing into the function itself:

def testfunc():
    num1 = randint(0,9)
    print(num1)

Or even more concisely:

def testfunc():
    print(randint(0,9))

do this:

def testfunc(): print(randint(0,9))

or

def getnum(): return randint(0,9) def testfunc(): print(getnum())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM