Search code examples
pythonpygamekeyboard

How do i make python detect a key press?


I want this code to say Hi when a button is pressed I use replit.com or repl.it It says as an error:

File "main.py", line 18, in intro
if keyboard.KEY_DOWN("a"):
TypeError: 'str' object is not callable 

I am trying to make a monoploy game on python but errors like this keep popping up

import tkinter as tk
from tkinter import *
import os
import random
import math
import pygame
from pygame.locals import * 
import sys
from sys import exit
import keyboard
from keyboard import *
window = pygame.init()
print("Wellcome to Math monopoply!!!\n")
time.sleep(1)
def intro():
  print("Hi")
  if keyboard.KEY_DOWN("a"):
    print("hi")
intro() 

Solution

  • This might help

    import pygame #Import pygame
    import sys #
    pygame.init() #Initialise it
    
    window = pygame.display.set_mode((1000,800)) #Create a 1000x800 window
    
    while True: #while loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT: #if the user presses the 'X' button
                pygame.quit() #De= initialise pygame
                sys.exit() #Exit
            if event.type == pygame.KEYDOWN: #if a key is pressed down
                if event.key == pygame.K_a: 
                    print("Hi") 
    

    You can read more about pygame.event.get() here