I want to create a window with an image and button in python with pygame. I have written the following code:
import pygame as p
import random as r
import time
p.init()
p.font.init()
wind = p.display.set_mode((800, 550), 0, 32)
tus = 1
oooo = p.image.load('oooo.png')
class Button:
pl = None
xy = [int, int]
h = int
w = int
text = str
fonte = str
font_size = int
com = None
def __init__(self, pl,text, x=400, y=525, bg=(0, 0, 0), fonte='Segoe print', font_size=4, fg=(0, 0, 0)):
self.bg = bg
self.pl = pl
self.x = x
self.y = y
self.text = text
self.fonte = fonte
self.font_size = font_size
self.fg = fg
self.font = p.font.SysFont(fonte, font_size)
self.reene = self.font.render(text, True, fg, bg)
self.f = self.pl.blit(self.reene, (self.x, self.y))
def action(self, com, c_time=0):
self.ttt = time.sleep(c_time)
self.com = com
self.com
def exit():
p.quit()
while True:
wind.blit(oooo, (0, 0))
b_exit = Button(wind, '...EXIT...', bg=(0, 255, 0), fg=(170, 248, 7))
b_exit.action(exit, c_time=2.75)
title = p.display.set_caption('cat & mouse & dog')
for event in p.event.get():
if event.type == p.QUIT:
p.quit()
p.display.flip()
This code produces the following error:
Traceback (most recent call last):
File "C:/Users/Sony/Desktop/sheep/venv/Lib/site-packages/pygame/wrong.py", line 119, in <module>
p.display.flip()
pygame.error: video system not initialized
How can I solve this problem?
The problem is, the button action is to close the screen, you call the button action with b_exit.action(exit, c_time=2.75)
every frame, meaning you quit on the first frame. so by the time it gets to update the display, you have already quit. To fix, you want to check if you have clicked the button, then call the button action. I would start by creating a draw function, and get the width and height of the button, then you can do
mouse_x, mouse_y = pygame.mouse.get_pos()
if mouse_x > b_exit.x and mouse_x < b_exit.x + b_exit.w:
if mouse.y > b_exit.y and mouse_y < b_exit.y + b_exit.h:
if button_clicked:
b_exit.action(exit, c_time=2.75)
you also don't need to create an instance of the button class every frame, so move it out of the loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.