0

Im trying to figure out how to change a string into a name of a Button.

For example if I had the string self._name = 'self._prentice', I would like to make self._prentice = tk.Button(master). I need to do it this way as the string could be any name and I need to create a way of storing this so I can later pack or destroy it.

I've tried using exec, however I could only get it to work for integers and not buttons.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Possible duplicate of [Calling a function of a module from a string with the function's name in Python](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python) – glS Dec 12 '16 at 15:42
  • @glS it's indeed a duplicate but the one you link too is possibly not the best exemple... – bruno desthuilliers Dec 12 '16 at 15:43
  • If you need to create a dynamic number of buttons with different names, consider storing them in a single dictionary instead of as multiple attributes. Additional reading: [How do I create a variable number of variables?](http://stackoverflow.com/q/1373164/953482) – Kevin Dec 12 '16 at 15:45
  • 1
    Suggest you read [_Why you don't want to dynamically create variables_](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html). – martineau Dec 12 '16 at 16:08
  • Whatever problem you're trying to solve, there are almost certainly better ways to solve it. We have an [xy](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) problem here: you have problem "X" and think that "Y" is the solution so you ask about "Y". However, you should try to ask about "X" instead. Usually when people ask a question like this, the answer is to store the widgets in a dictionary, so that your "any name" is used as the key, and the widget is the value. – Bryan Oakley Dec 12 '16 at 17:20

2 Answers2

1

Use setattr:

setattr(self, '_prentice', tk.Button(master)).

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • With a `self._name = '_prentice'`, a `setattr(self, self._name, tk.Button(master))` might be more useful to OP. – martineau Dec 12 '16 at 16:03
-2

In python, the instance variables of a class are stored in a dictionary, self.__dict__, so instead of

self._prentice = tk.Button(master)

you could write

self.__dict__['_prentice'] = tk.Button(master)

or, in your case

self.__dict__[self._name] = tk.Button(master)
blue_note
  • 27,712
  • 9
  • 72
  • 90
  • 2
    It should be preferable to use `setattr` rather than directly changing `self.__dict__`. – DeepSpace Dec 12 '16 at 15:40
  • Dont. Seriously dont. It bypasses all the attribute lookup rules and will break computed properties etc. The answer is `getatt(obj, name) / setattr(obj, name, value)` – bruno desthuilliers Dec 12 '16 at 15:41