Game Development in Python 3 With PyGame - 15 - Button Events

sentdex · Beginner ·🛠️ AI Tools & Apps ·11y ago

Key Takeaways

This video tutorial covers creating events for button clicks in PyGame with Python 3, including handling mouse button data, detecting clicks, and using Pygame's event handling system. It also discusses workarounds for passing functions through Pygame's event handling and creating buttons with inactive and active colors.

Full Transcript

well hello there YouTubers welcome to another P game tutorial video in this video what we're going to be doing is extending our button function uh right now obviously we've got our our beautiful hover action going on it feels looks and feels like a button but it doesn't quite act like a button so um we already know that there is a way to know where the mouse is because that's how we're actually making the buttons you know look Interactive but how do we know when the button's been clicked um because it's not a button so how do we like have event handling for something that's not a button well it just so turns out that there are ways to do this so let's go up to our button function and what I'll go ahead and do is the following so we've got a definition of mouse we also can have a definition of a click so we going say click equals py game. Mouse . getor not position but pressed and it just so happens that P game collects all kinds of data all the time and on your mouse it collects the left right and middle button uh so let's go ahead and save and run that really quick and we'll just come over here I'll just put this here and then I'll move this over here nice beautiful and let's click oh we didn't print any click nice what a fool uh so print click derp run that at one more time and uh now as you can see it's a constant stream and um as we click you can see the ones appeared and I'm holding down my left button cool holding down my right now we've got a bunch of ones and then my Center got a bunch of ones now this is not including the mouse wheel rolling it's click the mouse wheel for the center just for clarity but we're mostly interested in the left click well since we have we're getting the mouse position how do we know when there's been a click well when Mouse position element zero is a one we've got a click so uh let's close out of this and now we can ask the question um first of all we're only curious about a click whenever we're within the bounds of our button right so we can come right here and we can say if click 0 equals 1 what do we want to do uh print nuclear missiles launched okay so we'll save and run that and now we've got this oh we're printing out all that nastin that's okay we'll just keep that printing out trying to arrange it but when we click on our screen now we'll click on the go and we can see it's spamming out all the nuclear missiles that we've launched so it does know when we're clicking on our on our buet so if we know when we're clicking on that button adding functionality to that's only one step away now so what we can do is we can do something like um we can come over to our game intro and our button here and we can add another parameter and this parameter is oops uh in quotes here play and this parameter is quit easy enough so then what we can do is we can come up to our actual button function we need to add one more thing to it and we're just going to add action uh and that's to parameters and then we can come down here to our this if statement and then we're asking if click zero equal 1 um and then actually we can we let's make action um the parameter have a default of none so we can say action equals none that's in the parameters so we can ask if click zero is one and action exclamation mark equals as in not equal uh none well now we want to do something and then what we can do is we can say if action let's see yeah if action equals play what do we want to do well now we just want to run the game Loop right so we just run this function right here so I'll copy that and we'll come back up here and we will do game Loop uh prams then we can also ask L if action equals quit what do we want to do well we just run a py game. quit to uninitialize pame and then quit and now we should have functionality in our button so let's go ahead and save and run that and we hit go and now we're playing our game like a bunch of Ballers and we crash um nice and you crash okay and then uh what we can do is let's do it again and then we can hit quit and then quits the game for us so uh like I was saying in the last video though this isn't quite the best because wouldn't we want to have like a button function that performs any function that we pass through because this is kind of sloppy I mean I'm going to be honest this isn't the best way to do it um so the question is can we pass a function through you can't pass a whole function through because if you do something like that like action equals none um just for kicks you don't have to you can follow along if you'd like um but let's say um here's a tip as well for you guys if you want to comment out a block you can use the multi-line comment or you can use a shorthand commenting where you highlight this block of code alt three and now you've commented out this code it's very fast I love doing it so if you didn't know that congratulations I didn't know that for at least 2 years um and I'm so thankful to have found it now uh and just so you know if you want to uncomment that alt 4 so keep that in mind anyway um so what would be ideal is that we just say if there is an action and it's not none let's let's just do that action right that'd be great so we would come down here and we would say uh oops let's go to our game intro here our action instead of being play is uh actually let's run quick quit a little more um makes a lot more sense so quit right actually quit needs two things so let's let's do play I'm sorry guys so so let's just straight up pass game Loop through here but here's the problem when we go to Def when we go to load code if you throw a function in there it's going to run so when we save and run this it's going to wait for a while and it's going to shove us straight into the game now uh what might we be able to do well we could go something like this um game Loop and then game Loop immediately runs like you could try to cheat the system right so you could say uh game intro like a so um but the problem here oh okay uh we get a bit of an infinite Loop but anyways um I thought it would be more interesting than a bunch of red text but anyway um so we can't quite we can't do that but you might ask well what what what if we pass the object right the the actual function object so we just delete the uh parenesi so we'll save and run that and we click go nothing happens because now all we're doing is referencing the object what if then we come up here and we add the function thingies to action and now we can get through and actually do the action but then the next question remains uh what about um actions like uh the quit functionality that we want well our quit actually wants to be two things so we could kind of cheat and do this very sloppy and instead of quit we could just do quit and really just mess up the whole the whole thing um okay oops Yeah just quit no no parameters um that's how we do it and then you hit quit um see it's not going to want to quit because we are on oh actually okay so it well let's run that let me run that real quick uh via sorry I think I'm having too much fun with this actually um what freaking tutorial number are we on 15 that would be this one here P game video 15 run it this might actually work but we're never un initializing P game yeah so that worked but we're not un initializing Pi game so that's not the ideal uh result um so then what you would need to do is uh if event. type equals Pi game quit um we need to just have like a you know exit Game function it something like that um cuz I don't think that we can get away with you know maybe we could add um if quit or something I don't know anyway there's obviously all kinds of stuff that you can do because for the most part when you click a button you really just want one function to run you're not actually trying to run multiple functions here um and in fact maybe what we could do is run uh P game. Qui game Loop um we could run uh n there's no way to get away from this anyway whatever um so you you know you might have to define a quick uh Define uh quit game function and then have that be like P game. quit and then quit and then you pass quit game through instead of quit like that save and run it and now our go Works fabulous and the quit works or should work I'm already saying it works but I'm just assuming that it's going to work I make no mistakes um so anyway uh that's how we can pass actions uh through our buttons and have our buttons be uh pretty functional so at this point you can actually just you can use this button function it's not even that long of a function really I'm going to get rid of this stuff cuz we don't need it anymore um and and and that's all you needed so why this is not included in um P game naturally I don't know but um you know if you just gave inactive color and active color a default color option maybe that's why I don't know CU then CU nobody predefines colors either there really should be predefined colors in pame 2 I don't I'm not like quite quite sure why there's not like predefined at least like white black red green blue like that just makes total sense to me why wouldn't you predefine have those like built into P game but whatever so anyway um I'm just not really sure why buttons aren't built into P game either um they've got a lot of really really great functionality in pi games so it is kind of weird that you don't have buttons built in and I have seen like some thirdparty button modules but um they're a lot more complex than this I'm not quite sure why you need anything more comple than this it would be kind of cool to have like rounded edges to your buttons uh I challenge anyone to do that one good luck uh if you want to do that so anyway um that's going to be it uh for now um Pro I have some high hopes for some like P game games that I want to make not really sure when I'll release the next batch of P game videos but hopefully this will tide you guys over for your P game fix for now um you guys have any questions or comments feel free to leave them below if you have any requests or like there's something very specific you want to see like how can we do X in pi game please do not ask me to like do you know crazy stuff in pi game I'm not going to make uh Battlefield 4 in pi game um but if you guys have something that you really want to see how it's done in P game or like maybe how might you do something cuz like buttons for example there's no way like immediately built into P game to make buttons but you can use tools and make buttons anyways so anyways if you guys have any requests feel free to make them as always thank you for watching thanks for all the support and subscriptions and until next time

