代码之家  ›  专栏  ›  技术社区  ›  Hoseong Jeon

如何用Python编写多线程程序

  •  -1
  • Hoseong Jeon  · 技术社区  · 7 年前

    我的意思是,我想创建一个注意Ctrl+S和Q的函数。

    但我的程序没有注意到。

    我的代码是:

    import threading, pygame, sys
    from pygame.locals import *
    from time import sleep
    
    pygame.init()
    screen = pygame.display.set_mode((1160, 640), 0, 0)
    screen.fill((255, 255, 255))
    pygame.display.flip()
    
    def background():
        while True:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if pygame.key.get_mods() & pygame.KMOD_CTRL and event.key == pygame.K_s:
                        print('GOOD')
    
    def foreground():
        while True:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        print('HELLO_WORLD')
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
    
    b = threading.Thread(name='background', target=background)
    
    b.start()
    foreground()
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   JimmyK    7 年前

    通过打电话 b.start() background 线程,将不会释放回事件队列中。以及 foreground 函数将无法捕获和处理它。