如何在Python中制作多键功能

如何在Python中制作多键功能

我使用的是Python3.5,我想创建多个击键函数。我想创建一个注意到Ctrl+Q的函数,但是我的程序没有注意到它。
这是我的代码:

import threading, pygame
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():
    number = 0
    while True:
        if number < 10:
            number = number + 1
            print(number)
            sleep(1)
        else:
            print("10 seconds are over!")
            break

def foreground():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q:
                    print('HELLO_WORLD')


b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)

b.start()
f.start()

我也变了
def foreground():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q:
                    print('HELLO_WORLD')


def foreground():
    while True:
        key = pygame.key.get_pressed()
        if key[pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q]:
            print('HELLO_WORLD')

但它没有注意到Ctrl+Q。
我怎么能做到?

最佳答案

下面是可能的代码修复方法:

import threading
import pygame
from pygame.locals import *
from time import sleep
import sys

pygame.init()
screen = pygame.display.set_mode((1160, 640), 0, 0)
screen.fill((255, 255, 255))
pygame.display.flip()


def background():
    number = 0
    while True:
        if number < 10:
            number = number + 1
            print(number)
            sleep(1)
        else:
            print("10 seconds are over!")
            break


def foreground():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if pygame.key.get_mods() & pygame.KMOD_CTRL and event.key == pygame.K_q:
                    print('HELLO_WORLD')

            pygame.display.update()


b = threading.Thread(name='background', target=background)
b.start()
foreground()

关于python - 如何在Python中制作多键功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50886888/

10-12 16:56