Color maps in matplotlib

To create a scatter chart that uses a selected color palette, enter the name of the selected color scheme as the cmap argument.

The colors are grouped (see documentation). For instance: Sequential – different intensity of one color, Diverging – different intensity of two contrasting colors, Qualitative – different contrasting colors, but matching the palette, e.g Pastel1 – containing different pastel colors.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_title('Chart title')
ax.set_xlabel('X axis label')
ax.set_ylabel('Y axis label')

# x - list with X axis values, e.g. product name
# y - list with Y axis values, e.g. product price
# intensivity - a list with numbers corresponding to the intensity of the attribute
# cm - name of the selected color palette

ax.scatter(x, y, c=intensivity,  cmap=cm)  
  # e.g: plt.scatter(x, y, c=intensivity, s=50,  cmap='plasma')

mappable = ax.collections[0]
cbar = fig.colorbar(mappable=mappable)

The s parameter is the size of drawn characters.

To display a colorbar that shows the intensity of a given feature for the displayed point, the mappable object should be specified as a parameter, which for the scatter plot is stored as an element of the AxesSubplot collections list.

As a result, on the chart, which may show, for example, the name of the product and the price, you can add additional information using the color, e.g. popularity among buyers or the quantity of goods in the warehouse (e.g. green – the product is available without any problems, up to red – no goods in stock) )

DataFrame object in Pandas based on data from pdf file

Reading data from a pdf file requires the tabula-py module to be installed. This module also enables saving the read data to a data file in csv or json format.

import tabula
df_list = tabula.read_pdf('file.pdf')

The read_pdf function reads one page from a pdf file by default, if no value is given for the pages parameter (if you want to load all pages: pages = ‘all’).

The above function returns a list object containing successive DataFrame objects, for example:

df = df_list[0]        # first DataFrame object

Loading data from csv file to numpy.ndarray

When there are no missing values ​​in the source data, we can use the numpy.loadtxt() function.

However, if there is no value in the loaded file, instead of the above function, we can use the numpy.genfromtxt() function, i.e.

import os
import numpy as np
script_dir = os.path.dirname(__file__)
path_to_file = os.path.join(script_dir, 'data_file.csv')

data_array = np.genfromtxt(path_to_file, dtype='str')

The genfromtxt() function returns an object of type numpy.ndarray. As additional function parameters, we can add e.g.

  • delimiter - determines which sign separates particular values
  • skip_header - specifies how many lines from the beginning of the file are to be skipped
  • autostrip - a bool parameter specifying whether spaces should be automatically removed

A list of all parameters can be found here.

Decorators with parameters – Fizz Buzz game

First, I will define a numbers function that returns a dictionary, where the keys are integers in the range given as the argument to the function (from start to end inclusive).

numbers() function source code:

def numbers(start, end):
    dict = {}
    for number in range(start, end + 1):
        dict[number] = ''
    return dict

The function can be modified using the decorators with parameters.

My decorator function that modifies dictionary values:

def fizzbuzz(number, message):
    def decor(func):
        def wrapper(*args):
            dict = func(*args)
            for key in dict:
                if not (key % number):
                    dict[key] += message
            return dict
        return wrapper
    return decor

Function numbers() definition with the decorator:

@fizzbuzz(5, 'BUZZ')
@fizzbuzz(3, 'FIZZ')
def numbers(start, end):
    dict = {}
    for number in range(start, end + 1):
        dict[number] = ''
    return dict

Calling the numbers function will not change, e.g. to display dictionary values ​​with keys from 0 to 15:

print(numbers(0, 15))

Modification by using a decorator is done behind the scenes.

Django #4

You can test the application by creating a free account here.
You can get the source code from GitHub here.

In this post I will present views responsible for car management and repairs.

▣ I will start with the main view showing the cars entered by the user.

The maximum number of entries per page is 10 cars.

After clicking on a particular car, the repairs of a given car are displayed.

Both car and repair entries are sorted by date, i.e. the newest entries are displayed first.

The view class displaying cars inherits from the ListView class and the LoginRequiredMixin class (so that access is only possible for logged in users).

First, I define all the class attributes, i.e. the model used – Car, the template used – cars.html, the name of the object under which the data in the context is available – context_object_name – ‘cars’, and the number of entries on the page – 10 vehicles.

In this class, I override two methods – get_queryset (), which is responsible for filtering data, and get_context_data (), in which I complete the context data with data from the search field.

