为什么 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 的新手,所以欢迎任何更改和建议!非常感谢!


慕工程0101907
浏览 71回答 1
1回答

UYOU

我非常建议使用 asyncio。这就是 90% 的人用来制作 discord 机器人的方法,包括我,而且它奏效了。如果你真的想这样做,那就去掉括号p1 = Thread(target=main_window())那条线会变成p1 = Thread(target=main_window).希望有所帮助。通常你在做类似的事情时必须删除括号。我可能是错的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python