亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Python 線程在我沒有告訴它時運行一個函數?

為什么 Python 線程在我沒有告訴它時運行一個函數?

慕工程0101907 2023-04-18 17:38:28
我正在嘗試讓我的代碼使用 discord api 從 discord 獲取消息,并使用 pygame 將其放在黑屏上,并在中心顯示該消息。我正在嘗試使用線程 api 運行這兩個函數,并在 main_process() 函數中聲明 p1 和 p2。即使我只告訴它運行 p2,它仍然只運行 p1。為什么要這樣做?我錯過了什么嗎?我的代碼import discordimport pygamefrom threading import Threadclient = 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 的新手,所以歡迎任何更改和建議!非常感謝!
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

我非常建議使用 asyncio。這就是 90% 的人用來制作 discord 機器人的方法,包括我,而且它奏效了。

如果你真的想這樣做,那就去掉括號p1 = Thread(target=main_window())

那條線會變成p1 = Thread(target=main_window).

希望有所幫助。通常你在做類似的事情時必須刪除括號。我可能是錯的。


查看完整回答
反對 回復 2023-04-18
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號