Original Description

See http://pythonprogramming.net for sample code PyGame with Python 3 Playlist: http://www.youtube.com/playlist?list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO In this PyGame with Python 3 programming tutorial, we cover how we can create events to transpire when buttons are clicked. http://seaofbtc.com http://sentdex.com http://hkinsley.com https://twitter.com/sentdex Bitcoin donations: 1GV7srgR4NJx4vrk7avCmmVQQrqmv87ty6
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from sentdex · sentdex · 0 of 60

← Previous Next →
1 Matplotlib Python Tutorial Part 1: Basics and your first Graph!
Matplotlib Python Tutorial Part 1: Basics and your first Graph!
sentdex
2 Python Encryption Tutorial with PyCrypto
Python Encryption Tutorial with PyCrypto
sentdex
3 Python's Logging Function
Python's Logging Function
sentdex
4 wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
sentdex
5 wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
sentdex
6 wxPython Programming Tutorial 3: Menu Bar and Menu Button
wxPython Programming Tutorial 3: Menu Bar and Menu Button
sentdex
7 wxPython Programming Tutorial 4: Panels
wxPython Programming Tutorial 4: Panels
sentdex
8 wxPython Programming Tutorial 5: User Input Saved To Variables
wxPython Programming Tutorial 5: User Input Saved To Variables
sentdex
9 wxPython Programming Tutorial 6: Multiple Choice Input
wxPython Programming Tutorial 6: Multiple Choice Input
sentdex
10 wxPython Programming Tutorial 7: Adding Static Text and Colors
wxPython Programming Tutorial 7: Adding Static Text and Colors
sentdex
11 wxPython Programming Tutorial 8: Custom Button Images
wxPython Programming Tutorial 8: Custom Button Images
sentdex
12 wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
sentdex
13 Basic PHP Tutorial 13: Multi-dimensional Array
Basic PHP Tutorial 13: Multi-dimensional Array
sentdex
14 Basic PHP Tutorial 15: Functions and Global Variables
Basic PHP Tutorial 15: Functions and Global Variables
sentdex
15 Basic PHP Tutorial 12: Associative Array
Basic PHP Tutorial 12: Associative Array
sentdex
16 Basic PHP Tutorial 14: Foreach loop
Basic PHP Tutorial 14: Foreach loop
sentdex
17 Basic PHP Tutorial 16: Include and Require
Basic PHP Tutorial 16: Include and Require
sentdex
18 Basic PHP Tutorial 7: Assignment, comparison and Logical operators
Basic PHP Tutorial 7: Assignment, comparison and Logical operators
sentdex
19 Basic PHP Tutorial 4: Variables and Comments
Basic PHP Tutorial 4: Variables and Comments
sentdex
20 Basic PHP Tutorial 11: Arrays part 1, basic array
Basic PHP Tutorial 11: Arrays part 1, basic array
sentdex
21 Basic PHP Tutorial 6: If else and else if conditionals cont'd
Basic PHP Tutorial 6: If else and else if conditionals cont'd
sentdex
22 Basic PHP Tutorial 1: Intro to PHP
Basic PHP Tutorial 1: Intro to PHP
sentdex
23 Basic PHP Tutorial 3: HTML with PHP
Basic PHP Tutorial 3: HTML with PHP
sentdex
24 Basic PHP Tutorial 9: While Loop
Basic PHP Tutorial 9: While Loop
sentdex
25 Basic PHP Tutorial 10: Switch Statement
Basic PHP Tutorial 10: Switch Statement
sentdex
26 Basic PHP Tutorial 2: Print and Echo
Basic PHP Tutorial 2: Print and Echo
sentdex
27 Basic PHP Tutorial 5: If else and else if conditional statements
Basic PHP Tutorial 5: If else and else if conditional statements
sentdex
28 Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
sentdex
29 Basic PHP Tutorial 17: User Input Form Example / String Manipulation
Basic PHP Tutorial 17: User Input Form Example / String Manipulation
sentdex
30 Basic PHP Tutorial 18: HTML Entities and forms cont'd
Basic PHP Tutorial 18: HTML Entities and forms cont'd
sentdex
31 Basic PHP Tutorial 19: Finding words in strings
Basic PHP Tutorial 19: Finding words in strings
sentdex
32 Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
sentdex
33 Basic PHP Programming Tutorial 22: Hashing part 2: salting
Basic PHP Programming Tutorial 22: Hashing part 2: salting
sentdex
34 Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
sentdex
35 Basic PHP Programming Tutorial 21: MD5 Hashing For Security
Basic PHP Programming Tutorial 21: MD5 Hashing For Security
sentdex
36 Basic PHP Programming Tutorial 24: String similarity
Basic PHP Programming Tutorial 24: String similarity
sentdex
37 Basic PHP Programming Tutorial 25: Time and Time stamps
Basic PHP Programming Tutorial 25: Time and Time stamps
sentdex
38 Basic PHP Programming Tutorial 26: Die and Exit
Basic PHP Programming Tutorial 26: Die and Exit
sentdex
39 Basic PHP Programming Tutorial 27: MySQL Databases Part 1
Basic PHP Programming Tutorial 27: MySQL Databases Part 1
sentdex
40 Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
sentdex
41 Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
sentdex
42 Basic PHP Programming Tutorial 30: MySQL database in Use
Basic PHP Programming Tutorial 30: MySQL database in Use
sentdex
43 Django Tutorial Web Development with Python Part 1: Installing Django
Django Tutorial Web Development with Python Part 1: Installing Django
sentdex
44 Python Tutorial: File Deletion and Folder Deletion / directory deletion
Python Tutorial: File Deletion and Folder Deletion / directory deletion
sentdex
45 Python Tutorial: How to Rename Files and Move Files with Python
Python Tutorial: How to Rename Files and Move Files with Python
sentdex
46 3D Graphs in Matplotlib for Python: Basic 3D Line
3D Graphs in Matplotlib for Python: Basic 3D Line
sentdex
47 3D Plotting in Matplotlib for Python: 3D Scatter Plot
3D Plotting in Matplotlib for Python: 3D Scatter Plot
sentdex
48 3D Charts in Matplotlib for Python: Multiple datasets scatter plot
3D Charts in Matplotlib for Python: Multiple datasets scatter plot
sentdex
49 Sikuli Tutorial 1: Visually programming in python!
Sikuli Tutorial 1: Visually programming in python!
sentdex
50 Sikuli Tutorial 2: Program visually in python!
Sikuli Tutorial 2: Program visually in python!
sentdex
51 Sikuli Tutorial 3: Program visually in python!
Sikuli Tutorial 3: Program visually in python!
sentdex
52 3D Bar Charts in Python and Matplotlib
3D Bar Charts in Python and Matplotlib
sentdex
53 3D Plane wire frame Graph Chart in Python
3D Plane wire frame Graph Chart in Python
sentdex
54 Raspberry Pi Part 1 Introduction
Raspberry Pi Part 1 Introduction
sentdex
55 Raspberry Pi Part 8: First Download and Update! (Firmware)
Raspberry Pi Part 8: First Download and Update! (Firmware)
sentdex
56 Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
sentdex
57 Raspberry Pi Part 11: Remote Desktop
Raspberry Pi Part 11: Remote Desktop
sentdex
58 Twitter Analysis: How to rank a user's influence
Twitter Analysis: How to rank a user's influence
sentdex
59 GPIO Tutorial for Pi Part 2 - Programming the GPIO
GPIO Tutorial for Pi Part 2 - Programming the GPIO
sentdex
60 GPIO Tutorial for Raspberry Pi Part 1 - Setting up
GPIO Tutorial for Raspberry Pi Part 1 - Setting up
sentdex

