为什么 Python 线程在我没有告诉它的时候运行一个函数?



我正试图让我的代码使用discord api从discord中获取消息,并使用pygame将其放在黑屏上,并在中央显示所述消息。我尝试使用线程api运行这两个函数,并在main_process((函数中声明p1和p2。即使我只告诉它运行p2,它仍然只运行p1。它为什么要这样做?我是不是错过了什么?

我的代码

import discord
import pygame
from threading import Thread
client = discord.Client()
new_message = "Potato"
color = (255, 255, 255)

def main_process():
p1 = Thread(target=main_window())
p2 = Thread(target=get_message())
p2.start()

def main_window():
print("start function 1")
pygame.init()
pygame.font.init()
font = pygame.font.SysFont(None, 45)
info = pygame.display.Info()
screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.FULLSCREEN)
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
last_message = new_message
txt = font.render(new_message, True, color)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
if new_message != last_message:
last_message = new_message
txt = font.render(new_message, True, color)
screen.fill((30, 30, 30))
screen.blit(txt, txt.get_rect(center=screen_rect.center))
pygame.display.flip()
clock.tick(30)

def get_message():
print("start function 2")
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user or message.author.id == "MY_USER_ID":
return
if message.channel.id == MY_MESSAGE_CHANNEL_ID:
if message.content != " ":
global new_message
new_message = message.content
client.run("MY_ACCESS_TOKIN")

if __name__ == '__main__':
main_process()

我也是Python的新手,所以欢迎任何更改和建议!非常感谢!

我非常建议使用异步。这就是90%的人用来制造不和机器人的东西,包括我,它已经奏效了。

如果你真的想这样做,那么去掉p1 = Thread(target=main_window())中的括号

那条线将变成p1 = Thread(target=main_window)

希望能有所帮助。通常在做这样的事情时,你必须去掉括号。我可能错了。

最新更新