简体   繁体   English

如何重启 function?

[英]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.每次单击按钮并执行 function 时,我都尝试打印随机整数,但是,除非我重新启动程序,否则我只会得到相同的结果。

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.将随机数生成移至 function。 randint isn't magic - you'll have to call it again to get a new random number. randint并不神奇——你必须再次调用它才能获得一个新的随机数。

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. num1被初始化为一个随机值,但该值在程序执行期间保持不变。 Instead you could move the randomizing into the function itself:相反,您可以将随机化移动到 function 本身:

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()) def getnum(): return randint(0,9) def testfunc(): print(getnum())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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