Boolean Variable in TKinter 8.5
python, tkinter
Solution
Short answer: Call `root = tk.Tk()` first.
Long answer: The line that is raising the error,
self._tk = master.tk
is failing because `master` is `None`. However, look at the code (in Tkinter.py) above this line:
class Variable:
def __init__(self, master=None, value=None, name=None):
if not master:
master = _default_root
...
self._tk = master.tk
If you explicitly pass a `master` widget to `BooleanVar` (which is a subclass of `Variable`) then `master` would not be `None`. Or, if `_default_root` were not `None`, then `master` would not be `None`.
In a normal Tkinter application, you will make a root window before making a `BooleanVar`. In that case, `tk.BooleanVar()` will not raise an error.
`root = tk.Tk()` sets the `_default_root` global variable to itself (as long as the `useTk` parameter is `True` -- which it is by default). The `_default_root` is used by `BooleanVar` as the widget's master if no master is explicitly set with `tk.BooleanVar(master)`.
So in summary, either call `root = tk.Tk()` or something similar to set the `_default_root` before calling `tk.BooleanVar()`, or pass an explicit master widget as the first argument: `tk.BooleanVar(master)`.
In [1]: import Tkinter as tk
In [2]: root = tk.Tk()
In [3]: x = tk.BooleanVar()
In [4]: x.set(True)
In [5]: x.get()
Out[5]: 1
Problem
I did this inside the python shell: ``` from Tkinter import * v = BooleanVar() ``` But I got the following error: ``` Traceback (most recent call last): File "<pyshell#52>", line 1, in <module> v = BooleanVar() File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 320, in __init__ Variable.__init__(self, master, value, name) File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 185, in __init__ self._tk = master.tk AttributeError: 'NoneType' object has no attribute 'tk' >>> ``` And then while just playing around trying to make it work I tried this: ``` v = BooleanVar ``` And this worked. So I went on to do the next logical thing, checking if the variable has been initialised and got this: ``` >>> v <class Tkinter.BooleanVar at 0xb6f666bc> ``` Then I tried to initialise with the value `True` and for that I used the `set` method: ``` v.set(True) ``` For which I got the following error: ``` Traceback (most recent call last): File "<pyshell#63>", line 1, in <module> v.set(True) TypeError: unbound method set() must be called with BooleanVar instance as first argument (got bool instance instead) ``` What is going on? Please help me with this issue Goal I want to use this as the variable associated with a check button in a menu specs Linux mint 14, python 2.7, Tkinter 8.5