Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python VLC MediaPlayer – Enabling Keyboard Input
Next article icon

Python Arcade - Handling Keyboard Input

Last Updated : 23 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will discuss how to handle keyboard inputs in Python arcade module.

In Arcade, you can easily check which keyboard button is pressed and perform tasks according to that. 

For this, we are going to use these functions:

  • on_key_press()
  • on_key_release()

Syntax:

  • on_key_press(symbol,modifiers)
  • on_key_release (symbol, modifiers)

Parameters:

  • symbol: Key that was hit
  • modifiers: Bitwise ‘and’ of all modifiers (shift, ctrl, num lock) pressed during this event.

on_key_press() function will be called whenever the user presses a keyboard button. Similarly, on_key_released() will be called whenever a user releases a keyboard button.

Example 1:

In this example, we will create a simple program using the arcade module which will check if the upper arrow key is pressed or not.

Then we will create three functions inside this class.

  • on_draw(): Inside this function, we will start the rendering using arcade.start_render().
  • on_key_press(): This function will be called whenever a keyboard key is pressed. Inside this function, we will check if the key pressed is the up arrow key then we will print "upper arrow key is pressed".
  • on_key_release(): This function will be called whenever a keyboard key is released. Inside this function, we will check if the key released is the up arrow key then we will print "upper arrow key is released".

Below is the implementation:

Python3
# Importing arcade module import arcade  # Creating MainGame class        class MainGame(arcade.Window):     def __init__(self):         super().__init__(600, 600, title="Keyboard Inputs")      # Creating on_draw() function to draw on the screen     def on_draw(self):         arcade.start_render()              # Creating function to check button is pressed     # or not     def on_key_press(self, symbol,modifier):          # Checking the button pressed         # is up arrow key or not         if symbol == arcade.key.UP:             print("Upper arrow key is pressed")      # Creating function to check button is released     # or not     def on_key_release(self, symbol, modifier):          # Checking the button pressed         # is up arrow key or not         if symbol == arcade.key.UP:             print("Upper arrow key is released")          # Calling MainGame class        MainGame() arcade.run() 

Output:

Example 2:

In this example, we move the player according to the keyboard inputs.

For this, we are going to create a MainGame() class. Inside this class first, we are going to initialize some variables for x and y coordinates of the player's sprite and player's x and y velocity then we will create 4 functions inside this class.

  • on_draw(): Inside this function, we will draw our player and start the rendering.
  • setup(): In this function, we will initialize our camera and scene object then we will load our player and platform's sprites. After that, we will call the  PhysicsEnginePlatformer() function.
  • on_update(): In this function, we will update the x and y coordinates of the player's sprite by adding the value of vel_x and vel_y variable,
  • on_key_press(): In this function, we will change the value of the vel_x and vel_y variables according to the keyboard key that is pressed.
  • on_key_release(): In this function, we will change the value of the vel_x and vel_y variables according to the keyboard key that is released.

Below is the implementation:

Python3
# Importing arcade module import arcade  # Creating MainGame class        class MainGame(arcade.Window):     def __init__(self):         super().__init__(600, 600, title="Player Movement")          # Initializing the initial x and y coordinated         self.x = 250          self.y = 250          # Initializing a variable to store         # the velocity of the player         self.vel_x = 0         self.vel_y = 0      # Creating on_draw() function to draw on the screen     def on_draw(self):         arcade.start_render()          # Drawing the rectangle using         # draw_rectangle_filled function         arcade.draw_circle_filled(self.x, self.y,25,                                      arcade.color.GREEN )     # Creating on_update function to     # update the x coordinate     def on_update(self,delta_time):         self.x += self.vel_x * delta_time         self.y += self.vel_y * delta_time               # Creating function to change the velocity     # when button is pressed     def on_key_press(self, symbol,modifier):          # Checking the button pressed         # and changing the value of velocity         if symbol == arcade.key.UP:             self.vel_y = 300             print("Up arrow key is pressed")         elif symbol == arcade.key.DOWN:             self.vel_y = -300             print("Down arrow key is pressed")         elif symbol == arcade.key.LEFT:             self.vel_x = -300             print("Left arrow key is pressed")         elif symbol == arcade.key.RIGHT:             self.vel_x = 300             print("Right arrow key is pressed")      # Creating function to change the velocity     # when button is released     def on_key_release(self, symbol, modifier):          # Checking the button released         # and changing the value of velocity         if symbol == arcade.key.UP:             self.vel_y = 0         elif symbol == arcade.key.DOWN:             self.vel_y = 0         elif symbol == arcade.key.LEFT:             self.vel_x = 0         elif symbol == arcade.key.RIGHT:             self.vel_x = 0          # Calling MainGame class        MainGame() arcade.run() 

Output:


Next Article
Python VLC MediaPlayer – Enabling Keyboard Input

I

imranalam21510
Improve
Article Tags :
  • Python
  • Python-Arcade
Practice Tags :
  • python

Similar Reads

  • Python Arcade - Handling Mouse Inputs
    In this article, we will learn how we can handle mouse inputs in the arcade module in Python. In Arcade, you can easily handle the mouse inputs using these functions: on_mouse_motion(): Syntax: on_mouse_motion(x, y, dx, dy) Parameters: x : x coordinatey : y coordinatedx : change in x coordinatedy :
    3 min read
  • How to get keyboard input in PyGame ?
    While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() functio
    3 min read
  • Python VLC MediaPlayer – Enabling Keyboard Input
    In this article, we will see how we can enable keyboard input handling the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the bas
    2 min read
  • Handling NameError Exception in Python
    Prerequisites: Python Exception Handling There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : 1. Misspelled built-in functio
    2 min read
  • Design a Keylogger in Python
    Keystroke logging is the process of recording (logging) the keys pressed on a keyboard (usually when the user is unaware). It is also known as keylogging or keyboard capturing.These programs are used for troubleshooting technical problems with computers and business networks. It can also be used to
    3 min read
  • Input and Output in Python
    Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
    8 min read
  • Python Keywords and Identifiers
    Every language contains words and a set of rules that would make a sentence meaningful. Similarly, in Python programming language, there are a set of predefined words, called Keywords which along with Identifiers will form meaningful sentences when used together. Python keywords cannot be used as th
    10 min read
  • How to handle KeyError Exception in Python
    In this article, we will learn how to handle KeyError exceptions in Python programming language. What are Exceptions?It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.Exceptions are runtime errors because, th
    3 min read
  • PyQt5 Input Dialog | Python
    PyQt5 provides a class named QInputDialog which is used to take input from the user. In most of the application, there comes a situation where some data is required to be entered by the user and hence input dialog is needed. Input can be of type String or Text, Integer, Double and item.Used methods:
    2 min read
  • PyQt5 QCalendarWidget -Grabbing Keyboard input
    In this article we will see how we can grab the keyboard input for the QCalendarWidget. By grabbing keyboard the calendar will not be affected, except that it doesn't receive any keyboard events. setFocus moves the focus as usual, but the new focus widget receives keyboard events only after releaseK
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences