Class to define value holders for e.g. buttons. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations that constrain the type of the value returned from get().
| 375 | |
| 376 | |
| 377 | class Variable: |
| 378 | """Class to define value holders for e.g. buttons. |
| 379 | |
| 380 | Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations |
| 381 | that constrain the type of the value returned from get().""" |
| 382 | _default = "" |
| 383 | _tk = None |
| 384 | _tclCommands = None |
| 385 | |
| 386 | def __init__(self, master=None, value=None, name=None): |
| 387 | """Construct a variable |
| 388 | |
| 389 | MASTER can be given as master widget. |
| 390 | VALUE is an optional value (defaults to "") |
| 391 | NAME is an optional Tcl name (defaults to PY_VARnum). |
| 392 | |
| 393 | If NAME matches an existing variable and VALUE is omitted |
| 394 | then the existing value is retained. |
| 395 | """ |
| 396 | # check for type of NAME parameter to override weird error message |
| 397 | # raised from Modules/_tkinter.c:SetVar like: |
| 398 | # TypeError: setvar() takes exactly 3 arguments (2 given) |
| 399 | if name is not None and not isinstance(name, str): |
| 400 | raise TypeError("name must be a string") |
| 401 | global _varnum |
| 402 | if master is None: |
| 403 | master = _get_default_root('create variable') |
| 404 | self._root = master._root() |
| 405 | self._tk = master.tk |
| 406 | if name: |
| 407 | self._name = name |
| 408 | else: |
| 409 | self._name = 'PY_VAR' + repr(_varnum) |
| 410 | _varnum += 1 |
| 411 | if value is not None: |
| 412 | self.initialize(value) |
| 413 | elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)): |
| 414 | self.initialize(self._default) |
| 415 | |
| 416 | def __del__(self): |
| 417 | """Unset the variable in Tcl.""" |
| 418 | if self._tk is None: |
| 419 | return |
| 420 | if self._tk.getboolean(self._tk.call("info", "exists", self._name)): |
| 421 | self._tk.globalunsetvar(self._name) |
| 422 | if self._tclCommands is not None: |
| 423 | for name in self._tclCommands: |
| 424 | self._tk.deletecommand(name) |
| 425 | self._tclCommands = None |
| 426 | |
| 427 | def __str__(self): |
| 428 | """Return the name of the variable in Tcl.""" |
| 429 | return self._name |
| 430 | |
| 431 | def set(self, value): |
| 432 | """Set the variable to VALUE.""" |
| 433 | return self._tk.globalsetvar(self._name, value) |
| 434 |
no outgoing calls
searching dependent graphs…