Reputation: 323
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?
Upvotes: 0
Views: 54
Reputation: 87
do this:
def testfunc(): print(randint(0,9))
or
def getnum(): return randint(0,9)
def testfunc(): print(getnum())
Upvotes: 1
Reputation: 311338
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))
Upvotes: 1
Reputation: 168986
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)
Upvotes: 4