Skip to content

Commit 277b97f

Browse files
▶Buttons pygame (avinashkranjan#934)
1 parent faf52a0 commit 277b97f

File tree

5 files changed

+352
-0
lines changed

5 files changed

+352
-0
lines changed

Pygame-Buttons/ExampleButtons.py

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import pygame
4+
import os,sys
5+
6+
7+
class Button(object):
8+
9+
def __init__(self, position, size):
10+
11+
# create 3 images
12+
self._images = [
13+
pygame.Surface(size),
14+
pygame.Surface(size),
15+
pygame.Surface(size),
16+
]
17+
18+
# fill images with color - red, gree, blue
19+
self._images[0].fill((255, 226, 39))
20+
self._images[1].fill((235, 89, 110))
21+
self._images[2].fill((77, 55, 93))
22+
23+
# get image size and position
24+
self._rect = pygame.Rect(position, size)
25+
26+
# select first image
27+
self._index = 0
28+
29+
def draw(self, screen):
30+
31+
# draw selected image
32+
screen.blit(self._images[self._index], self._rect)
33+
34+
def event_handler(self, event):
35+
36+
# change selected color if rectange clicked
37+
if event.type == pygame.MOUSEBUTTONDOWN: # is some button clicked
38+
if event.button == 1: # is left button clicked
39+
if self._rect.collidepoint(event.pos): # is mouse over button
40+
self._index = (self._index+1) % 3 # change image
41+
42+
# --- main ---
43+
44+
pygame.init()
45+
w, h = 800, 800
46+
screen = pygame.display.set_mode((w, h))
47+
GREEN = (0, 255, 0)
48+
GRAY= (174, 150, 255)
49+
font = pygame.font.Font('freesansbold.ttf', 22)
50+
51+
# =============================================================================
52+
# Rendring texts23564
53+
# =============================================================================
54+
55+
p1 = font.render("A PNG button , Click it ", True,(233, 248, 103))
56+
p2= font.render("A color img buttons", True,(254, 32, 107))
57+
p0 = font.render('Go Back', True,(15, 28, 2))
58+
textRectp0 = p0.get_rect()
59+
textRectp1 = p1.get_rect()
60+
textRectp2 = p2.get_rect()
61+
textRectp0.center = (405, 225)
62+
textRectp1.center = (200, 225)
63+
textRectp2.center=(350,420)
64+
65+
#backButton=main.backButton
66+
67+
module = sys.modules['__main__']
68+
path, name = os.path.split(module.__file__)
69+
path = os.path.join(path, 'retry_button.png')
70+
71+
img0 = pygame.image.load(path)
72+
img0.convert()
73+
rect0 = img0.get_rect()
74+
rect0.x=350
75+
rect0.y=200
76+
pygame.draw.rect(img0, GREEN, rect0, 1)
77+
act=False
78+
79+
80+
# create buttons
81+
82+
button1 = Button((205, 435), (100, 100))
83+
button2 = Button((310, 435), (100, 100))
84+
button3 = Button((420, 435), (100, 100))
85+
86+
# mainloop
87+
88+
89+
running=True
90+
while running:
91+
for event in pygame.event.get():
92+
pos=pygame.mouse.get_pos()
93+
if event.type == pygame.QUIT:
94+
running = False
95+
print("Job Done!!")
96+
#pygame.quit()
97+
pygame.quit()
98+
sys.exit()
99+
100+
# --- buttons events ---
101+
102+
button1.event_handler(event)
103+
button2.event_handler(event)
104+
button3.event_handler(event)
105+
106+
107+
if event.type==pygame.MOUSEBUTTONDOWN:
108+
if rect0.collidepoint(event.pos):
109+
# Toggle the active variable.
110+
act = not act
111+
else:
112+
act = False
113+
if act:
114+
print("You Clicked PNG button")
115+
print("Gone back")
116+
running=False
117+
import main
118+
119+
120+
screen.fill(GRAY)
121+
screen.blit(img0, rect0)
122+
screen.blit(p0,textRectp0)
123+
screen.blit(p1,textRectp1)
124+
screen.blit(p2,textRectp2)
125+
126+
127+
#---Buttons
128+
button1.draw(screen)
129+
button2.draw(screen)
130+
button3.draw(screen)
131+
pygame.display.update()
132+
133+
134+
135+

Pygame-Buttons/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Buttons in Python <img width="35" src="https://img.icons8.com/fluent/48/000000/play-button-circled.png"/>
2+
## Aim 🎯
3+
- How to make buttons in python
4+
- Why to use them
5+
- To be able to design and animate buttons in python .
6+
- Make buttons use in any GUI based applications . ( It will be preety handy )
7+
- To Redirect user to any other module using buttons .
8+
9+
## Details 🛈
10+
| Library | README | Install |
11+
| ------ | ------ | ------ |
12+
| Pygame | [Pygame/PyPi](https://pypi.org/project/pygame/) | `pip install pygame` |
13+
14+
## What is Included Inside ✨
15+
16+
1. Animating Button Using MOUSEOVER Porperty of pygame .
17+
2. Adding Image Buttons.
18+
> i. PNG images as buttons .
19+
> ii.Simple Color images as buttons .
20+
3. Assigning Loop Switching and Module Switching to Buttons .
21+
4. Taking Input from USER and rendring it on a button .
22+
5. Applying logic to leave/quit buttons .
23+
24+
## How to get Started 🤔
25+
- clone the repo or [copy the source code](https://github.com/Lakhankumawat/Amazing-Python-Scripts/edit/Buttons-Pygame/Pygame-Buttons/) ( be sure you maintain files in same directory ) .
26+
- Run main.py .
27+
- Enter your name -> click play -> welcome screen -> come back -> click close .
28+
- You will be headed to next module -> check out all buttons .
29+
- Looks cool !! .
30+
- Check out line of code and then start making changes , happy coding ! .
31+
32+
## How it may Look 👀
33+
34+
35+
| <img width="200" src="https://user-images.githubusercontent.com/55774240/115188301-5c91d600-a102-11eb-8a14-9e60e414d6d6.png"/> | <img align="center" width="200" src="https://user-images.githubusercontent.com/55774240/115188308-5ef43000-a102-11eb-9eac-b0b96210ddaf.png"/> | <img align="right" width="200" src="https://user-images.githubusercontent.com/55774240/115188314-60bdf380-a102-11eb-8ded-866464fa4c26.png"/><hr> |
36+
| ------ | ------ | ------ |
37+
38+
39+
40+
## Author : [LakhanKumawat](https://github.com/Lakhankumawat)

Pygame-Buttons/main.py

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# -*- coding: utf-8 -*-
2+
3+
4+
import pygame as pg
5+
6+
pg.init()
7+
8+
screen=pg.display.set_mode((500,500))
9+
pg.display.set_caption('Buttons Pygame')
10+
11+
12+
class button():
13+
def __init__(self, color, x,y,width,height, text=''):
14+
self.color = color
15+
self.x = x
16+
self.y = y
17+
self.width = width
18+
self.height = height
19+
self.text = text
20+
21+
def draw(self,screen,outline=None):
22+
#Call this method to draw the button on the screen
23+
if outline:
24+
pg.draw.rect(screen, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
25+
26+
pg.draw.rect(screen, self.color, (self.x,self.y,self.width,self.height),0)
27+
28+
if self.text != '':
29+
font = pg.font.SysFont('comicsans', 60)
30+
text = font.render(self.text, 1, (0,0,0))
31+
screen.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))
32+
33+
def isOver(self, pos):
34+
#Pos is the mouse position or a tuple of (x,y) coordinates
35+
if pos[0] > self.x and pos[0] < self.x + self.width:
36+
if pos[1] > self.y and pos[1] < self.y + self.height:
37+
return True
38+
39+
return False
40+
41+
42+
def redraw():
43+
screen.fill((164,235,243))
44+
greenButton.draw(screen,(0,0,0))
45+
redButton.draw(screen,(0,0,0))
46+
txt_surface1 = font.render(text1, True, color1)
47+
48+
# Resize the box if the text is too long.
49+
width = max(200, txt_surface1.get_width()+10)
50+
input_box1.w = width
51+
52+
# Blit the text.
53+
screen.blit(txt_surface1, (input_box1.x+5, input_box1.y+10))
54+
55+
screen.blit(p1,textRectp1)
56+
57+
# Blit the input_box rect.
58+
pg.draw.rect(screen,color1, input_box1,2)
59+
60+
pg.display.flip()
61+
62+
def draw_enter():
63+
screen.fill((164,235,243))
64+
welcomeButton.draw(screen,(0,0,0))
65+
backButton.draw(screen,(0,0,0))
66+
67+
run=True
68+
redButton=button((164,235,243),250,335,150,100,'Close')
69+
greenButton=button((164,235,243),50,335,150,100,'Play')
70+
welcomeButton=button((164,235,243),50,105,400,300,'Hi')
71+
72+
backButton=button((164,235,243),150,435,170,50,'Go Back')
73+
game_is_going=True
74+
enter_screen=False
75+
76+
input_box1 = pg.Rect(140, 170, 170, 50)
77+
color_inactive = pg.Color((2, 0, 93))
78+
color_active = pg.Color((33, 224, 239))
79+
color1 = color_inactive
80+
81+
active1 = False
82+
83+
text1 = ''
84+
font = pg.font.SysFont('comicsans', 60)
85+
p1 = font.render('Enter Your Name ', True,(14, 43, 103))
86+
87+
textRectp1 = p1.get_rect()
88+
89+
textRectp1.center = (245, 115)
90+
91+
92+
while(game_is_going):
93+
while(run):
94+
redraw()
95+
pg.display.update()
96+
97+
for event in pg.event.get():
98+
pos=pg.mouse.get_pos()
99+
100+
if event.type==pg.QUIT:
101+
run=False
102+
game_is_going=False
103+
pg.quit()
104+
105+
106+
if event.type == pg.KEYDOWN:
107+
if not active1:
108+
if event.key == pg.K_RETURN:
109+
print(text1)
110+
111+
elif event.key == pg.K_BACKSPACE:
112+
text1 = text1[:-1]
113+
else:
114+
text1 += event.unicode
115+
116+
117+
if event.type==pg.MOUSEBUTTONDOWN:
118+
119+
if input_box1.collidepoint(event.pos):
120+
# Toggle the active variable.
121+
active1 = not active1
122+
else:
123+
active1 = False
124+
color1 = color_active if active1 else color_inactive
125+
if greenButton.isOver(pos):
126+
print("Clicked Enter")
127+
run=False
128+
enter_screen=True
129+
elif redButton.isOver(pos):
130+
print("Clicked Close")
131+
run=False
132+
game_is_going=False
133+
pg.quit()
134+
135+
if event.type ==pg.MOUSEMOTION:
136+
if greenButton.isOver(pos):
137+
greenButton.color=(158,222,11)
138+
elif redButton.isOver(pos):
139+
redButton.color=(232, 69, 69)
140+
else:
141+
greenButton.color=(164,235,243)
142+
redButton.color=(164,235,243)
143+
144+
145+
while(enter_screen):
146+
draw_enter()
147+
pg.display.update()
148+
149+
for event in pg.event.get():
150+
pos=pg.mouse.get_pos()
151+
welcomeButton.text="Hi "+str(text1)
152+
if event.type==pg.QUIT:
153+
enter_screen=False
154+
game_is_going=False
155+
pg.quit()
156+
157+
158+
if event.type==pg.MOUSEBUTTONDOWN:
159+
if backButton.isOver(pos):
160+
print("Gone back")
161+
run=True
162+
enter_screen=False
163+
if event.type ==pg.MOUSEMOTION:
164+
if welcomeButton.isOver(pos):
165+
welcomeButton.color=(158,222,11)
166+
elif backButton.isOver(pos):
167+
backButton.color=(232, 69, 69)
168+
else:
169+
welcomeButton.color=(164,235,243)
170+
backButton.color=(164,235,243)
171+
172+
173+
if __name__=="__main__":
174+
import ExampleButtons
175+
176+

Pygame-Buttons/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pygame==2.0.1

Pygame-Buttons/retry_button.png

974 Bytes
Loading

0 commit comments

Comments
 (0)