CarListView () class source code:

class CarsListView(LoginRequiredMixin, ListView):
    model = Car
    template_name = 'cars/cars.html'
    context_object_name = 'cars'
    paginate_by = 10

    def get_queryset(self):
        if self.request.GET.get('q'):
            q = self.request.GET.get('q')
            make_results = self.model.objects.filter(
                user=self.request.user, make=q).order_by('-pk')
            model_results = self.model.objects.filter(
                user=self.request.user, model=q).order_by('-pk')
            if make_results.exists():
                return make_results
            elif model_results.exists():
                return model_results
                return self.model.objects.none()
        return self.model.objects.filter(user=self.request.user).order_by('-pk')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['q'] = self.request.GET.get('q', '')
        return context

The get_queryset() method lists all of the user’s vehicles. The last added car is visible first (sort ‘-pk’). If the make or model of the vehicle (s) was entered in the search field, only these vehicles will be displayed.

The get_context_data() method adds an entry from the search field to the context, thanks to which the data about car repairs is displayed correctly when dividing cars into individual pages.

▣ Adding a vehicle is done by pressing the Add Car button in the application menu.

The view that handles adding a car is the AddCarView () class, and the template that displays the add car form is car_form.html (the same template also supports updating auto data).

The AddCarView () class inherits the functionality from the CreateView () and LoginRequiredMixin class (only logged in users can create a new vehicle).

I define the following view class attributes: model that the class uses – Car, fields – the form fields to be visible, and success_url – the url that will be loaded after successfully completing the form.

I override the form_valid() method, which adds the user who created the new car (the Car model requires a user attribute to be defined).

The source code for the AddCarView class :

class AddCarView(LoginRequiredMixin, CreateView):
    model = Car
    fields = ['make', 'model', 'vrn', 'year']
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

▣ Removing the car is done using the DeleteCarView () view class, and the template that prompts you to delete the auto is the car_confirm_delete.html file (displays the Delete button that deletes the auto and the Cancel button that returns to the previous page).

DeleteCarView () class inherits functionality from DeleteView, LoginRequiredMixin class (only logged in user can delete auto) and UserPassesTestMixin (user can delete auto created by himself).

I define the model arguments – the used Car model and success_url – the address to which it will be loaded after the successful removal of the car – in this case, the view showing all the user’s cars.

I am creating a test_func () method which checks if the user who wants to delete the car is the person who created the auto (the user can only delete the cars he created).

I override the delete () method, which additionally displays the message about deleting the car.

The DeleteCarView() class source code:

class DeleteCarView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Car
    success_url = '/'

    def test_func(self):
        if self.get_object().user == self.request.user:
            return True
        return False

    def delete(self, request, *args, **kwargs):
        success_message = f'Car {self.get_object()} has been deleted'
        messages.success(self.request, success_message)
        return super().delete(request, *args, **kwargs)

▣ The vehicle data is updated using the UpdateCarView () class, while the template displaying the form for changing this data is car_form.html.

The UpdateCarView () class inherits functionality from the UpdateView class as well as the LoginRequiredMixin classes (only the logged in user can update the data) and UserPassesTestMixin (a function is called to check if the user who wants to modify is the one who created the auto).

I define class attributes: model – specifies the model that is used to change the data – in this case the Car model, fields attribute – specifying which form fields are to be available and success_message – a text message about updating the car data.

Two methods are defined: test_func () and get_success_url ().

The test_func () method checks if the user who wants to modify the car’s data is the one who created the car.

The get_success_url() method displays a message about the data change and returns to the page with the name: car_detail – displaying repairs for a given car. As additional parameters, they are sent using the GET method: row, p and q that define the row and page of the car in the table and the text string from the search box.

Code of the UpdateCarView() class:

class UpdateCarView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Car
    fields = ['make', 'model', 'vrn', 'year']
    success_message = 'Car info has been updated'

    def get_success_url(self, **kwargs):
        row = self.request.GET.get('row')
        p = self.request.GET.get('p')
        q = self.request.GET.get('q')
        options = '?p=' + p + '&row=' + row
        options += '&q=' + q
        messages.success(self.request, self.success_message)
        return reverse_lazy('car_detail') + options

    def test_func(self):
        if self.get_object().user == self.request.user:
            return True
        return False

▣ Adding a repair note is defined in the AddRepairView() class, and the form is defined in the repair_form.html template.

