Python GUI - Quick Introduction to Tk (tkinter)

Tk is a tool for developing cross-platform desktop applications, that is, native applications with a graphical user interface (GUI) for Windows, Linux, Mac and other operating systems. Technically, Tk is an open source library written in C and originally developed for the Tcl programming language. Hence we usually refer to it as Tcl/Tk. Since its first versions, the Python standard library has included the tkinter module, which allows you to interact with Tk to write desktop applications in Python. Tk's learning curve is relatively small compared to other libraries in the field (like Qt), so any programmer with a minimal background in Python can quickly start building professional GUI applications and distribute them by using packaging tools like cx_Freeze or PyInstaller, which integrate very well with Tk.

Read more…

Send HTML Email With Attachments via SMTP

Starting from Python 3.6, the standard library includes the email package to build email messages (which may eventually contain HTML code and attachments) and the smtplib module to send them through the SMTP protocol, with the possibility of using secure SSL and TLS connections. In this post we will learn how to build and send an email in Python through any SMTP server (Gmail, Outlook, Yahoo, etc. or a custom SMTP service).

Let's start by sending a plain text email. The first step is to import the necessary modules. The email package has several modules (email.message, email.parser, etc.) to work with emails. We are only interested in email.message, which contains the necessary class (EmailMessage) to create an email. On the other hand, we will need the smtplib module to send it through an SMTP server once the message has been created.

from email.message import EmailMessage
import smtplib

Read more…

How to Return From a Thread

Python allows us to spawn new threads of execution through an elegant API by using the threading standard module. Here is a simple example program that runs a worker() function within a new thread:

import threading
import time
def worker():
    """
    This function runs in a new thread.
    """
    # Run some random code.
    for _ in range(3):
        print("Hello from thread!")
        time.sleep(1)
# Set up the thread instance and start execution.
t = threading.Thread(target=worker)
t.start()

This kind of procedure is useful when there is need to execute a heavy task on the background without blocking the main thread, specially when the main thread runs our app's UI. But what happens if worker() returns a value that we actually need in the main thread, or wherever t.start() was called?

Read more…

Creating and Using Decorators

Decorators are very useful, powerful tools and, once properly understood, easy to implement. To be sure, this is what we are talking about:

@decorator
def func():
    pass

If you have seen this syntax and want to know what it means and how to use it, then keep reading.

Read more…

Textbox (Entry) Validation in Tk (tkinter)

We have already seen in a previous post how to work with textboxes using the ttk.Entry class in a Tcl/Tk desktop application. Now let's see how to validate the text that the user writes within a certain textbox, for example, in order to allow only numbers, dates, or other formats, or to apply other types of restrictions.

Let's start with the following code, which creates a window with a textbox (entry).

from tkinter import ttk
import tkinter as tk
root = tk.Tk()
root.config(width=300, height=200)
root.title("My App")
entry = ttk.Entry()
entry.place(x=50, y=50, width=150)
root.mainloop()

Suppose we want the user to only be able to enter numbers. To do this, we first create a function that will be called every time the user types, pastes, or deletes text in the textbox:

def validate_entry(text):
    return text.isdecimal()

Read more…

Progress Bar in Tk (tkinter)

A progress bar is useful to display the status of an operation or task. The ttk.Progressbar widget can indicate the evolution of a certain process (for example, downloading a file from the Internet) or simply represent that an operation is being executed, in those cases in which the remaining time is unknown.

Standard Progress Bar

Let's start with a little code that creates a window with a horizontal progress bar.

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Progress Bar in Tk")
progressbar = ttk.Progressbar()
progressbar.place(x=30, y=60, width=200)
root.geometry("300x200")
root.mainloop()
/images/progress-bar-in-tk-tkinter/progressbar-horizontal.png

Read more…

Tk after() Function (tkinter)

The tkinter.Tk.after() function allows you to program the execution of your own function so that it is executed after a certain amount of time. However, it can also be used to tell Tk to execute a function every a given amount of time, which is the most common usage. Let's start by creating a simple window with a label (tk.Label):

import tkinter as tk
root = tk.Tk()
root.title("Tk after() Example")
root.config(width=400, height=300)
label1 = tk.Label(text="Hello world!")
label1.place(x=100, y=70)
root.mainloop()

Read more…

Sets

Sets are unordered collections of unique objects. In Python a set is a built-in data type, like other more common collections, such as lists, tuples and dictionaries. Sets are widely used in logic and mathematics. In Python we can take advantage of their properties to create shorter, more efficient, and more readable code.

To create a set we put its elements between braces:

s = {1, 2, 3, 4}

Read more…

Generating Prime Numbers

How to know if a number is prime? How to get a list of prime numbers in Python? In this post we analyze and provide a simple and efficient method. If you want to skip the explanation and just copy the function for generating prime numbers, the full code is at the bottom.

We are going to build two functions. The first one aims to obtain all the prime numbers from 2 to a certain natural number and return them in a list. The second tells us if a supplied number is prime by calling the above function and checking if it is found in the list.

Read more…