Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 returns 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.

like image 760
LaserDude11 Avatar asked Dec 27 '25 22:12

LaserDude11


1 Answers

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
like image 60
jfs Avatar answered Dec 30 '25 23:12

jfs