This class has the following arguments: model – specifying the model used – in this case Repair. The next argument: fields – specifies what the form fields are displayed. The last argument is the success_message string displayed after the repair note was successfully added.

The methods in the AddRepairView() class are: get_context_data(), form_valid(), and get_success_url().

The get_context_data() method adds a Car object to the context, making it visible in the template.

The form_valid () method uses the data from the form to create a new model instance. To properly create an instance of the Repair class, it is necessary to provide a foreign key – a Car object that identifies the vehicle to which a given repair note relates.

The get_success_url () method specifies the address of the page to be displayed when a new note is successfully added. In this case, a page named car_detail as defined in cars / will be displayed.

class AddRepairView(LoginRequiredMixin, CreateView):
    model = Repair
    fields = ['date', 'description']
    success_message = 'New repair has been added'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['car'] = Car.objects.get(id=self.kwargs['pk'])
        return context

    def form_valid(self, form, **kwargs): = Car.objects.get(id=self.kwargs['pk'])
        return super().form_valid(form)

    def get_success_url(self, **kwargs):
        row = self.request.GET.get('row')
        p = self.request.GET.get('p')
        q = self.request.GET.get('q')
        options = '?p=' + p + '&row=' + row
        options += '&q=' + q
        return reverse_lazy('car_detail') + options

to be continued

Django #3

You can see the application deployed on heroku here.
You can get a source code here.

In previous posts, I described user management in the application, i.e. a new user can register – create an account on the site, a registered user can log in, log out or change the password.

Then I’ll describe the main functionality of the app – car and repair records.

For this purpose, in the project file, I will attach the mapping of addresses related to cars application.

After the changes, the project file will look like this:

