为什么 Python 线程 运行 是一个函数,而我并没有告诉它?

Why does Python Threading run a function when I don't tell it to?

我正在尝试让我的代码使用 discord api 从 discord 获取消息,并使用 pygame 将其放在黑屏上,并在中心显示该消息。我正在尝试使用线程 api 运行 这两个函数,并在 main_process() 函数中声明 p1 和 p2。即使我只告诉它 运行 p2,它仍然只 运行s 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的新手,所以欢迎任何更改和建议!非常感谢!

我非常建议使用 asyncio。这就是 90% 的人用来制作 discord 机器人的方法,包括我,而且它奏效了。

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

中的括号

该行将变为 p1 = Thread(target=main_window)

希望对您有所帮助。通常你在做类似的事情时必须删除括号。不过我可能是错的。