Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TKinter按钮和函数语法_Python_Function_Tkinter - Fatal编程技术网

Python TKinter按钮和函数语法

Python TKinter按钮和函数语法,python,function,tkinter,Python,Function,Tkinter,我在和特金特玩,想做一个数字发生器 我不明白为什么在使用此代码时不会生成新号码: roll = Button(window, text = 'Roll!', command = num()) 但如果我去掉括号,它会起作用: roll = Button(window, text = 'Roll!', command = num) 谢谢大家 代码的其余部分: from tkinter import * import random def num(): number = random.r

我在和特金特玩,想做一个数字发生器

我不明白为什么在使用此代码时不会生成新号码:

roll = Button(window, text = 'Roll!', command = num())
但如果我去掉括号,它会起作用:

roll = Button(window, text = 'Roll!', command = num)
谢谢大家

代码的其余部分:

from tkinter import *
import random

def num():
    number = random.randint(1, 6)
    num1.configure(text = number)
    return

window = Tk()
window.geometry('300x200')
window.title('Dice')

num1 = Label(window, text = 0)
num1.grid(column = 0, row = 0)

roll = Button(window, text = 'Roll!', command = num)
roll.grid(column = 0, row = 1)

window.mainloop()

当您使用括号编写
num()
时,您将立即调用该函数,并将其返回值作为参数传递给
按钮
。当您只是命名函数时,您正在将函数对象本身作为参数传递给
按钮
,稍后它将调用函数(单击按钮时)。

只是为了确保我理解。当使用括号时,随机值被定义并设置为等于按钮的值,并且在程序重新启动之前无法更改(即,按下按钮时不会重放该功能)。但是如果没有括号,函数将被“重放”,因此会生成一个新的数字?是的,
按钮
命令
参数应该是一个函数。单击按钮时,将调用该按钮。如果使用带括号的
num()
,则传递的不是函数,而是
None
,因为这是函数的返回值。在这种情况下,在创建按钮之前,该函数只运行一次。感谢Blckknght的帮助。我现在明白了