Home > OS >  Inherited class returns NoneType instance
Inherited class returns NoneType instance

Time:10-20

I'm trying to create my own widget in Tkinter, so I inherited from Frame class. But for some reason, my Food class returns NoneType class instance. Why does it happen and how can I make it return an instance of a Food class?

import tkinter as tk

class Food(tk.Frame):
    def __init__(self,parent,index,name="",price=0):
        tk.Frame.__init__(self, parent)

        self.name = tk.Entry(self)
        self.price = tk.Entry(self)

        self.name.insert(0, name)
        self.price.insert(0, str(price))

        self.name.pack(ipadx=70,ipady=5,side='left',expand=True, fill='x')
        self.price.pack(ipadx=10,ipady=5,side='left')

        self.index=index
        
    def getIndex(self):
        return self.index

if __name__ == "__main__":
    root = tk.Tk()
    print(type(Food(root,1).pack(fill='x'))) # <class 'NoneType'>
    root.mainloop()

CodePudding user response:

This is because you've put the .pack() function inside the type() function, which makes type() to return the return-type of function 'Food(root,1).pack(fill='x')' (which is None) and not the class object 'Food(root,1)' as you wanted.

CodePudding user response:

Note that Food(root,1).pack(fill='x') will get the result of .pack(...) which is always None.

You need to split the line into two lines:

...
frame = Food(root, 1)
frame.pack(fill='x')
print(type(frame))
...
  • Related