I'm using a GUI module with an onchange
parameter.
Currently I have a Settings
object that contains properties, and I want to bind them to my GUI.
But my GUI only accepts setter functions, and not variables, so I need to get the setter function of my property.
Here is the Settings
code:
class Settings:
def __init__(self):
self._name = "Jhon Doe"
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if value.count(" ") > 1:
self._name = value
Here is the (simplified) GUI code:
import pygame
import pygame_menu
from settings import Settings
settings = Settings()
pygame.init()
surface = pygame.display.set_mode((600, 600))
menu = pygame_menu.Menu('My menu', 600, 600)
menu.add.text_input('Name :', default='John Doe', onchange=settings.name)
menu.add.button('Quit', pygame_menu.events.EXIT)
menu.mainloop(surface)
You don't need the actual function, that is written as a method so it requires the instance. Just do what you'd do in this situation, whether there were a property
or not:
def _callback(value):
settings.name = value
menu.add.text_input('Name :', default='John Doe', onchange=_callback)
Or, alternatively,
menu.add.text_input('Name :', default='John Doe', onchange=lambda value: setattr(settings, "name", value))