我一直在玩Ruby库“鞋子”。基本上,您可以通过以下方式编写 GUI 应用程序:
Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
这让我思考——如何在 Python 中设计一个同样好用的 GUI 框架?一种基本上不具有 C* 库包装器的通常联系(对于 GTK、Tk、wx、QT 等)
鞋子借鉴了网络开发的东西(比如#f0c2f0
样式颜色表示法、CSS 布局技术等:margin => 10
),以及来自 ruby(以合理的方式广泛使用块)
Python 缺乏“rubyish 块”使得(隐喻性的)直接移植变得不可能:
def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
没有那么干净,也不会nearly很灵活,我什至不确定它是否可以实施。
使用装饰器似乎是一种将代码块映射到特定操作的有趣方法:
class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
基本上,装饰器函数存储函数,然后当发生操作(例如单击)时,将执行适当的函数。
各种东西的范围(例如,la
上面示例中的标签)可能相当复杂,但它似乎可以以相当简洁的方式实现。