【发布时间】:2010-09-08 16:37:14
【问题描述】:
我一直在玩 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 等的情况下)
Shoes 从 Web 开发(如 #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)
没有那么干净,也不会几乎那么灵活,我什至不确定它是否可以实现。
使用装饰器似乎是一种将代码块映射到特定操作的有趣方式:
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 标签)可能相当复杂,但它似乎以相当简洁的方式可行..
【问题讨论】:
-
Ruby 和 Python 都适用于 DSL。区别在于“L”;它代表 Ruby 的“语言”和 Python 的“库”。你可以从 Python 中强制使用一些语法魔法,例如 Django 的模型,但你应该这样做吗?
标签: python user-interface frameworks