from django.contrib import admin
from django.urls import path, include
from users import views as users_views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('', include('cars.urls')),
    path('register-user/', users_views.RegisterUser.as_view(
        template_name='users/register-user.html'), name='register_user'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('change-password/', users_views.ChangePassword.as_view(
        template_name='users/change-password.html'), name='change_password'),

The file created in the cars application also takes into account mapping addresses to appropriate views. The file from the cars application looks like this:

from django.urls import path
from .views import (
urlpatterns = [
    path('', CarsListView.as_view(), name='cars'),
    path('add-car/', AddCarView.as_view(), name='add_car'),
    path('car/', RepairsListView.as_view(), name='car_detail'),
    path('car/<int:pk>/update/', UpdateCarView.as_view(), name='update_car'),
    path('car/<int:pk>/delete/', DeleteCarView.as_view(), name='delete_car'),
    path('car/<int:pk>/new-repair/', AddRepairView.as_view(), name='add_repair'),

The main view defined in the CarListView class displays all the user’s cars.

Remember to add the application in the project’s file in the INSTALLED_APPS list, e.g. for cars it will be an element: ‘cars.apps.CarsConfig’.

I used the pre-installed user model in the users application. In the cars application, I created models – objects mapping database tables.

These models will define: vehicle – Car model and repair – Repair model. The file looks like this:

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator

class Car(models.Model):
    make = models.CharField(max_length=10)
    model = models.CharField(max_length=10)
    vrn = models.CharField(max_length=10)
    year = models.IntegerField(,
                               validators=[MinValueValidator( - 100),
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.make} {self.model}'

class Repair(models.Model):
    date = models.DateField(
    description = models.TextField()
    car = models.ForeignKey(Car, on_delete=models.CASCADE)

    def __str__(self):
        lead = self.description[:10] + '...'
        return lead

The Car model contains make, model, vrn, year, and user attributes that describe the vehicle make, model, vehicle registration number, and year of manufacture, as well as a foreign key containing the user object that created the vehicle entry.

The year field has validators that make it impossible to enter a car with a production year 100 years older than the current date and newer than the current year.

The on_delete option of the user attribute has the default value CASCADE, ie deleting a user will also delete all his cars.

The Repair model includes the attributes: date – repair date, description – repair details and a foreign key car – which car the repair concerns.

The __str__() method prints the header that is the beginning of the repair description (leading 10 characters).

To be able to edit entries of both models from the administration panel, you need to add both models to the file of the cars application, i.e.

from django.contrib import admin
from .models import Car, Repair

In the next post, I will describe the views that define individual functionalities, i.e. displaying cars belonging to the user, adding repairs, and searching for cars using the search box on the website.

Django #2

The login and logout views are predefined as LoginView and LogoutView classes, so you only need to put the appropriate entries in the file (as described in part 1) and create template files, i.e.

login.html template:

{% extends 'cars/base.html' %}
{% load crispy_forms_tags %}

{% block content %}
  <div class="row justify-content-center">
    <div class="col-4">
      <form method="POST" class="form-control-sm">
       {% csrf_token %}
       <fieldset class="form-group">
         <legend class="border-bottom text-primary">
            Log In
          {{ form|crispy }}
        <button class="btn btn-secondary" type="submit">Login</button>
        <p class="text-muted text-small mt-5 ml-2">Need an Account? <a href="{% url 'register_user' %}">Sign up</a></p>
{% endblock %}
login.html template

logout.html template:

{% extends 'cars/base.html' %}

{% block content %}
 <div class="row justify-content-center mb-5">
    <div class="col-4">
	   <h4 class="border-bottom text-primary mt-2">You're logged out now</h4>	
  <div class="text-muted text-small ml-2 mt-5">Back to: <a href="{% url 'login' %}">login page</a></div>
{% endblock %}

It still remains to create a view responsible for changing the password. The view class will inherit from the CreateView class as well as the LoginRequiredMixin class. The LoginRequiredMixin class adds the functionality that only the logged in user can change the password.

ChangePassword () view class code:

class ChangePassword(LoginRequiredMixin, CreateView):
    form_class = PasswordChangeForm

    def get(self, request, *args, **kwargs):
        form = PasswordChangeForm(request.user)
        return render(request, 'users/change-password.html', {'form': form})

    def post(self, request, *args, **kwargs):
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user =
            update_session_auth_hash(request, user)
            messages.success(request, 'Password changed!')
            return redirect('cars')
        return render(request, 'users/change-password.html', {'form': form})

In the class above, I override the get() and post() methods.

When the page is displayed using the get() method, an empty password change form is displayed for the user.

When the page is displayed using the post () method, the submitted data is validated and, if correct, the changed password is saved, a password change message is displayed and redirected to a page named cars.

It remains to add the template file, ie change-password.html.

{% extends 'cars/base.html' %}
{% load crispy_forms_tags %}

{% block content %}
  <div class="row justify-content-center">
   <div class="col-4">
	  <form method="POST" class="form-control-sm">
      {% csrf_token %}
      <fieldset class="form-group">
        <legend class="border-bottom text-primary">
            New Password Settings
        {{ form|crispy }}
      <button class="btn btn-secondary" type="submit">Save</button>
{% endblock %}
change-password.html template

to be continued….

Django #1

Below is a listing of the required packages for the project:


I recommend creating a separate virtual environment for the project (how to create a virtual environment I described here).

All packages except django-crispy-forms are installed when the django package is installed.

In the directory containing the venv subdirectory, create a project with the command: django-admin startproject project_name

Startproject command creates the project’s main directory and a file for managing the project.

You can then create a project administrator, i.e. a user with maximum administrative privileges, so that you can use the web admin panel. However, first you need to run a migrate: python migrate thanks to which the appropriate tables are created in the database, e.g. admin, auth etc.

After migration, you can create an administrative account with the command: python createsuperuser

The project directory contains the following files and directories:

├── project_name
│ ├──
│ ├──
│ ├── pycache
│ ├──
│ ├──
│ └──
├── db.sqlite3

By default, the data is placed in the sqlite3 database (db.sqlite3 file), which is a good solution when creating a project, and finally you can use a different database (Django includes support for PostgreSQL, MySQL and many others). Changing the default database only requires modifying the data from the DATABASES section of the project’s file.

In order to separate the individual components of the project, I made two components, i.e. users – responsible for user management and cars for vehicle management. In Django, these are called apps. To create them, type: python startapp users and python startapp cars

I will start with the users application, in which new users will be able to create accounts, log in, log out, and change their access password.

To define URL mapping to specific view classes, I modify the project file, i.e.

from django.contrib import admin
from django.urls import path
from users import views as users_views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('register-user/', users_views.RegisterUser.as_view(
        template_name='users/register-user.html'), name='register_user'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('change-password/', users_views.ChangePassword.as_view(
        template_name='users/change-password.html'), name='change_password'),

For example, after entering the address ending with: register-user /, the class RegisterUser () is called from the file and the assignment is given a name that we can use in templates.

For a class to be used as a view, its as_view () method must be called. As an argument I have given the template_name argument, in which I give the name of the template that displays the given page. You might as well pass this argument as a class attribute in a view, but for consistency with the rest of the views, I have included it here.

The code of the RegisterUser () class from the file of the users application looks as follows (at the beginning I put the required imports):

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.contrib.auth import login, authenticate
from django.views.generic import CreateView
from django.contrib import messages

class RegisterUser(CreateView):
    form_class = UserCreationForm

    def get(self, request, *args, **kwargs):
        return render(request, 'users/register-user.html', {'form': UserCreationForm()})

    def post(self, request, *args, **kwargs):
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            messages.success(request, f'Welcome, {username}!')
            return redirect('cars')
        return render(request, 'users/register-user.html', {'form': form})

The RegisterUser () class inherits from the CreateView class, and the form is defined by the UserCreationForm class.

When the page is displayed using the GET method, an empty form appears, while if some data is already provided in the form, it is passed using the POST method.

To handle GET and POST, I override the get() and post() methods of RegisterUser(), respectively. In the post() method, the form is validated and if the form is correct, then the data from the form is saved, ie the user is created using the save() method. By default, this is a user with no administrative privileges. He is logged in using the data provided during registration. A new message with the tag Success will be displayed after redirecting to an address named cars. The message is displayed only once.

It remains to create the register-user.html template for RegisterUser(). For this purpose, I create a template directory in the users application according to the convention – in the templates directory, create another directory with the name consistent with the name of the application, i.e.


The code of register-user.html is part of a larger whole, or more precisely, the base.html file from the cars application, which has not been created yet.

Applications can use their templates, so the look defined in cars in base.html is preserved in register-user.html

The template also enables the use of crispy_forms tags to make the form look better.

Each form must contain csrf_token, thanks to which the website is automatically immune to some forms of attacks (details: here).

Code of register-user.html file:

{% extends 'cars/base.html' %}
{% load crispy_forms_tags %}

{% block content %}
  <div class="row justify-content-center">
    <div class="col-4">
      <form method="POST" class="form-control-sm">
        {% csrf_token %}
        <fieldset class="form-group">
          <legend class="border-bottom text-primary">
            {{ form|crispy }}
          <button class="btn btn-secondary" type="submit">Register</button>
{% endblock %}

Django – web framework

In this series, I will describe the basics of the Django framework using the example of an application for recording repairs related to your car.

The application is similar to the one described in this posts, but the use of a web framework forced additional functionalities, e.g. user accounts support.

You can create your own account and log in to the application here.

You can download the project code here.

Tkinter GUI for CRUD app #3

Below I have described the code of the NewCarWindow class describing a new child window, created when the add_car_button button is clicked:

import tkinter as tk
from sql_helper import Helper

class NewCarWindow():
    def __init__(self, root, parent):
        self.top_level = tk.Toplevel(root)
        self.helper = Helper()
        self.parent = parent
        x = self.top_level.winfo_screenwidth()
        y = self.top_level.winfo_screenheight()
        geometry = '+{}+{}'.format(int((x / 2) - 100),
                                   int((y / 2) - 100))
        size = self.top_level.geometry(geometry)

First, I import the required classes, then the init () method sets the child window’s position relative to the main window.

        self.top_level.title('Add car')
        label_make = tk.Label(self.top_level, text='Make: ',
                              font=12, padx=20, pady=10).grid(row=0, column=0)
        label_model = tk.Label(self.top_level, text='Model: ',
                               font=12, padx=20, pady=10).grid(row=1, column=0)
        label_year = tk.Label(self.top_level, text='Year: ',
                              font=12, padx=20, pady=10).grid(row=2, column=0)
        label_vrn = tk.Label(self.top_level, text='VRN: ',
                             font=12, padx=20, pady=10).grid(row=3, column=0)
        label_vin = tk.Label(self.top_level, text='VIN: ',
                             font=12, padx=20, pady=10).grid(row=4, column=0)

Then the title of the child window is set. The grab_set () method makes the main window inactive – e.g. you cannot press any button, etc.

The next step is to set the text labels describing the input fields, which I define below, together with variables of the StringVar type that store the values ​​entered into these fields:

    self.make_sv = tk.StringVar()
    self.model_sv = tk.StringVar()
    self.year_sv = tk.StringVar()
    self.vrn_sv = tk.StringVar()
    self.vin_sv = tk.StringVar()
    self.info_sv = tk.StringVar()

    entry_make = tk.Entry(
            self.top_level, text=self.make_sv)
    entry_make.grid(row=0, column=1)
    entry_model = tk.Entry(
            self.top_level, text=self.model_sv).grid(row=1, column=1)
    entry_year = tk.Entry(
            self.top_level, text=self.year_sv).grid(row=2, column=1)
    entry_vrn = tk.Entry(
            self.top_level, text=self.vrn_sv).grid(row=3, column=1)
    entry_vin = tk.Entry(
            self.top_level, text=self.vin_sv).grid(row=4, column=1)

    info_label = tk.Label(self.top_level, textvariable=self.info_sv,
                              font=12, padx=10, pady=10, fg='red').grid(row=5, column=0, columnspan=2)

The info_label label is used to display a message in the case of not filling all the required fields to create a new car.

        save_button = tk.Button(self.top_level, text='Save',
        save_button.bind('<Return>', self.save_new_car)
        save_button.grid(row=6, column=1, sticky='W', padx=10)
        cancel_button = tk.Button(self.top_level, text='Cancel',
        cancel_button.grid(row=6, column=1, sticky='W', padx=70)
        cancel_button.bind('<Return>', self.top_level.destroy)

At the bottom of the window, the Save and Cancel buttons are displayed to save the data about the new car in the database or close the ‘Add car’ window.

def save_new_car(self, event=None):
    if self.make_sv.get() and self.model_sv.get() and self.year_sv.get() and self.vrn_sv.get() and self.vin_sv.get():
        self.info_sv.set('Please fill in all entry fields')

The code for the save_new_car() method is activated if the Save button is pressed. If all the values ​​needed to create a new car have been filled, the add_car () method of the Helper class is run, then the child window is closed and the entries about cars in the main window are updated using the show_cars() method of the CarManager class.

The ‘Add car’ child window. The message is displayed when all input fields are not filled in. Focus is set on the first element.


The code of the RepairsWindow class, activated after pressing the main button repair_button:

import tkinter as tk
from tkinter import ttk
from sql_helper import Helper
from date_picker import DatePicker

class RepairsWindow():
    def __init__(self, root, car):
        self.top_level = tk.Toplevel(root)
        self.root = root
        self.top_level.grab_set() = car
        self.helper = Helper()

        x = self.top_level.winfo_screenwidth()
        y = self.top_level.winfo_screenheight()
        geometry = '+{}+{}'.format(int((x / 2) - 150),
                                   int((y / 2) - 150))
        size = self.top_level.geometry(geometry)

First, I import all the necessary classes. In the init () method, a new window is created – an instance of the TopLevel class, and the window title is set to ‘Repairs’. Then, using the grab_set () method, the possibility of starting widgets from the main window is blocked. The and self.helper variables are set and the child window is positioned relative to the main window.

        toolbox_frame = tk.Frame(self.top_level)
        toolbox_frame.grid(column=0, row=0, sticky='W')
        self.add_repair_img = tk.PhotoImage(file='Resources/add_repair.gif')
        add_repair_button = tk.Button(
            toolbox_frame, image=self.add_repair_img, command=self.add_repair)
        add_repair_button.grid(column=0, row=0, sticky='W')
        add_repair_button.bind('<Return>', self.add_repair)
        add_repair_button.bind('<KP_Enter>', self.add_repair)
        if car.sold:

A toolbox_frame is created in the child window, in which the add_repair_button button is placed. The add_repair () method is bound to the created button – activated with the mouse or keyboard after pressing Enter on the numeric or main keyboard. Then it is checked if the car is not marked as ‘sold’, then the button for adding new repairs is inactive.

        col_headers = ('No', 'Date', 'Description')
        self.repairs_tv = ttk.Treeview(self.top_level, columns=col_headers,
                                       show='headings', selectmode='none')
        self.repairs_tv.tag_configure('c1', background='ivory2')
        self.repairs_tv.tag_configure('c2', background='ivory3')
        for i, col in enumerate(col_headers):
            self.repairs_tv.heading(col, text=col)
            self.repairs_tv.column(col, anchor='center')
            if i == 0:
                self.repairs_tv.column(col, width=50, stretch='NO')
        self.repairs_tv.grid(column=0, row=2,  sticky='NSWE')

        scrollbar = tk.Scrollbar(self.top_level, command=self.repairs_tv.yview)
        scrollbar.grid(column=1, row=2, sticky='NS')

The next code snippet describes creating the Treeview widget that will display repair data. To improve readability, I created two tags that set the background colors of the entered widget elements. The init () method ends by calling the show_repairs () method, which adds repairs to the Treeview widget.

    def show_repairs(self):
        repairs = self.helper.show_repairs(
        for i, repair in enumerate(repairs, start=1):
            repair = (i, repair[0], repair[2])
            if i % 2:
                self.repairs_tv.insert('', 'end', values=repair, tag='c1')
                self.repairs_tv.insert('', 'end', values=repair, tag='c2')

The show_repairs () method calls the appropriate Helper method to retrieve the repair data from the database. Then the repairs_tv items are deleted and the updated data is set. To improve readability, the following lines are alternately colored, i.e.

Repairs window.

Code of the add_repair method, which is activated when the add_repair_button button is pressed with the mouse or the keyboard:

    def add_repair(self, event=None):
        self.add_repair_frame = tk.Frame(self.top_level)
            column=0, row=1, pady=20, sticky='WE')

        date_label = tk.Label(self.add_repair_frame,
                              text='Date:').grid(column=0, row=2)
        self.date_sv = tk.StringVar()
        self.date_entry = tk.Entry(self.add_repair_frame,
        self.date_entry.grid(column=1, row=2, sticky='W')

        self.cal_img = tk.PhotoImage(file='Resources/calendar.gif')
        show_cal_btn = tk.Button(self.add_repair_frame, image=self.cal_img,
                                 command=self.show_cal, relief='flat').grid(column=1, row=2, sticky='W', padx=170)

        description_label = tk.Label(self.add_repair_frame,
                                     text='Description:').grid(column=0, row=3)
        self.description_sv = tk.StringVar()
        self.description_entry = tk.Entry(self.add_repair_frame,
        self.description_entry.grid(column=1, row=3, ipadx=200)
        save_button = tk.Button(self.add_repair_frame, text='Save',
        save_button.grid(column=1, row=4, pady=10, sticky='E')
        save_button.bind('<Return>', self.save_repair)
        save_button.bind('<KP_Enter>', self.save_repair)
        cancel_button = tk.Button(self.add_repair_frame, text='Cancel',
        cancel_button.grid(column=1, row=4, sticky='E', padx=60)
        cancel_button.bind('<Return>', self.cancel_repair)
        cancel_button.bind('<KP_Enter>', self.cancel_repair)
Repairs window after pressing the add_repair_button button.

Code of the cancel_repair () method that hides the repair_frame:

    def cancel_repair(self, event=None):

Save_repair () method code:

def save_repair(self, event=None):
        if self.date_sv.get() and self.description_sv.get():
            self.helper.add_repair(, self.date_sv.get(),

In the save_repair () method, basic form validation is performed, ie it is checked if all required fields to create a repair entry are filled in.

If so, the repair note is saved in the database (add_repair method of the Helper class), and then the entries about the repairs are updated and the repair_frame is hidden.

The remaining show_cal () method, which is activated after pressing the show_cal_btn button:

    def show_cal(self, event=None):
        date_picker = DatePicker(self.top_level, self.date_entry, '%d-%m-%Y')

The show_cal () method creates an instance of the DatePicker class that I created to get the date and insert it into the given Entry field. As an argument, this class allows you to insert the selected date formatting, so that, for example, in the application settings the user could choose how the date should be displayed.

You can find the code of the DatePicker class in this post.

Selecting a date using my DatePicker class


P.S. If the main window is to run as maximized, but with the resize option, then in the init () method of the CarManager class, add:

root.attributes('-zoomed', True)

P.P.S. If entries about cars are to be displayed with row formatting, the show_cars () method can be modified by adding tags that define row colors, i.e.

    def show_cars(self):
        all_cars = self.helper.show_all_cars()
        for i, car in enumerate(all_cars, start=1):
            car = list(car)
            car.insert(0, i)
            if i % 2:
                self.car_tview.insert('', 'end', values=car, tag='c2')
                self.car_tview.insert('', 'end', values=car, tag='c1')
            self.car_tview.tag_configure('c1', background='ivory3')
            self.car_tview.tag_configure('c2', background='ivory2')
Treeview widget with formatting tags