EriktheRed
EriktheRed

Reputation: 584

parameter error when inheriting from tkinter object

I have a class, call it Test, which has a variable var. It uses this variable in its __init__ mathod, and maybe looks something like this:

class Test(object):
    var = 0
    def __init__(self):
        print(self.var)

In order to change this variable before I initialise the class, this seemed logical

test = Test
test.var = 42
test.__init__(test)

...and behaves like I expected it to. (printing 42)
However, when the code looks like this:

class Test(Canvas):
    var = 0
    def __init__(self, parent):
        Canvas.__init__(self, parent)
        self.pack()
        print(self.var)

test = Test
test.var = 42
test.__init__(test, frame) #tkinter frame I had made elsewhere

... it throws an error at the canvas.__init__ line, complaining that

TypeError: _options() missing 1 required positional argument: 'cnf'

I doubt this is a problem with the cnf parameters, as the class works fine when called 'normally', as in test = Test(). I have a feeling the parameters are being passed differently. Can someone shed some light?
Thanks in advance

Upvotes: 0

Views: 44

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385960

You seem to have a misunderstanding of how python classes work.

In your code you're doing test = Test, which does nothing but make test point to the class Test. It does not create an instance of Test.

If you want to change the value of a class value, there's no need to do an assignment to a temporary variable first. For example. to create a class that has var set to zero, and you later want to change it to 42, you can do it this way:

class Test(object):
    var = 0
...
Test.var = 42

Also, you should never call __init__ directly, except perhaps when calling the function of the superclass with the __init__ of a subclass. Instead, you create an instance of the class which will automatically call the __init__ for you:

test = Test()

This all works the same whether you inherit from a tkinter class or any other class.

When you run the following example, it will print out 42:

import tkinter as tk

class Test(tk.Canvas):
    var = 0
    def __init__(self, parent):
        tk.Canvas.__init__(self, parent)
        self.pack()
        print(self.var)

Test.var = 42

root = tk.Tk()
test = Test(root)

Note that because this is a class variable, changing it once will change it for all instances.

Upvotes: 1

Related Questions