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()
添加回答
舉報