Home > OS >  Python tkinter strange error on subclassing Frame
Python tkinter strange error on subclassing Frame

Time:09-12

The code below works just fine and makes a (very small) decent user-interface display – as long as line 21 is commented out. If line 21 is in, I get the following very strange error message:

'CheckButtonPair' object has no attribute 'tk'
  File "/Users/ken/Shoshin/AimGUI/try/ClassError.py", line 28, in __init__
    super().__init__(self, parent)
  File "/Users/ken/Shoshin/AimGUI/try/ClassError.py", line 21, in __init__
    self.check2 = CheckButtonPair(self.root, "hello")
  File "/Users/ken/Shoshin/AimGUI/try/ClassError.py", line 36, in <module>
    Example()

Here's the code:

import tkinter as tk

class Example():
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("some application")

        self.label1 = tk.Label(self.root, text="1. Aim the camera")
        self.label1.grid(row=0, column=1, sticky="ew")

        # checkbox stuff
        self.check1 = tk.Frame(self.root, width=150, height=140)
        self.check1.grid(row=2, column=1, sticky="ew")
        self.state = tk.IntVar(0)
        self.check = tk.Checkbutton(self.check1, variable=self.state) 
        self.check.pack(side=tk.LEFT, padx=40)
        self.button = tk.Button(self.check1, text="check this")
        self.button.pack(side=tk.LEFT)
        
        # check box as class
        self.check2 = CheckButtonPair(self.root, "hello")

        self.root.mainloop()

class CheckButtonPair(tk.Frame):
    def __init__(self, parent, text, background="orange"):
        #self.parent = parent
        super().__init__(self, parent)
        
        self.state = tk.IntVar(0)
        self.check = tk.Checkbutton(self, variable=self.state) 
        self.check.pack()
        self.button = tk.Button(self, text=text)
        self.button.pack()

Example()

What on earth am I doing wrong? How on earth would it think that I am asking for a tk attribute? BTW, don't tell me I can simplify CheckButtonPair into one item, because it is just a test, it is going to get more complicated in reality.

CodePudding user response:

You should not pass self in super().__init__(self, parent). It should be this:

super().__init__(parent)
  • Related