0

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() 
  • The error is pointing out that the `keyboard.KEY_DOWN` object is a string, not a function. So you cannot call it with "a" as an argument. – William Apr 28 '21 at 03:32
  • See if this question can help you: https://stackoverflow.com/questions/16044229/how-to-get-keyboard-input-in-pygame – William Apr 28 '21 at 03:38

2 Answers2

1

if a key is currently held down can be detected with pygame.key.get_pressed(). pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False:

keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
    # [...]

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. You need and application loop and an event loop to handle the events:

# application loop
run = True
while run:

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a: 
                print("Hi")    
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

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

CopyrightC
  • 857
  • 2
  • 7
  • 15