I also have not a lot of practice with Python and have a fundamental problem of understanding the error: AttributeError: 'NoneType' object has no attribute '_root', which only appears, when I define the dec variable BEFORE defining the main window win:
import tkinter as tk
from tkinter import ttk
from tkinter import *
# This variable must be defined AFTER definition of the Tk() window!
dec = tk.BooleanVar()
# Main window
win = Tk()
# # This variable must be defined AFTER definition of the Tk() window!
# dec = tk.BooleanVar()
decreaseButton = Checkbutton(win, text = "Decrease (optional)", variable = dec)
decreaseButton.grid(row=1, column=1, sticky='W')
# Runs the event loop of Tkinter
win.mainloop()
Why do I have to define first the window and than the Boolean variable? What did I not understand from Tkinter?
Thank you everybody for your great help and with best wishes Lars
You can actually look this up at tkinter's
__init__.py.StringVar,IntVar,DoubleVarandBooleanVarall inherits from the classVariable:So you see when a tkinter variable is created, it will lookup for a
masterstored as a global variable_default_root(which isNoneif you have yet to create atkinstance), which is why you receive aAttributeError.But you might ask, why the same does not apply to widgets? That is because
Widgetsinherits from a different base class calledBaseWidgets:So you see when you create a new widget without a master,
BaseWidgetwill actually create a new instance oftkas_default_rootas opposed toVariable. My guess is that there is no reason to create an instance ofTkjust for a variable since nothing needs to be rendered on screen, but the same cannot be applied for a widget.As such, the below doesn't throw an error even you did not create a
Tkinstance yourself: