开发者

Tkinter string callbacks

Here is the situation:

I have an XML file with the menu hiearchy for my app in it. I can display the menu, but defining the callbacks in the XML file only retur开发者_如何学Gons strings.

The more defined problem: I need a way to callback functions via a string. Yeah, there's the

lambda x: pass

deal, but I'm not really sure that's what I need.


I need a way to callback functions via a string.

From the comments to your question I understand that you'd like to do something like:

# ...
callback_str = getcallback_str() # e.g., 'self.logic.account_new'
callback = eval_dottedname(self, callback_str)`

In this case eval_dottedname() function could be implemented as:

def eval_dottedname(obj, dottedname):
    if dottedname.partition(".")[0] != 'self': # or some other criteria
                                               # to limit the context
        raise ValueError
    return reduce(getattr, dottedname.split('.')[1:], obj)

A better approach would be to limit string callbacks to simple identifiers and use a dispatch table like stdlib's cmd module:

  def dispatch(self, callback_str):
      return getattr(self, 'do_' + callback_str, self.default)()      

  def do_this(self):
      pass

  def do_that(self):
      pass
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