Added simple "page system".

This commit is contained in:
The Wobbler 2024-12-18 17:33:16 +01:00
parent 103da5c1d7
commit 10ba70d545
3 changed files with 113 additions and 0 deletions

View file

@ -0,0 +1,8 @@
#!/usr/bin/python3
"""
Simple module to create "pages". Pages can be used like web browser tabs.
"""
from .page_manager import PageManager
from .page import Page

View file

@ -0,0 +1,49 @@
#!/usr/bin/python3
import pygame
class Page:
"""
Represents a "page". Can be used similar to a browser tab.
To use this properly, you have to overwrite this class.
"""
def __init__(
self,
app: any=None,
surface: pygame.Surface=None,
main_container: "Container"=None,
):
"""
:param app: Can be any class. This has no builtin functionality,
but this can be useful if you want to access something in your main class from a widget or something else.
:param surface: If you dont want to directly draw a container's surface onto the screen,
you can also draw your own surface.
"""
self.app = app
self.surface = surface
self.main_container = main_container
def draw(self, surface: pygame.Surface) -> None:
"""
Draws the main container on the given surface.
:param pygame.Surface surface: The surface to draw on.
"""
if not self.surface is None:
surface.blit(self.surface, (0, 0))
if not self.main_container is None:
self.main_container.draw(surface)
def update(self) -> None:
"""
Updates the main container.
"""
if not self.main_container is None:
self.main_container.update()

View file

@ -0,0 +1,56 @@
#!/usr/bin/python3
from pygame import Surface
from .page import Page
class PageManager:
"""
Simple class for managing "pages". A page can be used like a tab in a web browser or something else.
"""
def __init__(self, app: any=None):
"""
:param app: Some class that gets passed to all pages so they can all access it.
This has no builtin functionality.
"""
self.app = app
self.DefaultPage = Page() # empty page, should be overwritten
self.current_page = "DefaultPage"
self.page_names = []
def draw(self, surface: Surface) -> None:
"""
Draws the current page onto a pygame.Surface.
:param pygame.Surface surface: The surface to draw on.
"""
getattr(self, self.current_page).draw(surface)
def update(self) -> None:
"""
Updates all pages.
"""
for page_name in self.page_names:
page = getattr(self, page_name)
page.update()
def __iadd__(self, other: Page):
self.page_names.append(type(other).__name__)
setattr(self, type(other).__name__, other)
return self
def __setattr__(self, key, value):
self.__dict__[key] = value
if key == "current_page":
getattr(self, self.current_page).visible = False # tell the page that it is not visible anymore
getattr(self, value).visible = True # and tell the new page that it is now visible