The present invention relates to a Pyrimido[5,4-]indolizine or pyrimido[5,4-] pyrrolizine compound, preparation method thereof and use thereof. The compounds of the present invention have good inhibitory activities against BTK at the molecular and cellular levels. Importantly, the compounds of the present invention have low activity against Ramos cells of normal human B lymphoma cells, and have high activity against BTK-sensitive human diffuse large B lymphoma TMD8 cells, indicating that these type of compounds with novel structural are highly selective, off-target phenomenon and corresponding side effects are low. Thus it is a selective inhibitor of BTK with development potential.