如何在Python中创建多击键功能

时间:2018-06-16 10:00:30

标签: python python-3.x pygame

我使用的是Python 3.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。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

以下是您的代码的可能修复:

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()