You are using the special method __init__
as a class name and not as a class method (I do not know what you are trying to do on that line, you may be confusing concepts.).
The __init__
method is in charge of initializing the class, of giving a certain status to your object as soon as it is instantiated. It is executed automatically when the class is instantiated and is something similar to what is known as "constructor" in other languages. In your case, it is responsible for receiving the root instance for your Label
as parameter and creating it.
Look at these two questions for more information:
You must use the reserved word class
to define a class and def
to define methods (such as the __init__
method).
The use of for modulo import *
is a very bad practice that you should avoid, even more if you are learning (see PEP 8 ). The code is less readable and can induce errors by overwriting some method by mistake (especially in complex libraries). You will find it often, especially in Tkinter tutorials (partly because of the documentation of effbot. org ), which does not imply that it's not a bad idea, like the famous using namespace std;
of C ++ ... :). Nothing happens in a simple example like this, but to avoid taking bad habits, better avoid it. Remember the zen from Python:
"Explicit is better than implied"
Instead use one of the following ways:
-
from tkinter import Label, Tk
-
import tkinter
or the most generalized (to save characters):
The self
parameter is a convention. Instance methods must receive as a first parameter the reference to the instance of the class to which they belong. self
is just that, the reference to the instance to which the method belongs. When an instance method is called it is automatically passed. In front of the attributes (as in the __init__
) they indicate that they are instance attributes.
If we have the class:
class Foo:
def bar():
print("Soy un método de la instancia: ", self)
We instantiate and call your method like this:
>>> instancia = Foo()
>>> instancia.bar()
Soy un método de la instancia: <__main__.Foo object at 0x7f4e0a267080>
This is the same as doing (so you understand what self
is):
>>> instancia = Foo()
>>> Foo.bar(instancia)
Soy un método de la instancia: <__main__.Foo object at 0x7f8436622cc0>
You can see a much more extended explanation in the following publication:
Your code has no more problems, apart from a typo in the first parameter when instantiating Label
, it should be like this:
import tkinter as tk
class Interfaz(): #Definición de tu clase llamada Intefaz
def __init__(self, contenedor): #Definición de su método __init__ Intefaz
self.e1 = tk.Label(contenedor, text ="Etiqueta1", fg="black", bg="white")
self.e1.pack()
ventana = tk.Tk() #Instancia de la clase Tk.
miInterfaz= Interfaz(ventana) #Instancia de tu clase Interfaz.
ventana.mainloop()