1 回答
TA贡献1735条经验 获得超5个赞
可能是在单独的线程中呈现文本导致了问题。根据 pygame font 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()
添加回答
举报