This tutorial teaches how to create button events in PyGame with Python 3, covering event handling, mouse button data, and button creation. It provides workarounds for common issues and demonstrates how to implement quit events and button functionality.

Key Takeaways
  1. Define mouse and click variables
  2. Use Pygame's get_pressed function to get mouse button state
  3. Check if click has occurred by checking mouse position and button state
  4. Add event handling to button function to handle play and quit actions
  5. Pass a function through Pygame's event handling
  6. Use a function object instead of a function call
  7. Check for the Pygame quit event
  8. Use a separate function for the quit action
  9. Define a quit game function
  10. Use P game quit to quit the game loop
💡 Pygame's event handling system can be used to create button events, but requires workarounds for passing functions and handling quit events.

Related Reads

📰
How I use python to save hours every week
Learn how to use Python to automate tasks and save hours every week, with practical steps for beginners and experienced users alike.
Dev.to AI
📰
What Are AI Software Solutions and How Can They Transform Your Business?
Discover how AI software solutions can transform your business by automating tasks, enhancing decision-making, and driving innovation
Dev.to · upwork floating infotech
📰
AI Shorts generators you can actually edit (not a black box)
Learn to identify editable AI video generators and when to use black box solutions
Dev.to · Reel Mint
📰
I Wanted To Automate Website Testing Without Writing Hundreds Of Scripts. AI Changed The Approach.
Learn how AI-powered testing is revolutionizing website testing by shifting from script-based automation to goal-based testing, increasing efficiency and reducing manual effort
Medium · AI
Up next
Microsoft Bot Framework Web Chat Authentication with Microsoft Graph API Call using Auth Token in C#
Dewiride Technologies
Watch →