python - 如何使用线程同时运行不和谐客户端和 pygame?

标签 python pygame discord.py

我试图让我的代码使用discord api从discord获取消息,并使用pygame将其放在黑屏上,并在中心显示所述消息。 get_message() 和 main_window() 函数都是单独工作的,但是当我将其与线程结合在一起时,get_message() 似乎不起作用。

我的代码

import discord
import pygame
from threading import Thread

client = discord.Client()
new_message = "Potato"

pygame.font.init()
font = pygame.font.Font(None, 45)
color = (255, 255, 255)
txt = font.render(new_message, True, color)

def main():
    t1 = Thread(target=main_window())
    t3 = Thread(target=get_message())
    t3.start()
    t1.start()

def main_window():
    global new_message
    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()
    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True

screen.fill((30, 30, 30))
screen.blit(txt, txt.get_rect(center=screen_rect.center))

pygame.display.flip()
clock.tick(30)

def get_message():

    @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_CHANNEL_ID:
           if message.content != " ":
               global new_message
               global txt
               new_message = message.content
               txt = font.render(new_message, True, color)

    client.run("MY_ACCESS_KEY")

if name == 'main':
    pygame.init()
    main()

我对 Python 还很陌生,所以如果您有任何清理或建议,我将不胜感激!谢谢!

最佳答案

问题可能是在单独的线程中渲染文本引起的。根据pygame字体render()根据文档,该方法不是线程安全的。

我修改了您的代码,将 font.render() 调用以及与 pygame 相关的所有内容移至 main_window() 函数中。在 pygame 事件循环的每次传递中,它都会检查全局 new_message 是否已更改,如果已更改,则渲染文本。

编辑: 我刚刚注意到,当您创建线程时,您错误地指定了函数。它应该是 Thread(target=myFunc) (对函数的引用),而不是 Thread(target=myFunc()) (调用函数并传递结果)。

import discord
import pygame
from threading import Thread

client = discord.Client()
new_message = "Potato"

color = (255, 255, 255)

def main():
    t1 = Thread(target=main_window) # no parentheses on function
    t3 = Thread(target=get_message)
    t1.start()
    t3.start()

def main_window():
    pygame.init()
    pygame.font.init()

    font = pygame.font.Font(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 # inital message
    txt = font.render(new_message, True, color) # renter initial text

    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: # message was changed by other thread
            last_message = new_message
            txt = font.render(new_message, True, color) # re-render text

        screen.fill((30, 30, 30))
        screen.blit(txt, txt.get_rect(center=screen_rect.center))

        pygame.display.flip()
        clock.tick(30)

def get_message():

    @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_CHANNEL_ID:
            if message.content != " ":
                global new_message
                new_message = message.content

        client.run("MY_ACCESS_KEY")

if name == 'main':
    main()

关于python - 如何使用线程同时运行不和谐客户端和 pygame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63177650/

相关文章:

python - 在我的浏览器中看不到 view.py。 Django

python - Messenger 平台中的位置小部件在移动版中显示搜索栏,但在桌面版中不显示

python - pygame中的音乐类型未实现位置

python - Discord.py 机器人将消息重新发送到另一个 channel ,添加 react 后会中断

python - 尝试找到一种巧妙的方法来查找给定字符串中关键字的索引

python - 在没有设置的情况下更快地获得两个列表的差异

python - 为什么我的 pygame 在 Mac 上加载到空白屏幕?

python - pygame 中的命中检测

discord - 使用 Discord py 删除来自特定用户的消息

python - 使用discord.py,有什么方法可以让我的discord 机器人在成员选项卡的 'playing' 部分显示自定义消息?