How would you design a very “Pythonic” UI framework?

后端 未结 15 1803
日久生厌
日久生厌 2021-02-02 01:29

I have been playing with the Ruby library \"shoes\". Basically you can write a GUI application in the following way:

Shoes.app do
  t = para \"Not clicked!\"
  b         


        
15条回答
  •  再見小時候
    2021-02-02 01:49

    This is extremely contrived and not pythonic at all, but here's my attempt at a semi-literal translation using the new "with" statement.

    with Shoes():
      t = Para("Not clicked!")
      with Button("The Label"):
        Alert("You clicked the button!")
        t.replace("Clicked!")
    

    The hardest part is dealing with the fact that python will not give us anonymous functions with more than one statement in them. To get around that, we could create a list of commands and run through those...

    Anyway, here's the backend code I ran this with:

    context = None
    
    class Nestable(object):
      def __init__(self,caption=None):
        self.caption = caption
        self.things = []
    
        global context
        if context:
          context.add(self)
    
      def __enter__(self):
        global context
        self.parent = context
        context = self
    
      def __exit__(self, type, value, traceback):
        global context
        context = self.parent
    
      def add(self,thing):
        self.things.append(thing)
        print "Adding a %s to %s" % (thing,self)
    
      def __str__(self):
        return "%s(%s)" % (self.__class__.__name__, self.caption)
    
    
    class Shoes(Nestable):
      pass
    
    class Button(Nestable):
      pass
    
    class Alert(Nestable):
      pass
    
    class Para(Nestable):
      def replace(self,caption):
        Command(self,"replace",caption)
    
    class Command(Nestable):
      def __init__(self, target, command, caption):
        self.command = command
        self.target  = target
        Nestable.__init__(self,caption)
    
      def __str__(self):
        return "Command(%s text of %s with \"%s\")" % (self.command, self.target, self.caption)
    
      def execute(self):
        self.target.caption = self.caption
    

提交回复
热议问题