Python GUI https://pythongui.org Build Powerful Python GUI Apps for Android, Windows, Linux, and MacOS Sun, 26 Jan 2025 23:53:00 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://i0.wp.com/pythongui.org/wp-content/uploads/2022/05/cropped-EmbarcaderoPython-5718928-9574398.png?fit=32%2C32&ssl=1 Python GUI https://pythongui.org 32 32 184929319 Unlock the Power of Python for Deep Learning with Diffusion Model – The Engine behind Stable Diffusion https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-diffusion-model-the-engine-behind-stable-diffusion/ https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-diffusion-model-the-engine-behind-stable-diffusion/#respond Mon, 23 Dec 2024 14:44:03 +0000 https://pythongui.org/?p=12883 Deep learning is a subset of machine learning, which is a subset of artificial intelligence (AI), the technology behind the most exciting capabilities in robotics, natural language processing, image and video recognition, large language models...

The post Unlock the Power of Python for Deep Learning with Diffusion Model – The Engine behind Stable Diffusion first appeared on Python GUI.

]]>
Deep learning is a subset of machine learning, which is a subset of artificial intelligence (AI), the technology behind the most exciting capabilities in robotics, natural language processing, image and video recognition, large language models (LLMs), generative AI, etc.

To address intricate problems, extensive amounts of data and substantial computational capabilities are essential for the functioning of deep learning algorithms. These algorithms are versatile in handling various types of data. 

This article will delve into a comprehensive exploration of the Diffusion Model, a prominent member of the deep learning domain and the driving force behind Stable Diffusion, which is pretty popular and widely used in generative AI these days.

Stable Diffusion has been praised for making AI image generation accessible and flexible, becoming one of the key tools for creative professionals and hobbyists working with generative AI.

Before we begin, let’s see the overview of Latent Diffusion Models architecture:

00_architectureofldm
Overview of Latent Diffusion architecture. Image source: Reference [8].

What is Deep Learning?

Deep learning is a subfield of machine learning that solves complex problems using artificial neural networks. These neural networks are made up of interconnected nodes arranged in multiple layers that extract features from input data. Large datasets are used to train these models, allowing them to detect patterns and correlations that humans would find difficult or impossible to detect.

The impact of deep learning on artificial intelligence has been substantial. It has paved the way for the development of intelligent systems capable of independent learning, adaptation, and decision-making. Deep learning has led to remarkable advancements in various domains, encompassing image and speech recognition, natural language processing, machine translation, text generation, image generation (as would be reviewed in this article), autonomous driving, and numerous others.

000
Example of AI-generated image using Stable Diffusion XL model that I generated using the following prompt: “Illustration of a future Artificial General Intelligence (AGI)”.

Why Python for Deep Learning?

Python has gained widespread popularity as a programming language due to its versatility and ease of use in diverse domains of computer science, especially in the field of deep learning. Thanks to its extensive range of libraries and frameworks specially tailored for deep learning, Python has emerged as a top choice among many machine learning professionals.

Python has emerged as the language of choice for deep learning, and here are some of the reasons why:

1. Simple to learn and use:

Python is a high-level programming language that is easy to learn and use, even for those who are new to programming. Its concise and uncomplicated syntax makes it easy to write and understand. This allows developers to concentrate on solving problems without worrying about the details of the language.

2. Abundant libraries and frameworks:

Python has a vast ecosystem of libraries and frameworks that cater specifically to deep learning. Some of these libraries include TensorFlow, PyTorch, Keras, and Theano. These libraries provide pre-built functions and modules that simplify the development process, reducing the need to write complex code from scratch.

3. Strong community support:

Python has a large and active community of developers contributing to its development, maintenance, and improvement. This community offers support and guidance to beginners, making it easier to learn and use Python for deep learning.

4. Platform independence:

Python is platform-independent, which means that code written on one platform can be easily executed on another platform without any modification. This makes it easier to deploy deep learning models on different platforms and devices.

5. Easy integration with other languages:

Python can be easily integrated with other programming languages, such as Delphi, C++, and Java, making it ideal for building complex systems that require integrating different technologies.

Overall, Python’s ease of use, an abundance of libraries and frameworks, strong community support, platform independence, and ease of integration with other languages make it an indispensable tool for machine learning practitioners. Its popularity continues to soar as a result.

What are Diffusion and Latent Diffusion Models?

A diffusion model is a type of generative model in machine learning designed to create data by reversing a noise-adding process. It models the way data can evolve from randomness (pure noise) to meaningful structures, such as images, audio, or other complex data distributions.

The following table shows how the diffusion model is compared with other generative models[8]:

AspectDiffusion ModelsGANs (Generative Adversarial Networks)
Training StabilityMore stableProne to mode collapse
Output QualityHigh detail, fewer artifactsSometimes sharper, but less reliable
SpeedSlower to generate imagesFaster at inference
Mode CoverageBetter at covering the data’s full distributionGANs may miss some modes

To dive deeper into GAN, read our previous article below:

On the other hand, a Latent Diffusion Model (LDM) is an advanced type of diffusion model that operates in a compressed (latent) space rather than directly on pixel data, making it more computationally efficient. LDMs, such as Stable Diffusion, enable faster image generation without compromising quality, which is especially useful for large-scale generative tasks like text-to-image synthesis.

The following table shows how LDMs improve over traditional diffusion models[8]:

AspectTraditional Diffusion ModelsLatent Diffusion Models
Data SpaceOperates directly on pixelsWorks in a compressed latent space
SpeedSlower due to pixel-level stepsFaster due to reduced dimensionality
Resource UsageHigher GPU/CPU requirementsMore efficient for large-scale models
QualityHigh, but with higher costHigh quality with lower overhead

What is Stable Diffusion?

Stable Diffusion is a generative artificial intelligence (generative AI) model that allows us to produce unique, high-quality, or even photorealistic images from text and image prompts[1]. Stable Diffusion leverages the Latent Diffusion model[2][5][10], developed by researchers from the Machine Vision and Learning group at LMU Munich, a.k.a CompVis.

Model checkpoints were publicly released at the end of August 2022 by a collaboration of Stability AI, CompVis, and Runway with support from EleutherAI and LAION[7][9]. For more information, you can check out their official blog post[13][14].

At the time this article was written, Stable Diffusion 3 Medium had already been released. Stable Diffusion 3 Medium is the latest and most advanced text-to-image AI model in our Stable Diffusion 3 series, comprising two billion parameters. It excels in photorealism, processes complex prompts, and generates clear text.

Try Stable Diffusion online with no-code approach

Before we dive deeper into Stable Diffusion with Python, let’s try it online first, with online Stable Diffusion 2.1 Demo:

00_huggingfacedemo01
Outputs of “A cat playing bass guitar” prompt.

For faster generation and API access, you can try: DreamStudio Beta.

00_dreamstudiodemo02
Outputs of “A cat playing bass guitar” prompt.

Or, you can try Playground AI, which enables us to try dozens of different filters and presets, to generate far better outputs:

00_playgroundaidemo01
Output of “A cat playing bass guitar” prompt. The left side shows the dozens of different filters or styles offered by Playground AI.
00_playgroundaidemo02
Outputs of “A cat playing bass guitar” prompt, using 4 different filters.

How do you get started in Stable Diffusion with Python using Hugging Face’s Diffusers library?

The easiest way to get started with Stable Diffusion and other diffusion models with Python is by using Hugging Face’s Diffusers library.

What is 🤗 Diffusers library?

00_diffuserslibrarylogo

🤗 Diffusers is a leading library for state-of-the-art pre-trained diffusion models, enabling the generation of images, audio, and even 3D structures of molecules. It serves as a modular toolkit suitable for both simple inference tasks or training your own custom diffusion model.

🤗 Diffusers library is designed with a focus on usability over performance, simplicity over easy, and customizability over abstractions. One goal of the 🤗 Diffusers library is to make diffusion models accessible to a wide range of deep learning practitioners.

The underlying model of 🤗 Diffusers library, a neural network, is trained to predict a way to slightly denoise the image in each step. After a certain number of steps, a sample is obtained.

The following is the architecture of the neural network (commonly follows the U-net architecture as proposed by reference[4] and improved upon in the Pixel++ paper):

unet-model

Some of the highlights of the architecture are:

  • this model predicts images of the same size as the input
  • the model makes the input image go through several blocks of ResNet layers which halves the image size by 2
  • then through the same number of blocks that upsample it again
  • skip connections link features on the downsample path to corresponding layers in the upsample path.

How to install Diffusers on your local machine?

Move to your chosen or preferred working directory, and then create a new virtual environment, and install Python version 3.10.

Create a virtual environment called “diffusers”, and install Python 3.10:

conda create --name diffusers python=3.10

To activate this environment, use:

conda activate diffusers

To deactivate an active environment, use this command:

conda deactivate

Before we begin any further, make sure we have all the necessary libraries installed using the following pip command:

pip install --upgrade diffusers accelerate transformers

We would install the following two libraries:

  • Accelerate: To speed up model loading for inference and training.
  • Transformers: This is required to run the most popular diffusion models, such as Stable Diffusion.

There are three main components of the library to know about:

1. DiffusionPipeline

The DiffusionPipeline is a high-level end-to-end class designed to rapidly generate samples from popular pre-trained diffusion models for inference, in a user-friendly fashion.

We’ll begin by importing a pipeline first. We’ll use the google/ddpm-celebahq-256 model developed by Google and U.C. Berkeley. It’s a model that utilizes the Denoising Diffusion Probabilistic Models (DDPM) algorithm that is trained on a dataset of celebrities images.

Hands-on and selected outputs:

The following is a code snippet for the basic use of DiffusionPipeline, and a sufficient explanation of selected outputs:

from diffusers import DDPMPipeline

image_pipe = DDPMPipeline.from_pretrained("google/ddpm-celebahq-256")
image_pipe.to("cpu")

images = image_pipe().images
# Show an example of the generated image from the Hugging Face Hub (DDPM-CelebHQ)
images[0].show()

# Browse what was the building blocks of the pipeline:
image_pipe
output01_diffusersonpyscripter-pipelines01

To generate an image, we simply run the pipeline and don’t even need to give it any input, it will generate a random initial noise sample and then iterate the diffusion process.

The pipeline returns as output a dictionary with a generated sample of interest:

output01_diffusersonpyscripter-pipelines02

Let’s take a look at the image by running images[0].show() on PyScripter IDE:

output01_diffusersonpyscripter-pipelines03

Run image_pipe on PyScripter, to see what the pipeline is made of, so we can try to understand better what was going on under the hood:

output01_diffusersonpyscripter-pipelines04

Now we can see what’s inside the pipeline: A scheduler and a UNet model. Let’s look closely at them and what this pipeline just did under the hood.

2. Pretrained models

Popular pre-trained model architectures and modules can be used as building blocks for creating diffusion systems.

Instances of the model class are neural networks that take a noisy sample as well as a timestep as inputs to predict a less noisy output sample. In this subsection, we’ll load a pre-trained model and play around with it to understand the model API. We’ll load a simple unconditional image generation model of type UNet2DModel which was released with the DDPM Paper[3] and for instance, take a look at another checkpoint trained on church images: google/ddpm-church-256.

Hands-on and selected outputs

The following is a code snippet for the basic use of the models, and a sufficient explanation of selected outputs:

import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
from diffusers import UNet2DModel

repo_id = "google/ddpm-church-256"
model = UNet2DModel.from_pretrained(repo_id, use_safetensors=False)

model
model.config

model_random = UNet2DModel(**model.config)

model_random.save_pretrained("my_model")

# Add random gaussian sample
import torch

torch.manual_seed(0)

noisy_sample = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
noisy_sample.shape

# Inference
with torch.no_grad():
    noisy_residual = model(sample=noisy_sample, timestep=2).sample
output02_diffusersonpyscripter-models01

Now let’s take a look at the model’s configuration. By accessing the config attribute using model.config on PyScripter IDE, we can browse all the necessary parameters to define the model architecture:

output02_diffusersonpyscripter-models02

You can access all the complete output of the model and model.config in the repository [3].

A couple of important config parameters are:

  • sample_size: defines the height and width dimension of the input sample.
  • in_channels: defines the number of input channels of the input sample.
  • down_block_types and up_block_types: define the type of down- and upsampling blocks that are used to create the UNet architecture as was seen in the figure at the beginning of this notebook.
  • block_out_channels: defines the number of output channels of the downsampling blocks, also used in reversed order for the number of input channels of the upsampling blocks.
  • layers_per_block: defines how many ResNet blocks are present in each UNet block.

Coming back to the trained model, let’s now see how you can use the model for inference. First, you need a random gaussian sample in the shape of an image (batch_size × in_channels × sample_size × sample_size). We have a batch axis because a model can receive multiple random noises. A channel axis because each one consists of multiple channels (such as red-green-blue). And finally, sample_size corresponds to the height and width. Let’s confirm the output shapes match using noisy_sample.shape:

output02_diffusersonpyscripter-models03

The predicted noisy_residual has the exact same shape as the input and we use it to compute a slightly less noisy image. Let’s confirm the output shapes match using noisy_residual.shape:

output02_diffusersonpyscripter-models04

3. Schedulers

Schedulers are algorithms wrapped into a Python class that define the noise schedule, which is used to add noise to the model during training and also define the algorithm to compute the slightly less noisy sample given the model output (noisy_residual). This article only focuses on how to use scheduler classes for inference.

We will use DDPMScheduler, the denoising algorithm proposed in the DDPM Paper[4].

Hands-on and selected outputs

The following is a code snippet for the basic use of the schedulers, and a sufficient explanation of selected outputs:

import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
from diffusers import UNet2DModel
from diffusers import DDPMScheduler

repo_id = "google/ddpm-ema-church-256"
model = UNet2DModel.from_pretrained(repo_id, use_safetensors=False)
scheduler = DDPMScheduler.from_pretrained(repo_id)

scheduler.config

scheduler.save_config("my_scheduler")
new_scheduler = DDPMScheduler.from_pretrained("my_scheduler")

# Add random gaussian sample
import torch

torch.manual_seed(0)

noisy_sample = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
noisy_sample.shape

# Inference
with torch.no_grad():
    noisy_residual = model(sample=noisy_sample, timestep=2).sample

less_noisy_sample = scheduler.step(model_output=noisy_residual, timestep=2, sample=noisy_sample).prev_sample
less_noisy_sample.shape

# Define the denoising loop
import PIL.Image
import numpy as np

def display_sample(sample, i):
    image_processed = sample.cpu().permute(0, 2, 3, 1)
    image_processed = (image_processed + 1.0) * 127.5
    image_processed = image_processed.numpy().astype(np.uint8)

    image_pil = PIL.Image.fromarray(image_processed[0])
    print(f"Image at step {i}")
    image_pil.show()

# Display the progress, at every 50th step
import tqdm

sample = noisy_sample

for i, t in enumerate(tqdm.tqdm(scheduler.timesteps)):
    # 1. predict noise residual
    with torch.no_grad():
    residual = model(sample, t).sample

    # 2. compute less noisy image and set x_t -> x_t-1
    sample = scheduler.step(residual, t, sample).prev_sample

    # 3. optionally look at image
    if (i + 1) % 50 == 0:
        display_sample(sample, i + 1)

Let’s take a look at the scheduler configuration here, by running scheduler.config on PyScripter IDE:

output03_diffusersonpyscripter-schedulers01-01

Different schedulers are usually defined by different parameters. The following are the most important ones that we need to know:

  • num_train_timesteps defines the length of the denoising process, e.g. how many timesteps are needed to process random Gaussian noise to a data sample.
  • beta_schedule defines the type of noise schedule that shall be used for inference and training.
  • beta_start and beta_end define the smallest and highest noise values of the schedule.

We’ll try to use the model output from the previous section. We can see that the computed sample has the exact same shape as the model input, which means that we are ready to pass it to the model again in the next step.

output03_diffusersonpyscripter-schedulers01

The last step is to bring it all together and define the denoising loop. This loop prints out the (less and less) noisy samples along the way for better visualization in the denoising loop.

In the code above, we already define a display function that takes care of post-processing the denoised image, and then convert it to a PIL.Image and display it. Here is the output (displayed using the PIL.Image) of the 50th step:

output03_diffusersonpyscripter-schedulers02

It takes quite some time to see a meaningful shape, it can be seen after 800 steps. And, here is the final result, the 1000th step:

output03_diffusersonpyscripter-schedulers03

By saving the image results after the 50th step and its multiples until the 1000th step and aggregating them, we can see the following denoising progress:

output03_diffusersonpyscripter-schedulers04

Isn’t it amazing? We should now have a solid foundational understanding of the schedulers and all other components of the 🤗 Diffusers library. The key points to keep in mind are:

1. Schedulers have no trainable weights (parameter-free).

2. During inference, schedulers specify the algorithm that computes the slightly less noisy sample.

To end the subsection about models and schedulers, please also note that we very much deliberately try to keep models and schedulers as independent from each other as possible. This means a scheduler should never accept a model as an input and vice-versa. The model predicts the noise residual or slightly less noisy image with its trained weights, while the scheduler computes the previous sample given the model’s output.

How to perform text-to-image using Stable Diffusion on 🤗 Diffusers? 

In this section, we will try text-to-image or image generation from text, using the Diffusers library. We will try it using two different classes: DiffusionPipeline and StableDiffusionPipeline.

Using DiffusionPipeline

Load the model with the from_pretrained() method:

from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", use_safetensors=True)

The DiffusionPipeline downloads and caches all modeling, tokenization, and scheduling components.

output301_diffusionpipeline-from_pretrained

You’ll see that the Stable Diffusion pipeline is composed of the UNet2DConditionModel and PNDMScheduler among other things:

output302_diffusionpipeline2

The following is the complete code example to generate an image from a text prompt using Diffusers:

from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", use_safetensors=True)

image = pipeline("A painting of a cat playing bass guitar").images[0]
image
image.save("painting_of_cat_playing_bass2.png")

Run it on PyScripter IDE, the “A painting of a cat playing bass guitar” prompt would generate the following output:

output303_paintingofcatplayingbass2
painting_of_cat_playing_bass2

Using StableDiffusionPipeline

In this second example, we will generate an image from a text prompt, directly using StableDiffusionPipeline from the diffusers library.

Run the following code and your prompt on PyScripter IDE:

import torch
from diffusers import StableDiffusionPipeline

model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id)

prompt = "A man coding on his laptop"

pipe = pipe.to("cpu")
generator = torch.Generator("cpu").manual_seed(0)

image = pipe(prompt, generator=generator).images[0]
image
image.save("a_man_coding_on_his_laptop.png")
output304_amancodingonhislaptop-sd
a_man_coding_on_his_laptop

Other interesting implementations

The advancement of generative AI-particularly Stable Diffusion, enables us to do creativity-demanding tasks such as creating video art, with just a few clicks away. Below are videos I generate using combinations of text-to-image, image-to-image, frame interpolation, and text/image-to-video using Playground AI and Runway ML, which all are rooted in Stable Diffusion.

Text/image to video

Text/image to video is a multimodal AI system that can generate novel videos from text, images, or video clips.

Here is the collection of 11 short videos (4 seconds each) that I generated or animated from existing images with additional guidance from text prompts, with help from Runway ML:

The following are the prompts I use to guide the image-to-video generation process:

1. A cat playing bass guitar
2. An astronaut working on ISS
3. Human and robot handshake
4. Jackson Pollock's No. 1 (Lavender Mist) live drip painting
5. Typing on keyboard
6. A woman working with her laptop
7. Two software developers brainstorming
8. The startup founder gives a presentation
9. A PhD student teaches us about her research
10. A young mathematician struggling to solve equations on a blackboard
11. An alien gray staring at us

Text-to-image + frame interpolation

Frame interpolation is a technique to turn a sequence of images into an animated video, by filling in between images with smooth transitions. 

First, I generate 120 images from unusual, obscure, and complex text prompts using Playground AI. The following are the prompts I used to generate images:

1. Photographs of Space-Time Anomalies
2. Illustration of a future Artificial General Intelligence (AGI)
3. Illustration of deep learning and AI community
4. Very advanced alien civilizations that live inside black hole
5. Vibrating membrane from brane theory and m-theory
6. First ever photo of an atom, First ever photo of a proton taken using electron microscope
7. Deep sea, Deep sea with deep sea creatures, Deep sea monsters
8. A battalion of military robots
9. Dream of the Future of Humanity: Interplanetary, Interstellar, and Intergalactic Colony
10. Surface of exoplanet
11. Reimagine newton's apple and universal law of gravitation
12. Draw Feynman diagram in artistic but scientifically formal way

Then, I create a video by automatically generating smooth transitions between those images using frame interpolation from Runway ML:

Conclusion

In conclusion, leveraging Python for deep learning with diffusion models unlocks immense potential for generative AI, take Stable Diffusion as a perfect example. These models, particularly Latent Diffusion Models (LDMs), have revolutionized the field by combining computational efficiency with high-quality outputs, enabling accessible and versatile applications such as text-to-image synthesis.

We’ve also learned the hands-on parts of diffusion models by utilizing libraries like Hugging Face’s 🤗 Diffusers with Python, to draw picture from random noise (we explored pre-trained models, customizable pipelines, and efficient inference methods to draw church realistically) and performing text-to-image synthesis.

As we delve deeper into these cutting-edge advancements, diffusion models continue to shape the future of AI-driven innovation, empowering diverse domains ranging from art and design to scientific discovery.

I hope this article was successful in giving you a comprehensive and accessible introduction to diffusion models, and a solid understanding and workflow of how to implement them to your domains and project goals, so, it would inspire you to learn more and experiment with diffusion models yourself.

Check out the full repository here: github.com/Embarcadero/DL_Python07_ DiffusionModels


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL4Python, which makes it simple to create Windows GUIs with Python.


References & further readings

[1] Amazon Web Services, Inc. (2024). 

What is Stable Diffusion? AWS What is. aws.amazon.com/what-is/stable-diffusion

[2] Hakim, M. A. (2023). 

How to bypass the ChatGPT information cutoff? A busy (or lazy) man guide to read more recent ML/DL papers. Paper-001: “Rombach et al., 2022”. hkaLabs blog. hkalabs.com/blog/how-to-read-deep-learning-papers-using-bing-chat-ai-001

[3] Hakim, M. A. (2024).

Article47 – Deep Learning Python 07 – Diffusion Models. embarcaderoBlog-repo. GitHub repository. github.com/MuhammadAzizulHakim/ embarcaderoBlog-repo/tree/main/Article47%20-%20Deep%20Learning%20Python%2007%20-%20Diffusion%20Models

[4] Ho, J., Jain, A., & Abbeel, P. (2020). 

Denoising diffusion probabilistic models. Advances in neural information processing systems, 33, 6840-6851.

[5] Hugging Face. (2024). 

Diffusers. Hugging Face docs. huggingface.co/docs/diffusers/index

[6] Hugging Face. (2023). 

diffusers_intro.ipynb: Introducing Hugging Face’s new library for diffusion models. Hugging Face GitHub repository. colab.research.google.com/github/huggingface/ notebooks/blob/main/diffusers/diffusers_intro.ipynb

[7] Hugging Face. (2023). 

The Stable Diffusion Guide. Hugging Face docs. huggingface.co/docs/diffusers/v0.13.0/en/ stable_diffusion

[8] OpenAI. (2024). 

ChatGPT (Nov version) [Large language model]. chat.openai.com/chat

[9] Patil, S., Cuenca, P., Lambert, N., and von Platen, P. (2024). 

Stable Diffusion with 🧨 Diffusers. Hugging Face blog. huggingface.co/blog/stable_diffusion

[10] Rombach, R., Blattmann, A., Lorenz, D., Esser, P., & Ommer, B. (2022). 

High-resolution image synthesis with latent diffusion models. In Proceedings of the IEEE/CVF conference on computer vision and pattern recognition (pp. 10684-10695).

[11] Rombach, R., Blattmann, A., Lorenz, D., Esser, P., & Ommer, B. (2022).

latent-diffusion: High-Resolution Image Synthesis with Latent Diffusion Models. CompVis – Computer Vision and Learning LMU Munich. GitHub repository. github.com/CompVis/latent-diffusion

[12] Ronneberger, O., Fischer, P., & Brox, T. (2015). 

U-net: Convolutional networks for biomedical image segmentation. In Medical image computing and computer-assisted intervention–MICCAI 2015: 18th international conference, Munich, Germany, October 5-9, 2015, proceedings, part III 18 (pp. 234-241). Springer International Publishing.

[13] Stability AI. (2024).

Stability AI: Activating humanity’s potential through generative AI. Stability AI official website. stability.ai

[14] Stability AI. (2024).

Stable Diffusion Public Release. Stability AI news. stability.ai/news/stable-diffusion-public-release

[15] Towards AI Editorial Team. (2023).

Diffusion Models vs. GANs vs. VAEs: Comparison of Deep Generative Models. Toward AI blog. towardsai.net/p/generative-ai/diffusion-models-vs-gans-vs-vaes-comparison-of-deep-generative-models

The post Unlock the Power of Python for Deep Learning with Diffusion Model – The Engine behind Stable Diffusion first appeared on Python GUI.

]]>
https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-diffusion-model-the-engine-behind-stable-diffusion/feed/ 0 12883
Unlock the Power of Python for Deep Learning with Radial Basis Function Networks (RBFNs) https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-radial-basis-function-networks-rbfns/ https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-radial-basis-function-networks-rbfns/#respond Sat, 03 Aug 2024 02:48:57 +0000 https://pythongui.org/?p=12534 Deep learning algorithms work with almost any kind of data and require large amounts of computation power and information to solve complicated issues. Now, let us, deep-dive, into one of the most powerful deep learning...

The post Unlock the Power of Python for Deep Learning with Radial Basis Function Networks (RBFNs) first appeared on Python GUI.

]]>
Deep learning algorithms work with almost any kind of data and require large amounts of computation power and information to solve complicated issues. Now, let us, deep-dive, into one of the most powerful deep learning algorithms: Radial basis function networks (RBFNs).

Radial Basis Function Networks (RBFNs) are a powerful tool for specific types of problems, particularly those involving interpolation and function approximation. Their simplicity and effectiveness in these areas make them a valuable model in the machine learning and deep learning toolbox.

RBFNs are special types of feedforward neural networks that use radial basis functions as activation functions. They have an input layer, a hidden layer, and an output layer and are mostly used for classification, regression, and time-series prediction.

If you are interested in learning how to use Python for deep learning with Radial basis function networks (RBFNs), this article is perfect for you. 

Before we begin, let’s see the diagram of RBFN architecture:

01_architectureofrbfns_deep-learning
The RBFN architecture. Image source: Reference [5].

What is Deep Learning?

Deep learning is a branch of machine learning focused on solving complex problems through the use of artificial neural networks. These networks are composed of multiple layers of interconnected nodes that work together to extract features from input data. By training on large datasets, deep learning models can identify patterns and correlations that are often beyond human capability to detect.

The influence of deep learning on artificial intelligence has been substantial. It has paved the way for the creation of intelligent systems that can learn, adapt, and make autonomous decisions. This technology has driven significant advancements in various fields, including function approximation, classification, time-series prediction, image and speech recognition, natural language processing, machine translation, and autonomous driving, among others.

The following is a scheme of the use of neural networks in the Global Positioning System (GPS):

02_architectureofnnsinnavigationsystems_deep-learning
The flow of ANNs and NNs in the navigation system. While GDOP stands for Geometric Dilution of Precision, DGPS stands for Differential Global Positioning System, and KF stands for Kalman filter. Image source: Reference [3].

4 Reasons to Use Python for Deep Learning

Python’s rise in popularity is attributed to its adaptability and simplicity, particularly in the realm of deep learning. It has become the go-to language for many professionals in machine learning, deep learning, AI, and data science due to its comprehensive libraries and frameworks designed for these purposes.

Here are four compelling reasons why Python excels as a deep learning language:

1. Straightforward syntax and readability

Python’s straightforward syntax and readability make it an ideal choice for deep learning. Its high-level nature allows developers to write clean, understandable code, which is particularly beneficial for those new to programming or deep learning. This simplicity helps researchers and developers focus on creating and refining models without being bogged down by complex syntax, enabling faster experimentation and iteration.

2. Extensive ecosystem of libraries and frameworks

The extensive ecosystem of libraries and frameworks is another major advantage of using Python for deep learning. Libraries such as TensorFlow, PyTorch, and Keras offer powerful tools for building, training, and deploying deep learning models. These frameworks come with pre-built components that handle many aspects of deep learning, from data preprocessing to model evaluation, significantly reducing the amount of boilerplate code developers need to write. This makes the development process more efficient and allows for rapid prototyping.

3. Strong community support

Python’s strong community support enhances its appeal in the deep learning field. The large and active community of Python developers contributes to a wealth of resources, including comprehensive documentation, tutorials, and forums. This support network is invaluable for troubleshooting, learning new techniques, and staying up-to-date with the latest advancements in deep learning. The collaborative environment fostered by the Python community ensures continuous improvement and innovation in the tools and libraries available for deep learning.

4. Cross-platform compatibility

Cross-platform compatibility is another significant benefit of using Python. Python’s platform independence means that code written on one operating system can be easily executed on another with minimal modifications. This flexibility is crucial for deploying deep learning models across various environments, from local machines to cloud-based platforms. Python’s compatibility with different operating systems ensures that deep learning solutions can be seamlessly integrated into diverse deployment scenarios, enhancing their usability and reach.

What Are Radial Basis Function Networks (RBFNs)?

Radial Basis Function Networks, abbreviated as RBFNs, are a class of artificial neural networks frequently employed for tasks such as function approximation, classification, and clustering. These networks excel in addressing challenges involving nonlinear or discontinuous data.

The fundamental concept of RBFNs revolves around the use of radial basis functions as their activation functions. Positioned at specific locations within the input space, these functions enable the transformation of input data into a higher-dimensional space, facilitating easier separation and classification of the data.

What Python tools and libraries are needed for RBFN development?

Developing a Radial Basis Function Network (RBFN) in Python can be facilitated using several libraries and tools. Here’s a list of the most commonly used ones:

Core Libraries

1. NumPy:

  • Purpose: For numerical operations and handling arrays.
  • Installation: pip install numpy

2. SciPy:

  • Purpose: For scientific computing, including optimization and special functions.
  • Installation: pip install scipy

3. scikit-learn:

  • Purpose: Although scikit-learn doesn’t have a dedicated RBFN implementation, it provides tools for clustering (e.g., k-means) which can be useful for selecting centers, and other utilities for data preprocessing.
  • Installation: pip install scikit-learn

Data Handling and Visualization

4. Pandas:

  • Purpose: For data manipulation and analysis.
  • Installation: pip install pandas

5. Matplotlib:

  • Purpose: For plotting and visualizing data.
  • Installation: pip install matplotlib

6. Seaborn:

  • Purpose: For statistical data visualization, built on top of Matplotlib.
  • Installation: pip install seaborn

Example Code

Here’s a basic example of how you can implement an RBFN using these libraries:

import numpy as np
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from sklearn.linear_model import LinearRegression

class RBFN:
    def __init__(self, num_centers, spread):
        self.num_centers = num_centers
        self.spread = spread
    def _rbf(self, X, centers, spread):
        return np.exp(-cdist(X, centers) ** 2 / (2 * spread ** 2))
    def fit(self, X, y):
        # Step 1: Use k-means to find centers
        kmeans = KMeans(n_clusters=self.num_centers)
        kmeans.fit(X)
        self.centers = kmeans.cluster_centers_
        # Step 2: Calculate the RBF activations
        RBF_X = self._rbf(X, self.centers, self.spread)
        # Step 3: Train linear regression on RBF activations
        self.regressor = LinearRegression()
        self.regressor.fit(RBF_X, y)
    def predict(self, X):
        RBF_X = self._rbf(X, self.centers, self.spread)
        return self.regressor.predict(RBF_X)

# Sample usage
if __name__ == "__main__":
    from sklearn.datasets import make_regression
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import mean_squared_error
    # Generate synthetic data
    X, y = make_regression(n_samples=100, n_features=2, noise=0.1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    # Initialize and train RBFN
    rbfn = RBFN(num_centers=10, spread=1.0)
    rbfn.fit(X_train, y_train)
    # Predict and evaluate
    y_pred = rbfn.predict(X_test)
    mse = mean_squared_error(y_test, y_pred)
    print(f"Mean Squared Error: {mse}")
    # Plot results
    import matplotlib.pyplot as plt
    plt.scatter(y_test, y_pred)
    plt.xlabel("True Values")
    plt.ylabel("Predictions")
    plt.title("RBFN Predictions vs True Values")
    plt.show()
output00_basicpythonsetupandexampleforrbfn_deep-learning

These libraries provide a solid foundation for developing and experimenting with RBFNs in Python.

Radial basis function networks (RBFNs) as building blocks for more complex networks in AI

Radial basis function networks (RBFNs) are the building blocks for various applications in machine learning and neural networks, particularly for tasks involving pattern recognition, function approximation, and time-series prediction. They are characterized by their use of radial basis functions as activation functions, which measure the distance between input data points and a set of center points. This unique feature allows RBFNs to capture local patterns in the data, making them highly effective for interpolation and classification tasks. 

Moreover, RBFNs serve as foundational components in more complex architectures and algorithms, such as support vector machines and Gaussian processes, further extending their utility in the field of artificial intelligence.

The following is an example of the employment of RBFNNs for Navigation Systems:

03_trainingandpredictionphasesofrbfnnformeasurement_deep-learning
Training (a) and prediction (b) phases of RBFNNs for measurement reconfiguration based on neural networks in GPS. While INS stands for Inertial Navigation System and GNSS stands for Global Navigation Satellite System. Image source: Reference [3].

RBFNs vs MLPs

Radial Basis Function Networks (RBFNs) and Multilayer Perceptrons (MLPs) are both types of artificial neural networks used in machine learning, but they have distinct structures and mechanisms for processing information.

Comparison

Structure and Complexity: 

RBFNs are simpler in structure compared to MLPs. RBFNs have a single hidden layer, while MLPs can have multiple hidden layers.

Training Process: 

The training of RBFNs is typically faster as it involves finding centers and spreads followed by linear output weights. MLPs require iterative backpropagation, which can be computationally intensive.

Interpretability: 

RBFNs, with their localized response to input data, can be more interpretable than MLPs, where the influence of individual neurons is harder to decipher.

Function Approximation: 

RBFNs are often preferred for tasks requiring interpolation and where the relationship between inputs and outputs is locally smooth. MLPs, on the other hand, are more versatile and can handle more complex, non-linear relationships.

Generalization: 

MLPs generally have better generalization capabilities due to their deeper architecture and non-linear activations, making them suitable for a broader range of tasks compared to the typically shallow architecture of RBFNs.

04_multilayerperceptron_network_deep-learning
The RBFN architecture. Image source: Reference [7].

In summary, while both RBFNs and MLPs are powerful tools in machine learning, they are suited to different types of problems and have distinct strengths and weaknesses. RBFNs are often used for their simplicity and effectiveness in local function approximation, while MLPs are favored for their flexibility and ability to model complex global patterns in data.

RBFNs vs LSTMs

On the other hand, the following are the key differences between RBFNs and LSTMs:

Architecture

RBFNs:

  • Structure: Comprise three layers—input, hidden (with radial basis functions as activation functions), and output.
  • Hidden Layer: Uses radial basis functions (e.g., Gaussian functions) that respond to the distance between the input and a center.
  • Output: Produces a linear combination of the hidden layer activations.
  • Training: Involves determining centers and widths of the radial basis functions, followed by training the output weights using linear regression techniques.

LSTMs:

For more details on LSTMs, please refer to our previous article:

  • Structure: A type of recurrent neural network (RNN) with cells that include gates to manage memory and state.
  • Cells: Each LSTM cell has input, output, and forget gates to control the flow of information.
  • Memory: Designed to retain information over long sequences, addressing the vanishing gradient problem common in traditional RNNs.
  • Training: Uses backpropagation through time (BPTT) to update weights, which can be computationally intensive.
05_lstmarchitecture_deep-learning
The LSTM architecture. Image source: Reference [1].

Applications

RBFNs:

  • Function Approximation: Well-suited for interpolating functions in multi-dimensional space.
  • Classification: Can classify data by learning decision boundaries.
  • Regression: Useful for predicting continuous values.
  • Time-Series Prediction: Applied to forecasting future values based on past data, though not as effective as LSTMs for long sequences.

LSTMs:

  • Sequential Data: Ideal for tasks involving sequences, such as natural language processing (NLP), speech recognition, and time-series prediction.
  • Memory Retention: Effective in capturing long-term dependencies in data sequences.
  • Complex Patterns: Capable of learning intricate patterns over time, making them suitable for tasks like language translation, sentiment analysis, and video analysis.

Strengths and Weaknesses

RBFNs:

  • Strengths:
  • Weaknesses:

LSTMs:

  • Strengths:
  • Weaknesses:

Summary

  • RBFNs are best suited for problems involving interpolation, classification, and simple time-series prediction. 

They are easier to train and understand but may not scale well with large and complex datasets.

  • LSTMs excel in handling sequential data with long-term dependencies, such as in NLP and advanced time-series prediction. 

They are more complex and require more computational resources but are highly effective for tasks involving sequences.

Choosing between RBFNs and LSTMs depends on the specific nature of the problem at hand. If the task involves learning from sequential data with long-term dependencies, LSTMs are generally the better choice. For simpler problems involving function approximation or classification in multi-dimensional space, RBFNs might be more appropriate.

Hands-On RBFNs 1: Stock market prediction

This example uses synthetic data for simplicity, but you can replace it with actual stock market data:

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt

# Generate synthetic stock market data
np.random.seed(42)
X = np.linspace(0, 10, 100).reshape(-1, 1)
y = np.sin(X).ravel() + np.random.normal(scale=0.1, size=X.shape[0])

# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Standardize the data
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

class RBFNetwork:
    def __init__(self, num_input, num_hidden, num_output, sigma=1.0):
        self.num_input = num_input
        self.num_hidden = num_hidden
        self.num_output = num_output
        self.sigma = sigma
        self.centers = None
        self.weights = None

    def _calculate_centers(self, X):
        idx = np.random.choice(X.shape[0], self.num_hidden, replace=False)
        centers = X[idx]
        return centers

    def _compute_activation(self, X):
        activation = np.zeros((X.shape[0], self.num_hidden))
        for i in range(self.num_hidden):
            activation[:, i] = np.exp(-np.linalg.norm(X - self.centers[i], axis=1) ** 2 / (2 * self.sigma ** 2))
        return activation

    def fit(self, X, y):
        self.centers = self._calculate_centers(X)
        activation = self._compute_activation(X)
        self.weights = np.dot(np.linalg.pinv(activation), y)

    def predict(self, X):
        activation = self._compute_activation(X)
        output = np.dot(activation, self.weights)
        return output

# Initialize RBF network
num_hidden_neurons = 10
rbf_net = RBFNetwork(num_input=X_train_scaled.shape[1], num_hidden=num_hidden_neurons, num_output=1, sigma=1.0)

# Train the network
rbf_net.fit(X_train_scaled, y_train)

# Make predictions
y_train_pred = rbf_net.predict(X_train_scaled)
y_test_pred = rbf_net.predict(X_test_scaled)

# Evaluate the model
train_mse = mean_squared_error(y_train, y_train_pred)
test_mse = mean_squared_error(y_test, y_test_pred)

print(f'Train MSE: {train_mse:.4f}')
print(f'Test MSE: {test_mse:.4f}')

# Plot the results
plt.figure(figsize=(10, 6))
plt.plot(X, y, 'b-', label='True Data')
plt.plot(X_train, y_train_pred, 'ro', label='Train Predictions')
plt.plot(X_test, y_test_pred, 'go', label='Test Predictions')
plt.legend()
plt.xlabel('X')
plt.ylabel('y')
plt.title('RBF Network - Stock Market Prediction')
plt.show()

To execute the code above seamlessly without any errors, we can utilize the PyScripter IDE.

output01_stockmarketprediction_deep-learning

What did the code above do?

Let’s break down the important parts of the code above.

We’ll use the numpy library for numerical operations and sklearn for preprocessing. Here’s the step-by-step code:

1. Import Libraries

Import the necessary libraries.

2. Prepare Data

Load and preprocess your stock market data. For demonstration, we will create synthetic stock market data. Replace this with your actual data.

3. Define the RBF Network

Implement the RBF network class.

4. Train the Model

Train the RBFN on the training data.

5. Make Predictions

Use the trained model to make predictions.

This is a basic implementation to demonstrate how an RBFN can be applied to stock market prediction. 

For real-world applications, you should:

1. Use Real Stock Market Data

Replace the synthetic data generation with actual stock market data loading and preprocessing.

2. Tune Hyperparameters

Optimize the number of hidden neurons, sigma, and other hyperparameters using cross-validation or other techniques.

3. Feature Engineering

Use relevant financial indicators and features that affect stock prices.

4. Regularization and Advanced Techniques

Incorporate regularization, cross-validation, and more advanced techniques to improve model robustness and performance.

Hands-On RBFNs 2: Anomaly detection

Below is a Python example of how you can use a Radial Basis Function Network (RBFN) for anomaly detection. This example uses synthetic data for simplicity, but you can replace it with actual data.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_classification
from sklearn.linear_model import LinearRegression
from sklearn.metrics import accuracy_score
import scipy.spatial.distance as distance

class RadialBasisFunctionNeuralNetwork:
    def __init__(self, num_of_rbf_units=10):
        self.num_of_rbf_units = num_of_rbf_units

    def _rbf_unit(self, rbf_center, point_in_dataset):
        return np.exp(-self.beta * distance.cdist([point_in_dataset], [rbf_center], 'euclidean')**2).flatten()[0]

    def _construct_interpolation_matrix(self, input_dataset):
        interpolation_matrix = np.zeros((len(input_dataset), self.num_of_rbf_units))
        for idx, point_in_dataset in enumerate(input_dataset):
            for center_idx, rbf_center in enumerate(self.rbf_centers):
                interpolation_matrix[idx, center_idx] = self._rbf_unit(rbf_center, point_in_dataset)
        return interpolation_matrix

    def train_model(self, input_dataset, target_dataset):
        self.kmeans_clustering = KMeans(n_clusters=self.num_of_rbf_units, random_state=0).fit(input_dataset)
        self.rbf_centers = self.kmeans_clustering.cluster_centers_
        self.beta = 1.0 / (2.0 * (self.kmeans_clustering.inertia_ / input_dataset.shape[0]))
        interpolation_matrix = self._construct_interpolation_matrix(input_dataset)
        self.model_weights = np.linalg.pinv(interpolation_matrix.T.dot(interpolation_matrix)).dot(interpolation_matrix.T).dot(target_dataset)

    def predict(self, input_dataset):
        interpolation_matrix = self._construct_interpolation_matrix(input_dataset)
        predicted_values = interpolation_matrix.dot(self.model_weights)
        return predicted_values

if __name__ == "__main__":
    # Generating a simple classification dataset
    input_dataset, target_dataset = make_classification(n_samples=500, n_features=2, n_informative=2, n_redundant=0, n_classes=2)

    # Initializing and training the RBF neural network
    rbf_neural_network = RadialBasisFunctionNeuralNetwork(num_of_rbf_units=20)
    rbf_neural_network.train_model(input_dataset, target_dataset)

    # Predicting the target values
    predictions = rbf_neural_network.predict(input_dataset)

    # Converting continuous output to binary labels
    binary_predictions = np.where(predictions > 0.5, 1, 0)

    # print("Accuracy: {}".format(accuracy_score(target_dataset, binary_predictions)))
    print(f"Accuracy: {accuracy_score(target_dataset, binary_predictions)}")

    # Plotting the results
    plt.scatter(input_dataset[:, 0], input_dataset[:, 1], c=binary_predictions, cmap='viridis', alpha=0.7)
    plt.scatter(rbf_neural_network.rbf_centers[:, 0], rbf_neural_network.rbf_centers[:, 1], c='red')
    plt.title('Classification Result')
    plt.show()

To execute the code above seamlessly without any errors, we can utilize the PyScripter IDE.

What did the code above do?

Let’s break down the important parts of the code above.

1. Import Libraries

Import necessary libraries.

2. Prepare Data

  • Generate and preprocess data. For demonstration, we will create synthetic normal and anomalous data.
  • Split the data into training and test sets.
  • Standardize the data.

3. Define the RBF Network

Implement the RBF network class: Define an RBF network class with methods to fit the model, predict outputs, and calculate reconstruction errors.

4. Train the Model

Train the RBF network using only the normal data.

5. Anomaly Detection

Use the trained model to detect anomalies. We use the trained model to detect anomalies based on reconstruction error:

  • Calculate the reconstruction error for both training and test sets.
  • Determine a threshold for anomaly detection (e.g., the 95th percentile of training errors).
  • Classify anomalies based on whether their reconstruction error exceeds the threshold.
  • Evaluate and visualize the results.
output02_anomalydetection_deep-learning

This example demonstrates how to use an RBF network for anomaly detection. For real-world applications, you should adjust the data preprocessing, network parameters, and threshold determination based on the specific characteristics of your data and use case.

Hands-On RBFNs 3: Signal processing

Radial Basis Function Networks (RBFNs) are a type of artificial neural network used for various applications, including signal processing. Below is a Python code example demonstrating signal processing using an RBFN.

For this example, let’s use the scikit-learn library, which provides tools to work with RBFNs through its RBFSampler and MLPRegressor classes.

Here is the Python code for signal processing using an RBFN:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.kernel_approximation import RBFSampler
from sklearn.linear_model import Ridge

# Generate a sample signal (e.g., a noisy sine wave)
np.random.seed(42)
n_samples = 100
X = np.linspace(0, 4 * np.pi, n_samples).reshape(-1, 1)
y = np.sin(X).ravel() + np.random.normal(scale=0.1, size=n_samples)

# Plot the original noisy signal
plt.figure(figsize=(10, 6))
plt.plot(X, y, label='Noisy signal')
plt.title('Original Noisy Signal')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.legend()
plt.show()

# Use RBFSampler to approximate the RBF kernel
rbf_sampler = RBFSampler(gamma=1.0, n_components=100, random_state=42)
X_features = rbf_sampler.fit_transform(X)

# Train a Ridge regression model on the RBF features
model = Ridge(alpha=1.0)
model.fit(X_features, y)

# Predict the signal using the trained model
y_pred = model.predict(X_features)

# Plot the original noisy signal and the filtered signal
plt.figure(figsize=(10, 6))
plt.plot(X, y, label='Noisy signal')
plt.plot(X, y_pred, label='Filtered signal', color='red')
plt.title('Signal Processing using RBFN')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.legend()
plt.show()

To execute the code above seamlessly without any errors, we can utilize the PyScripter IDE.

output04a_originalnoisysignal_deep-learning
output03b_signalprocessing_deep-learning

What did the code above do?

1. Generate a Sample Signal 

We create a noisy sine wave as an example signal.

2. Plot the Original Noisy Signal 

We visualize the noisy signal.

3. RBFSampler 

We use the RBFSampler to approximate the RBF kernel, transforming the input data X into a higher-dimensional feature space.

4. Ridge Regression

We use Ridge regression on the transformed features to fit the model. Ridge regression is used here due to its robustness in handling collinearity and overfitting.

5. Predict the Signal

We use the trained model to predict the signal.

6. Plot the Original and Filtered Signal

We visualize the noisy signal alongside the filtered signal obtained through the RBFN.

Notes

  • The parameter gamma in RBFSampler controls the width of the RBF kernel. You might need to tune this parameter for your specific application.
  • The n_components parameter determines the number of features generated by the RBFSampler. Increasing this value can improve the model’s performance but will also increase computational complexity.
  • Ridge regression is used for its simplicity and effectiveness in this example. Depending on your application, other regression methods or neural network models could be used.

This code provides a basic framework for using RBFNs for signal processing tasks. You can further customize and optimize it for your specific requirements.

Conclusion

Radial Basis Function Networks (RBFNs) are a versatile and powerful tool in the deep learning and machine learning toolbox, particularly suited for tasks such as interpolation, classification, and regression. Their unique architecture and use of radial basis functions as activation functions allow them to effectively capture local patterns in data, making them highly valuable for specific applications.

By leveraging the power of Python and its rich ecosystem of libraries, you can efficiently implement and experiment with RBFNs for a wide range of tasks. Whether you are tackling stock market predictions, anomaly detection, or signal processing, Python’s straightforward syntax, extensive libraries, and strong community support make it an ideal choice for developing deep learning models.

RBFNs, with their simplicity and effectiveness, serve as building blocks for more complex neural networks and machine learning algorithms. While they may not always match the complexity and scalability of other models like Multilayer Perceptrons (MLPs) or Long Short-Term Memory networks (LSTMs), RBFNs offer a practical and interpretable approach to solving specific types of problems.

As you delve deeper into the world of deep learning and explore the capabilities of RBFNs, you’ll find that these networks provide a robust foundation for building intelligent systems that can learn and adapt. By continuously experimenting and refining your models, you can unlock the full potential of Python for deep learning with Radial Basis Function Networks.

Check out the full repository here:

github.com/Embarcadero/DL_Python06_RBFN


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL, which makes it simple to create Windows GUIs with Python.


References & further readings

[1] Biswal, A. (2023). 

Top 10 Deep Learning Algorithms You Should Know in 2023. Simplilearn. simplilearn.com/tutorials/deep-learning-tutorial/deep-learning-algorithm

[2] Buhmann, M. D. (2000). 

Radial basis functions. Acta numerica, 9, 1-38.

[3] Jwo, D. J., Biswal, A., & Mir, I. A. (2023). 

Artificial neural networks for navigation systems: A review of recent research. Applied Sciences, 13(7), 4475.

[4] Lowe, D., & Broomhead, D. (1988). 

Multivariable functional interpolation and adaptive networks. Complex systems, 2(3), 321-355.

[5] Olabanjo, O. A., Wusu, A. S., & Manuel, M. (2022). 

A machine learning prediction of academic performance of secondary school students using radial basis function neural network. Trends in Neuroscience and Education, 29, 100190.

[6] Park, J., & Sandberg, I. W. (1991). 

Universal approximation using radial-basis-function networks. Neural computation, 3(2), 246-257.

[7] scikit-learn developers. (2007-2024).

1.17.1. Multi-layer Perceptron, in 1.17. Neural network models (supervised). scikit-learn docs. scikit-learn.org/stable/modules/ neural_networks_supervised.html#multi-layer-perceptron

[8] Simplilearn. (2023). 

What are Radial Basis Functions Neural Networks? Everything You Need to Know. Simplilearn. simplilearn.com/tutorials/machine-learning-tutorial/what-are-radial-basis-functions-neural-networks

The post Unlock the Power of Python for Deep Learning with Radial Basis Function Networks (RBFNs) first appeared on Python GUI.

]]>
https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-radial-basis-function-networks-rbfns/feed/ 0 12534
Unlock the Power of Python for Deep Learning with Generative Adversarial Networks (GANs) – The Engine behind DALL-E https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-generative-adversarial-networks-gans-the-engine-behind-dall-e/ https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-generative-adversarial-networks-gans-the-engine-behind-dall-e/#respond Tue, 09 Apr 2024 10:00:00 +0000 https://pythongui.org/?p=11685 Deep learning algorithms work with almost any kind of data and require large amounts of computing power and information to solve complicated issues. Now, let us, deep-dive, into one of the most famous deep learning...

The post Unlock the Power of Python for Deep Learning with Generative Adversarial Networks (GANs) – The Engine behind DALL-E first appeared on Python GUI.

]]>
Deep learning algorithms work with almost any kind of data and require large amounts of computing power and information to solve complicated issues. Now, let us, deep-dive, into one of the most famous deep learning algorithms: Generative adversarial networks (GANs).

Generative adversarial networks (GANs) are an exciting (and relatively) recent innovation in machine learning and deep learning. GANs are generative deep learning algorithms that create new data instances that resemble the training data. GAN has two components: A generator, which learns to generate fake data, and a discriminator, which learns from that false information.

GANs are also the engine behind DALL-E, a recent breakthrough from OpenAI that can generate images from any text description.

If you are interested in learning how to use Python for deep learning with generative adversarial networks (GANs); which are a powerful technique for creating realistic and diverse synthetic data, this article is perfect for you. 

Before we begin, let’s see the remarkable ability of DALL-E (GAN) to generate a seemingly scientific photo of an atom:

first ever photo of an atom electron microscope by dall-e
Prompt: “First ever photo of an atom, electron microscope photo”. Created by: Niko × DALL·E.

What is Deep Learning?

Deep learning, a branch of machine learning, addresses intricate problems through the utilization of artificial neural networks. These networks consist of interconnected nodes organized in multiple layers, extracting features from input data. Extensive datasets are employed to train these models, enabling them to identify patterns and correlations that might be challenging or impossible for humans to perceive.

The impact of deep learning on artificial intelligence has been substantial. It has paved the way for the development of intelligent systems capable of independent learning, adaptation, and decision-making. Deep learning has led to remarkable advancements in various domains, encompassing image and speech recognition, natural language processing, machine translation, text generation, image generation (as would be reviewed in this article), autonomous driving, and numerous others.

thispersondoesnotexist GANs outputs
Examples of AI generated realistic human faces images using deep learning (GAN), that generated using thispersondoesnotexist.com.

Why Python for Deep Learning?

Python has gained widespread popularity as a programming language due to its versatility and ease of use in diverse domains of computer science, especially in the field of deep learning. Thanks to its extensive range of libraries and frameworks specially tailored for deep learning, Python has emerged as a top choice among many machine learning professionals.

Python has emerged as the language of choice for deep learning, and here are some of the reasons why:

1. Simple to learn and use:

Python is a high-level programming language that is easy to learn and use, even for those who are new to programming. Its concise and uncomplicated syntax makes it easy to write and understand. This allows developers to concentrate on solving problems without worrying about the details of the language.

2. Abundant libraries and frameworks:

Python has a vast ecosystem of libraries and frameworks that cater specifically to deep learning. Some of these libraries include TensorFlow, PyTorch, Keras, and Theano. These libraries provide pre-built functions and modules that simplify the development process, reducing the need to write complex code from scratch.

3. Strong community support:

Python has a large and active community of developers contributing to its development, maintenance, and improvement. This community offers support and guidance to beginners, making it easier to learn and use Python for deep learning.

4. Platform independence:

Python is platform-independent, which means that code written on one platform can be easily executed on another platform without any modification. This makes it easier to deploy deep learning models on different platforms and devices.

5. Easy integration with other languages:

Python can be easily integrated with other programming languages, such as Delphi, C++, and Java, making it ideal for building complex systems that require integrating different technologies.

Overall, Python’s ease of use, an abundance of libraries and frameworks, strong community support, platform independence, and ease of integration with other languages make it an indispensable tool for machine learning practitioners. Its popularity continues to soar as a result.

What is DALL-E? A revolutionary image generation model

DALL-E is a remarkable GAN model that can generate images from text descriptions (even an intricate one), such as “a cat wearing a bow tie” or “a painting of a landscape in the style of Van Gogh”. It is based on a large-scale dataset of text-image pairs, and a transformer architecture that can encode both text and image modalities.

Example of DALL-E generated images
Prompt: “a cat wearing a bow tie”.
Example of Van Gogh style AI generated images
Prompt: “a painting of a landscape in the style of Van Gogh”.

DALL-E can create plausible and diverse images for a wide range of concepts, such as animals, objects, scenes, and transformations, and control their attributes, viewpoints, and perspectives. DALL-E can also combine multiple concepts, such as “an armchair in the shape of an avocado” or “a snail made of a harp”, and generate novel and creative images that do not exist in the real world. DALL-E demonstrates the power and potential of GANs for image synthesis and multimodal understanding.

Example of AI generated images
Prompt: “an armchair in the shape of an avocado”.
Example of AI generated images
Prompt: “a snail made of a harp”.

Applications beyond DALL-E: GANs in various domains

DALL-E is based on a large-scale dataset of text-image pairs, and a transformer architecture that can encode both text and image modalities. DALL-E demonstrates the power and potential of GANs for image synthesis and multimodal understanding.

However, DALL-E is not the only application of GANs. GANs have been successfully applied to various domains and tasks, such as computer vision, natural language generation, audio synthesis, video prediction, and more. Some of the examples of GAN applications are:

1. Image generation

GANs can generate realistic and diverse images of objects, scenes, faces, animals, and more, from random noise or text descriptions.

2. Image-to-image translation

GANs can transform images from one domain to another, such as changing the style, season, or content of the images.

3. Image enhancement

GANs can improve the quality and resolution of images, such as super-resolution, deblurring, denoising, inpainting, and colorization.

4. Text generation

GANs can generate realistic and diverse texts, such as stories, poems, reviews, captions, and more, from random noise or keywords.

5. Text-to-speech

GANs can synthesize natural and expressive speech from text, such as voice cloning, style transfer, and emotion modulation.

6. Speech enhancement

GANs can improve the quality and intelligibility of speech, such as noise reduction, dereverberation, and bandwidth extension.

7. Video generation

GANs can generate realistic and diverse videos, such as animations, simulations, and future predictions, from random noise or text descriptions.

8. Video-to-video translation

GANs can transform videos from one domain to another, such as changing the style, content, or viewpoint of the videos.

What is Generative Adversarial Networks (GANs)?

Generative Adversarial Networks (GANs) are a breakthrough innovation in deep learning that can generate realistic and diverse data from random noise or text descriptions. GANs have many applications in various domains, such as computer vision, natural language generation, audio synthesis, and more. GANs can also enable creativity, accessibility, and fairness by generating novel and inclusive data that do not exist in the real world.

GANs consist of two neural networks that compete with each other in a game-like scenario: 

1. Discriminator

A discriminator that tries to distinguish between real and fake data.

More formally, given a set of data instances X and a set of labels Y: Discriminative models capture the conditional probability p(Y | X).

How an AI discriminator works
Backpropagation in discriminator training. Image source: Reference [4].

Illustration of the discriminative model in the handwritten digits generation use cases (we will explore the hands-on of it in the next sections):

Training samples
Image source: Reference [2].

2. Generator

A generator that tries to create fake data.

More formally, given a set of data instances X and a set of labels Y: Generative models capture the joint probability p(X, Y), or just p(X) if there are no labels.

00_gandiagram_generator-2079912
Backpropagation in generator testing. Image source: Reference [4].

Illustration of generative model in the handwritten digits generation use cases (we will explore the hands-on of it in the next sections):

00_figgenerative-9731713
Image source: Reference [2].

The discriminator and the generator are trained simultaneously, in an adversarial manner, until they reach an equilibrium, where the generator can fool the discriminator about half the time. GANs can learn to produce high-quality and diverse data, such as images, text, audio, and video, by leveraging large-scale datasets and advanced network architectures.

Here’s a picture of the whole GAN system:

00_gandiagram_wholesystem-8931350
Image source: Reference [4].

What are Python tools and libraries needed for GAN development?

Python is one of the most popular and widely used programming languages for machine learning and artificial intelligence, especially for developing generative adversarial networks (GANs). Python offers a rich set of tools and libraries that can help you implement and train GAN models with ease and efficiency. 

Some of the most useful and popular Python tools and libraries for GAN development are:

1. PyTorch

PyTorch is an open-source deep learning framework that provides a flexible and dynamic way of building and running GAN models. PyTorch supports automatic differentiation, GPU acceleration, distributed training, and various GAN architectures and loss functions. PyTorch also has a large and active community that contributes to the development and improvement of the framework[10].

2. TensorFlow

TensorFlow is another open-source deep learning framework that offers a comprehensive and scalable platform for building and deploying GAN models. TensorFlow supports eager execution, graph optimization, tensor operations, and various GAN architectures and loss functions. TensorFlow also has a high-level API called Keras, which simplifies the process of creating and training GAN models[10].

3. PyGAN

PyGAN is a Python library that implements GANs and its variants, such as conditional GANs, adversarial auto-encoders, and energy-based GANs. PyGAN allows you to design generative models based on statistical machine learning problems and optimize them using various algorithms and metrics[10].

4. TorchGAN

TorchGAN is a Python library that provides a collection of GAN models, loss functions, and evaluation metrics, built on top of PyTorch. TorchGAN enables you to easily create and customize your own GAN models, as well as reproduce the results of existing GAN papers[10].

5. VeGANs

VeGANs is another Python library that provides a variety of GAN models, loss functions, and evaluation metrics, built on top of PyTorch. VeGANs aims to make GAN development accessible and user-friendly, by offering a simple and consistent interface, as well as tutorials and examples[10].

Without further ado, let’s get our hands dirty with the hands-on GANs with Python, with three different use cases: Numerical mathematics (approximate a plot of a sine function), generating handwritten digits, and generating realistic human faces.

Hands-On GAN 1: Generate random numbers using GAN, to approximate sine plot

In this section, we will explore how GANs can be used to generate data that follows a simple sine function, between interval 0 and . We will implement a GAN using PyTorch and show how the generator and the discriminator networks interact and improve over time. We will also demonstrate the results of our GAN by comparing the generated data with the original sine function data.

The following is the complete Python code to automatically generate random numbers using GAN, to approximate sine plot:

import torch
from torch import nn
import math
import matplotlib.pyplot as plt

torch.manual_seed(111)

train_data_length = 1024
train_data = torch.zeros((train_data_length, 2))
train_data[:, 0] = 2 * math.pi * torch.rand(train_data_length)
train_data[:, 1] = torch.sin(train_data[:, 0])
train_labels = torch.zeros(train_data_length)
train_set = [
    (train_data[i], train_labels[i]) for i in range(train_data_length)
]

# Plot training data
plt.plot(train_data[:, 0], train_data[:, 1], ".")
plt.show()

# Create a PyTorch data loader
batch_size = 32
train_loader = torch.utils.data.DataLoader(
    train_set, batch_size=batch_size, shuffle=True
)

# Implementing the Discriminator
class Discriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(2, 256),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(256, 128),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(128, 64),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(64, 1),
            nn.Sigmoid(),
        )

    def forward(self, x):
        output = self.model(x)
        return output

# Instantiate a Discriminator object
discriminator = Discriminator()

# Implementing the Generator
class Generator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(2, 16),
            nn.ReLU(),
            nn.Linear(16, 32),
            nn.ReLU(),
            nn.Linear(32, 2),
        )

    def forward(self, x):
        output = self.model(x)
        return output

generator = Generator()

# Training the models
lr = 0.001
num_epochs = 300
loss_function = nn.BCELoss()

# Create the optimizers using Adam optimizer
optimizer_discriminator = torch.optim.Adam(discriminator.parameters(), lr=lr)
optimizer_generator = torch.optim.Adam(generator.parameters(), lr=lr)

# Implement a training loop in which training samples are fed to the models, and their weights are updated to minimize the loss function:
for epoch in range(num_epochs):
    for n, (real_samples, _) in enumerate(train_loader):
        # Data for training the discriminator
        real_samples_labels = torch.ones((batch_size, 1))
        latent_space_samples = torch.randn((batch_size, 2))
        generated_samples = generator(latent_space_samples)
        generated_samples_labels = torch.zeros((batch_size, 1))
        all_samples = torch.cat((real_samples, generated_samples))
        all_samples_labels = torch.cat(
            (real_samples_labels, generated_samples_labels)
        )

        # Training the discriminator
        discriminator.zero_grad()
        output_discriminator = discriminator(all_samples)
        loss_discriminator = loss_function(
            output_discriminator, all_samples_labels)
        loss_discriminator.backward()
        optimizer_discriminator.step()

        # Data for training the generator
        latent_space_samples = torch.randn((batch_size, 2))

        # Training the generator
        generator.zero_grad()
        generated_samples = generator(latent_space_samples)
        output_discriminator_generated = discriminator(generated_samples)
        loss_generator = loss_function(
            output_discriminator_generated, real_samples_labels
        )
        loss_generator.backward()
        optimizer_generator.step()

        # Show loss
        if epoch % 10 == 0 and n == batch_size - 1:
            print(f"Epoch: {epoch} Loss D.: {loss_discriminator}")
            print(f"Epoch: {epoch} Loss G.: {loss_generator}")

# Checking the samples generated by the GAN
latent_space_samples = torch.randn(100, 2)
generated_samples = generator(latent_space_samples)

generated_samples = generated_samples.detach()
plt.plot(generated_samples[:, 0], generated_samples[:, 1], ".")
plt.show()

To execute the code above seamlessly without any errors, we can utilize the PyScripter IDE.

What did the code above do?

Let’s break down the important parts of the code above:

1. Data generation:

  • train_data_length specifies the number of data points to be generated.
  • train_data is a tensor of shape (train_data_length, 2) where the first column represents random values between 0 and , and the second column is the sine of the first column.
  • train_labels is a tensor of zeros.
  • train_set is a list of tuples, each containing a data point and its corresponding label.

2. Data visualization:

  • The generated training data is plotted using matplotlib.

3. Data loader:

  • batch_size is set to 32.
  • train_loader is a PyTorch data loader that shuffles and batches the training data.

4. Discriminator model:

  • The Discriminator class is defined as a subclass of nn.Module.
  • It consists of a feedforward neural network with layers of sizes 2 (input) → 256128641, followed by a Sigmoid activation.
  • Dropout layers with a dropout probability of 0.3 are added for regularization.

5. Generator model:

  • The Generator class is defined, similar to the Discriminator.
  • It is a neural network with layers of sizes 2 (input) → 16322.

6. Model initialization:

  • Instances of the Discriminator and Generator classes are created.

7. Training configuration:

  • Learning rate (lr) is set to 0.001.
  • num_epochs is set to 300.
  • Binary Cross Entropy Loss (nn.BCELoss()) is used as the loss function.

8. Optimizer initialization:

  • Adam optimizers are created for both the discriminator and generator.

9. Training loop:

  • The code runs a training loop for the specified number of epochs.
  • For each epoch, it iterates through batches of data from the train_loader.
  • For the discriminator:
  • For the generator:
  • Losses for the discriminator and generator are printed every 10 epochs.

10. Generated samples visualization:

  • After training, 100 samples are generated using the trained generator, and they are plotted.

In summary, the code above implements a simple Generative Adversarial Network (GAN) where the generator and discriminator are trained adversarially to generate realistic samples. The generator generates fake samples to try and fool the discriminator, while the discriminator learns to distinguish between real and fake samples.

Here are a few selected outputs from all the process above:

Selected outputs:

Examine the training data by plotting each point (x₁, x₂):

Generative AI example in Python

Plot the generated samples. We show you the screenshot of the plotting results in epoch 300, which almost perfectly resemble the sine plot:

Generative AI example in Python

To see the progression between epoch (from 0 to 300) more clearly, please watch the following video:

Hands-On GAN 2: Generate handwritten digits using GAN

In this section, we will explore how GANs can be used to generate realistic images of handwritten digits. For that, you’ll train the models using the MNIST dataset of handwritten digits, which is included in the torchvision package. We will implement a GAN using PyTorch and show how the generator will produce fake images and the discriminator will try to tell them apart.

The following is the complete Python code to automatically generate handwritten digits using GAN:

import torch
from torch import nn, optim
import torchvision
import torchvision.transforms as transforms
import math
import matplotlib.pyplot as plt
import os

torch.manual_seed(111)

device = ''
if torch.cuda.is_available():
    device = torch.device('cuda')
else:
    device = torch.device('cpu')

transform = transforms.Compose(
    [transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,))])

train_set = torchvision.datasets.MNIST(root='.',
                                       train=True,
                                       download=True,
                                       transform=transform)

batch_size = 32
train_loader = torch.utils.data.DataLoader(train_set,
                                           batch_size=batch_size,
                                           shuffle=True)

plt.figure(dpi=150)
real_samples, mnist_labels = next(iter(train_loader))
for i in range(16):
    ax = plt.subplot(4, 4, i+1)
    plt.imshow(real_samples[i].reshape(28, 28), cmap='gray_r')
    plt.xticks([])
    plt.yticks([])
plt.tight_layout()

class Discriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(784, 1024),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(1024, 512),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(512, 256),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(256, 1),
            nn.Sigmoid()
        )

    def forward(self, x):
        x = x.view(x.size(0), 784)
        output = self.model(x)
        return output

discriminator = Discriminator().to(device=device)

class Generator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(100, 256),
            nn.ReLU(),
            nn.Linear(256, 512),
            nn.ReLU(),
            nn.Linear(512, 1024),
            nn.ReLU(),
            nn.Linear(1024, 784),
            nn.Tanh()
        )

    def forward(self, x):
        #x = x.view(x.size(0), 100)
        output = self.model(x)
        output = output.view(x.size(0), 1, 28, 28)
        return output

generator = Generator().to(device=device)

lr = 0.0001
num_epochs = 50
loss_function = nn.BCELoss()

optimizer_discriminator = torch.optim.Adam(discriminator.parameters(), lr=lr)
optimizer_generator = torch.optim.Adam(generator.parameters(), lr=lr)

latent_space_samples_plot = torch.randn((16, 100)).to(device=device)

# Load trained NN when it exists, or train a new NN
if os.path.isfile('discriminator.pt') and os.path.isfile('generator.pt'):
    discriminator.load_state_dict(torch.load('./discriminator.pt'))
    generator.load_state_dict(torch.load('./generator.pt'))
else:
    for epoch in range(num_epochs):
        for n, (real_samples, mnist_labels) in enumerate(train_loader):
            # Data for training the discriminator
            real_samples = real_samples.to(device=device)
            real_samples_labels = torch.ones((batch_size, 1)).to(device=device)
            latent_space_samples = torch.randn((batch_size, 100)).to(device=device)
            generated_samples = generator(latent_space_samples)
            generated_samples_labels = torch.zeros(
                (batch_size, 1)).to(device=device)
            all_samples = torch.cat((real_samples, generated_samples))
            all_samples_labels = torch.cat(
                (real_samples_labels, generated_samples_labels))

            # Training the discriminator
            discriminator.zero_grad()
            output_discriminator = discriminator(all_samples)
            loss_discriminator = loss_function(
                output_discriminator, all_samples_labels)
            loss_discriminator.backward()
            optimizer_discriminator.step()

            # Data for training the generator
            latent_space_samples = torch.randn((batch_size, 100)).to(device=device)

            # Training the generator
            generator.zero_grad()
            generated_samples = generator(latent_space_samples)
            output_discriminator_generated = discriminator(generated_samples)
            loss_generator = loss_function(
                output_discriminator_generated, real_samples_labels)
            loss_generator.backward()
            optimizer_generator.step()

            # Show loss
        	if n == batch_size - 1:
                print(f"Epoch: {epoch} Loss D.: {loss_discriminator}")
                print(f"Epoch: {epoch} Loss G.: {loss_generator}")

latent_space_samples = torch.randn(batch_size, 100).to(device=device)

generated_samples = generator(latent_space_samples)

generated_samples = generated_samples.cpu().detach()
plt.figure(dpi=150)
for i in range(16):
    ax = plt.subplot(4, 4, i+1)
    plt.imshow(generated_samples[i].reshape(28, 28), cmap='gray_r')
    plt.xticks([])
    plt.yticks([])
plt.tight_layout()

# Save trained NN parameters
torch.save(generator.state_dict(), 'generator.pt')
torch.save(discriminator.state_dict(), 'discriminator.pt')

To execute the code provided seamlessly, without any errors, we can utilize the PyScripter IDE.

What did the code above do?

Let’s break down the important parts of the code above:

1. Importing necessary libraries

  • torch for PyTorch, 
  • nn for neural network modules, 
  • optim for optimizers, 
  • torchvision for handling datasets like MNIST, 
  • transforms for data transformations, 
  • math for mathematical functions, 
  • matplotlib.pyplot for plotting, and 
  • os for operating system related functions.

2. Checking if a CUDA-enabled GPU is available and setting the device accordingly.

3. Defining a data transformation pipeline using transforms.Compose

It converts the images to PyTorch tensors and normalizes them.

4. Loading the MNIST dataset for training, 

specifying the root directory, setting it for training, downloading it if not available, and applying the defined transformation.

5. Creating a PyTorch data loader to handle batching and shuffling of the training data.

6. Plotting 16 real samples from the MNIST dataset using matplotlib.

7. Defining the Discriminator class, 

which is a neural network with several fully connected layers, ReLU activations, and Dropout layers. The final layer has a Sigmoid activation.

8. Implementing the forward method for the Discriminator class

and creating an instance of the Discriminator class, moving it to the specified device.

9. Defining the Generator class, 

which is another neural network with fully connected layers, ReLU activations, and a hyperbolic tangent (Tanh) activation.

10. Implementing the forward method for the Generator class

and creating an instance of the Generator class, moving it to the specified device.

11. Setting hyperparameters: 

  • learning rate (lr)
  • number of epochs (num_epochs), and using 
  • Binary Cross Entropy Loss (nn.BCELoss())
  • Initializing Adam optimizers for both the discriminator and generator.

12. Generating random samples in the latent space for visualization.

13. Loading pre-trained models if available, 

otherwise training the models for a specified number of epochs.

14. Generating and plotting 16 samples from the generator.

15. Saving the trained model parameters for future use.

Here are a few selected outputs from all the process above:

Selected outputs:

Download and extract the dataset:

Generative AI example in Python

Train the model with seed=111:

Generative AI example in Python

The following is the visualization of the excerpt of the MNIST dataset:

MINIST example set

vs the results of generated handwriting by GAN in epoch 50:

Plot using GAIN

To see the progression between epoch (from 0 to 50) more clearly, please see the following video:

Hands-On 3: Generate realistic human faces using GAN

In this section, we will learn how to generate realistic human faces using GANs. The GAN consists of two competing networks: A generator that creates fake images from random noise, and a discriminator that distinguishes real images from fake ones. We will use a large dataset of celebrity images to train our GAN and produce high-quality and diverse faces. However, as this task consumes large computational power, we will perform it using Kaggle’s GPU, while we will also show you the limitations and challenges of using a regular laptop.

Introduction to Kaggle’s GPU Options: P100 vs. T4

Kaggle offers its users a 30-hour weekly time cap for GPU access, allowing them to choose between NVIDIA T4 and P100 GPUs. However, many Kaggle users may lack clarity on which GPU is best suited for their specific needs.

In general, the T4 GPU is an optimal choice for inference workloads that demand high throughput and low power consumption. On the other hand, the P100 GPU excels in handling training workloads, thanks to its superior performance and increased memory capacity.[11].

It’s important to note that TPUs (Tensor Processing Units) are not part of this comparison, as they represent a distinct type of hardware accelerator designed by Google. When considering GPUs, the P100 is recommended for training tasks, while both the GPU P100 and GPU T4 can be utilized for inference purposes. Selecting the appropriate GPU depends on the specific requirements of the given machine learning task.[11].

The complete code for generating realistic human faces using GAN, and what did it do?

The following is the complete Python code to automatically generate realistic human faces using GAN:

import numpy as np # Linear algebra
import pandas as pd # Data processing, CSV file I/O (e.g. pd.read_csv)
import os
from matplotlib import pyplot as plt
from tqdm import tqdm
from PIL import Image as Img
from keras import Input
from keras.layers import Dense, Reshape, LeakyReLU, Conv2D, Conv2DTranspose, Flatten, Dropout
from keras.models import Model
from keras.optimizers import RMSprop

for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# Load the data and resize the images
PIC_DIR = f'../input/celeba-dataset/img_align_celeba/img_align_celeba/'

IMAGES_COUNT = 10000

ORIG_WIDTH = 178
ORIG_HEIGHT = 208
diff = (ORIG_HEIGHT - ORIG_WIDTH) // 2

WIDTH = 128
HEIGHT = 128

crop_rect = (0, diff, ORIG_WIDTH, ORIG_HEIGHT - diff)

images = []
for pic_file in tqdm(os.listdir(PIC_DIR)[:IMAGES_COUNT]):
    pic = Image.open(PIC_DIR + pic_file).crop(crop_rect)
    pic.thumbnail((WIDTH, HEIGHT), Image.ANTIALIAS)
    images.append(np.uint8(pic))

#Image shape
images = np.array(images) / 255
print(images.shape)

#Display first 25 images
plt.figure(1, figsize=(10, 10))
for i in range(25):
    plt.subplot(5, 5, i+1)
    plt.imshow(images[i])
    plt.axis('off')
plt.show()

# Create Generator
LATENT_DIM = 32
CHANNELS = 3

def create_generator():
    gen_input = Input(shape=(LATENT_DIM, ))

    x = Dense(128 * 16 * 16)(gen_input)
    x = LeakyReLU()(x)
    x = Reshape((16, 16, 128))(x)

    x = Conv2D(256, 5, padding='same')(x)
    x = LeakyReLU()(x)

    x = Conv2DTranspose(256, 4, strides=2, padding='same')(x)
    x = LeakyReLU()(x)

    x = Conv2DTranspose(256, 4, strides=2, padding='same')(x)
    x = LeakyReLU()(x)

    x = Conv2DTranspose(256, 4, strides=2, padding='same')(x)
    x = LeakyReLU()(x)

    x = Conv2D(512, 5, padding='same')(x)
    x = LeakyReLU()(x)
    x = Conv2D(512, 5, padding='same')(x)
    x = LeakyReLU()(x)
    x = Conv2D(CHANNELS, 7, activation='tanh', padding='same')(x)

    generator = Model(gen_input, x)
    return generator

# Create Discriminator
def create_discriminator():
    disc_input = Input(shape=(HEIGHT, WIDTH, CHANNELS))

    x = Conv2D(256, 3)(disc_input)
    x = LeakyReLU()(x)

    x = Conv2D(256, 4, strides=2)(x)
    x = LeakyReLU()(x)

    x = Conv2D(256, 4, strides=2)(x)
    x = LeakyReLU()(x)

    x = Conv2D(256, 4, strides=2)(x)
    x = LeakyReLU()(x)

    x = Conv2D(256, 4, strides=2)(x)
    x = LeakyReLU()(x)

    x = Flatten()(x)
    x = Dropout(0.4)(x)

    x = Dense(1, activation='sigmoid')(x)
    discriminator = Model(disc_input, x)

    optimizer = RMSprop(
        lr=.0001,
        clipvalue=1.0,
        decay=1e-8
    )

    discriminator.compile(
        optimizer=optimizer,
        loss='binary_crossentropy'
    )

    return discriminator

# Define a GAN Model
from IPython.display import Image
from keras.utils.vis_utils import model_to_dot

generator = create_generator()
generator.summary()

Image(model_to_dot(generator, show_shapes=True).create_png())

discriminator = create_discriminator()
discriminator.trainable = False
discriminator.summary()

Image(model_to_dot(discriminator, show_shapes=True).create_png())

gan_input = Input(shape=(LATENT_DIM, ))
gan_output = discriminator(generator(gan_input))
gan = Model(gan_input, gan_output)

optimizer = RMSprop(lr=.0001, clipvalue=1.0, decay=1e-8)
gan.compile(optimizer=optimizer, loss='binary_crossentropy')

gan.summary()

# Training the GAN model
import time

iters = 15000
batch_size = 16

RES_DIR = 'res2'
FILE_PATH = '%s/generated_%d.png'
if not os.path.isdir(RES_DIR):
    os.mkdir(RES_DIR)

CONTROL_SIZE_SQRT = 6
control_vectors = np.random.normal(size=(CONTROL_SIZE_SQRT**2, LATENT_DIM)) / 2

start = 0
d_losses = []
a_losses = []
images_saved = 0

for step in range(iters):
    start_time = time.time()
    latent_vectors = np.random.normal(size=(batch_size, LATENT_DIM))
    generated = generator.predict(latent_vectors)

    real = images[start:start + batch_size]
    combined_images = np.concatenate([generated, real])

    labels = np.concatenate([np.ones((batch_size, 1)), np.zeros((batch_size, 1))])
    labels += .05 * np.random.random(labels.shape)

    d_loss = discriminator.train_on_batch(combined_images, labels)
    d_losses.append(d_loss)

    latent_vectors = np.random.normal(size=(batch_size, LATENT_DIM))
    misleading_targets = np.zeros((batch_size, 1))

    a_loss = gan.train_on_batch(latent_vectors, misleading_targets)
    a_losses.append(a_loss)

    start += batch_size
    if start > images.shape[0] - batch_size:
        start = 0

    if step % 50 == 49:
        gan.save_weights('/gan.h5')

        print('%d/%d: d_loss: %.4f,  a_loss: %.4f.  (%.1f sec)' % (step + 1, iters, d_loss, a_loss, time.time() - start_time))

        control_image = np.zeros((WIDTH * CONTROL_SIZE_SQRT, HEIGHT * CONTROL_SIZE_SQRT, CHANNELS))
        control_generated = generator.predict(control_vectors)

        for i in range(CONTROL_SIZE_SQRT ** 2):
            x_off = i % CONTROL_SIZE_SQRT
            y_off = i // CONTROL_SIZE_SQRT
            control_image[x_off * WIDTH:(x_off + 1) * WIDTH, y_off * HEIGHT:(y_off + 1) * HEIGHT, :] = control_generated[i, :, :, :]
        im = Img.fromarray(np.uint8(control_image * 255))#.save(StringIO(), 'jpeg')
        im.save(FILE_PATH % (RES_DIR, images_saved))
        images_saved += 1

plt.figure(1, figsize=(12, 8))
plt.subplot(121)
plt.plot(d_losses, color='red')
plt.xlabel('epochs')
plt.ylabel('discriminant losses')
plt.subplot(122)
plt.plot(a_losses)
plt.xlabel('epochs')
plt.ylabel('adversary losses')
plt.show()

To execute the code provided seamlessly, without any errors, we can utilize the PyScripter IDE.

Let’s break down the important parts of the code above:

1. Importing necessary libraries for:

  • numerical operations (numpy), 
  • data processing (pandas), 
  • plotting (matplotlib), 
  • tqdm for progress bars, and
  • components from keras for building a Generative Adversarial Network (GAN).

2. Walking through the Kaggle input directory and printing the filenames.

3. Setting up parameters for loading and resizing images from the CelebA dataset.

Cropping and resizing images to a specified size.

4. Converting the list of images to a NumPy array 

and normalizing pixel values to the range [0, 1].

5. Displaying the first 25 images from the dataset.

6. Defining the generator model architecture using Keras.

7. Defining the discriminator model architecture using Keras.

8. Creating an instance of the generator and displaying its summary.

9. Creating an instance of the discriminator and displaying its summary. 

Setting trainable to False to prevent it from being trained during the GAN training phase.

10. Creating the GAN model by connecting the generator and discriminator

Compiling the GAN model with a binary cross-entropy loss.

11. Setting up parameters for training the GAN model and creating directories for saving generated images.

12. Training the GAN model, 

  • saving weights periodically, and plotting the losses during training. 
  • Images are also generated and saved for visualization.

Selected outputs:

Load and resize CelebA dataset:

Generative AI example in Python

Show image shape:

output07_printimageshape-2602965

Display first 25 images:

Generative AI example in Python

Generator summary:

Generative AI example in Python-3048847

Generator scheme (as generated automatically using model_to_dot function from keras.utils.vis_utils):

output14_kaggle-defineganmodel_generator-7626898

Discriminator summary:

Generative AI example in Python

Discriminator scheme (also generated automatically using model_to_dot function from keras.utils.vis_utils):

output15_kaggle-defineganmodel_discriminator-7280900

GAN summary:

_________________________________________________________________
Model: "model_2"
_________________________________________________________________
Layer (type)             	Output Shape          	Param #   
=================================================================
input_3 (InputLayer)     	[(None, 32)]          	0    	 
_________________________________________________________________
model (Functional)       	(None, 128, 128, 3)   	14953987  
_________________________________________________________________
model_1 (Functional)     	(None, 1)             	4211713   
=================================================================
Total params: 19,165,700
Trainable params: 14,953,987
Non-trainable params: 4,211,713
_________________________________________________________________

After the step above, further training and output production would require a sufficient GPU, so, for the next steps, I move on using Kaggle (with GPU P100 as accelerator). 

Here is the screenshot of the last step that can be done without GPU using PyScripter IDE (if you have your own GPU, you can continue run the code on your PyScripter IDE seamlessly):

Generative AI example in Python

Plot of Discriminant and Adversary losses:

Generative AI example in Python

Quoting Reference [3] to help in interpreting the plot of Discriminant and Adversary losses: “GAN convergence is hard to identify. As the generator improves with training, the discriminator performance gets worse because the discriminator can’t easily tell the difference between real and fake. If the generator succeeds perfectly, then the discriminator has a 50% accuracy. In effect, the discriminator flips a coin to make its prediction.

This progression poses a problem for convergence of the GAN as a whole: the discriminator feedback gets less meaningful over time. If the GAN continues training past the point when the discriminator is giving completely random feedback, then the generator starts to train on junk feedback, and its quality may collapse.”

After 300 epochs, the code would produce the following realistic human faces:

  • On Kaggle /output:
Generative AI example in Python
  • On my computer:
Generative AI example in Python

Image output for the first epoch (0) vs the 300th epoch (299):

Generative AI example in Python
Generative AI example in Python

To see the progression between epoch (from 0 to 299) more clearly, please see the following video:

Out of curiosity, I retrain the model until epoch 599, which you can see the results (from epoch 300 to 599) in the following video:

Conclusion

GANs are a powerful and versatile class of deep generative models that can produce realistic and diverse data, such as images, text, audio, and video, from random noise. You also learned how GANs can generate realistic and diverse data using text descriptions as demonstrated by DALL-E.

This article has highlighted and demonstrated the potential use of deep learning, specifically within the context of the GANs architecture in the domain of numerical mathematics (approximate a plot of a function), generating handwritten digits, and generating realistic human faces. All are implemented with hands-on Python examples.

I hope this article was successful in giving you a comprehensive and accessible introduction to GANs, and a solid understanding and workflow of how to implement GANs to your domains and project goals, so, it would inspire you to learn more and experiment with GANs yourself.

Check out the full repository here:

github.com/Embarcadero/DL_Python05_GAN


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL, which makes it simple to create Windows GUIs with Python.


References & further readings

[1] Biswal, A. (2023).

Top 10 Deep Learning Algorithms You Should Know in 2023. Simplilearn. simplilearn.com/tutorials/deep-learning-tutorial/deep-learning-algorithm.

[2] Candido, R. (2021).

Generative Adversarial Networks: Build Your First Models. Real Python. realpython.com/generative-adversarial-networks.

[3] Chauhan, N. S. (2021).

Generate Realistic Human Face using GAN. Kaggle. kaggle.com/code/nageshsingh/generate-realistic-human-face-using-gan.

[4] Google for Developers. (2024).

Generative Adversarial Networks. Advanced courses, machine learning, Google for Developers. developers.google.com/machine-learning/gan.

[5] LeCun, Y. (1998).

The MNIST database of handwritten digits. yann.lecun.com/exdb/mnist.

[6] Liu, Z., Luo, P., Wang, X., & Tang, X. (2018).

Large-scale celebfaces attributes (celeba) dataset. Retrieved August, 15(2018), 11. mmlab.ie.cuhk.edu.hk/projects/CelebA.html.

[7] Goodfellow, I., Pouget-Abadie, J., Mirza, M., Xu, B., Warde-Farley, D., Ozair, S., … & Bengio, Y. (2014).

Generative adversarial nets. Advances in neural information processing systems, 27.

[8] Goodfellow, I., Pouget-Abadie, J., Mirza, M., Xu, B., Warde-Farley, D., Ozair, S., … & Bengio, Y. (2020).

Generative adversarial networks. Communications of the ACM, 63(11), 139-144.

[9] Ramesh, A., Pavlov, M., Goh, G., Gray, S., Chen, M., Child, R., Misra, V., Mishkin, P., Krueger, G., Agarwal, S., & Sutskever, I. (2015-2023).

DALL·E: Creating images from text. DALL-E, OpenAI research. openai.com/research/dall-e.

[10] Sagar, R. (2020).

Top Libraries For Quick Implementation Of GANs. Analytics India Magazine. analyticsindiamag.com/generative-adversarial-networks-python-libraries.

[11] Siddhartha. (2023).

GPU T4 vs GPU P100 | Kaggle | GPU. Medium. siddhartha01writes.medium.com/gpu-t4-vs-gpu-p100-kaggle-gpu-cd852d56022c.

The post Unlock the Power of Python for Deep Learning with Generative Adversarial Networks (GANs) – The Engine behind DALL-E first appeared on Python GUI.

]]>
https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-generative-adversarial-networks-gans-the-engine-behind-dall-e/feed/ 0 11685
How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API https://pythongui.org/how-to-create-a-weather-app-with-the-python-delphi-ecosystem-and-weatherstack-api/ https://pythongui.org/how-to-create-a-weather-app-with-the-python-delphi-ecosystem-and-weatherstack-api/#respond Thu, 02 Nov 2023 20:59:44 +0000 https://pythongui.org/?p=11441 Weather has always held a certain fascination for us, shaping our daily decisions and guiding our plans. As technology continues to weave itself into every facet of our lives, it’s no surprise that it has...

The post How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API first appeared on Python GUI.

]]>
Weather has always held a certain fascination for us, shaping our daily decisions and guiding our plans. As technology continues to weave itself into every facet of our lives, it’s no surprise that it has also transformed how we interact with the weather. In this article, we will create a weather app that blends the power of the Python Delphi ecosystem with the rich data streams of the Weatherstack API. 

Our destination? An elegant form housing a search bar that opens up a world of meteorological insight. With three distinct tabs – historical, current, and prediction – we’ll explore the weather’s past, present, and future, bringing it all to your fingertips. So, let’s dive into the world of weather forecasting with DelphiFMX and Weatherstack, and let the forecasts begin!

How to Build a Feature-Packed Weather App With Delphi FMX?

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Creating a weather application with DelphiFMX involves a series of key steps. First, install the Delphi Integrated Development Environment (IDE) and the Python FireMonkey GUI framework on your PC. These are the fundamental tools you’ll need to craft your weather app. Also, ensure you have the Delphi4PythonExporter tool set up along with a text editor or an IDE that supports Python, such as PyScripter. If you haven’t set up these essential tools yet, consider referring to the article “Setting Up a Robust Python GUI Project” for a head start.

Furthermore, it’s crucial to prepare for data retrieval from Weatherstack API. To do this, sign up and subscribe to a plan on Weatherstack’s website. While this tutorial uses the plan providing access to all endpoints, you can certainly begin with the free plan, utilizing the current weather endpoint to get started.

To access the source code and resources for this tutorial, you can download them from our GitHub repository using the following link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/WeatherApp

What Kind of a Form do I Need For this Python GUI App?

Let’s launch the Delphi application and set up a new project. Navigate to the File menu, choose New -> Multi-Device Application, and select Blank Application before clicking OK. For this tutorial, we’ve given our project the name “WeatherApp.”
If you’re not yet familiar with the different sections and features within the Delphi IDE, we recommend checking out our complimentary eBook bundle. This resource offers a comprehensive overview of the Delphi Python EcoSystem and various Python GUI offerings.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Now, let’s assign a name to our primary form. Right-click on the form and choose QuickEdit. In this case, we’ll name our form MainForm and add the caption Weather App.

To simplify file tracking, we’ll rename the source file for MainForm to WeatherApp.pas. Additionally, you can adjust the form’s dimensions using the Object Inspector, modifying ClientWidth and ClientHeight properties, or simply by dragging and resizing it with your mouse.

For this weather app, we’ll utilize the TTabControl component in the IDE to create two tabs on our form: one for current weather and the other for weather predictions. You can find this component in the Palette, and it can be added by simply dragging and dropping it onto the form.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Expand the component to cover the entire form area. This is how our form looks like.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Right-click on the component and select AddTabItem to add tabs to the form. As previously mentioned, we will include three tabs: one for displaying current weather, one for historical weather data, and another for future weather predictions. Then, use QuickEdit to rename the tabs to Current, Historical, and Prediction respectively.

Before, adding components to our tabs, let’s add a drop down menu, using the TComboBox component to help the user select a city for the app, as well as a few TLabel components. We will also use the text settings property of each label to make them more visually appealing. Here is what our form looks like:

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Now that we’ve completed the top of our form, let’s start adding components to each tab of our TTabControl component. We will start by opening up the prediction tab of our form. Here we will be adding three different components. The TMemo component will be used to show the user the weather data. A TSpinBox component will be used to ask the user the number of days after which the user will show the data. Finally a TButton component will be used to call on the API to retrieve the weather data. We will also add a few TLabel components to help the user navigate through the form. Here is what our form looks like:

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Now that our prediction tab is completed let’s complete our Current weather tab. Start by opening up the tab, and just like the Prediction tab, we will be adding a TMemo component to display our results as well as a TButton component to get the data. In addition, we will also be adding a TImage component that will be used to display an image consistent with our current weather. Here is what our form looks like:

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Finally, let’s add some components to our Historical tab. Similar to the Prediction and Current Tab’s we will be adding a TButton and TMemo component. However, we will also be adding a TCalender component to help the user select the data for a specific historical date. Here is what our form looks like:

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Now that we are done with the form’s, let’s infuse some style to make them more appealing. To do this, you’ll need to obtain the free eBook bundle, which includes various styles. Download the eBook and extract the FMX styles ZIP file to your preferred directory. Now select the style you want to use, in this tutorial we’ll be using the Dark.style from the bundle.

Now Go to the Palette and add the TStyleBook component to your form.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Double-click on the StyleBook1 component to access the Style Designer. Now click the open button, which will prompt a dialog box to appear.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Navigate to the .style file within the dialog box, select the file, and then click exit.

Now, select the form and access the Object Inspector. Locate the StyleBook property, choose the drop-down menu, and select StyleBook1.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Here’s what our form looks like:

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

With the forms now complete, the last step requires us to add functionality to each button of our form. To do this, navigate to the location of each button in the form and double-click on each button. This action creates an OnClick method for that button subsequently creating a procedure in the .pas file and corresponds it to the .fmx file. This will allow you to add unique functionalities to each button when clicked.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

However, due to the Delphi4PythonExporter’s lack of runtime implementation, we need to include at least one comment (//) in each procedure to preserve its function when exporting the form.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

How Can I Export The Form Into a Python Script?

Now that our form is ready, we can export the project by navigating to Tools > Export To Python > Export Current Entire Project.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Here, we will give the project the title Weather App. Next, select the directory of your choosing and click on Export:

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Because we had one form, Delphi generated two Python files and one .pyfmx file. The WeatherApp.py file will be used to run the application, whereas the Main.py file contains the class for the MainForm. The Main.pyfmx file contains the visual information for the MainForm. Here are the contents for each file.

WeatherApp.py:

from delphifmx import *
from Main import MainForm

def main():
    Application.Initialize()
    Application.Title = 'Weather App'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Main.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.TabControl1 = None
        self.HistoricalTab = None
        self.HistoryButton = None
        self.Calendar1 = None
        self.HistoricalMemo = None
        self.DateLabel = None
        self.CurrentTab = None
        self.CurrentButton = None
        self.Image1 = None
        self.CurrentMemo = None
        self.PredictionTab = None
        self.Edit2 = None
        self.TabControl2 = None
        self.TabItem1 = None
        self.Button1 = None
        self.Calendar2 = None
        self.Memo1 = None
        self.Label1 = None
        self.TabItem2 = None
        self.Button2 = None
        self.Image2 = None
        self.Memo2 = None
        self.TabItem3 = None
        self.Edit1 = None
        self.PredictButton = None
        self.SpinBox1 = None
        self.PredictLabel = None
        self.PredictLabel2 = None
        self.PredictMemo = None
        self.TitleLabel = None
        self.CityLabel = None
        self.CityCombo = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def HistoryButtonClick(self, Sender):
        pass

    def CurrentButtonClick(self, Sender):
        pass

    def PredictButtonClick(self, Sender):
        pass

How Can I Use the Weatherstack API to Add Functionality to this Form?

Now the only thing that remains is to add functionality to our app. Let’s start by opening up the Main.py file and importing some libraries.

import os
from delphifmx import *

# Additional Imports
import requests

Next, navigate to the __init__ function. Here we will populate the CityCombo box using APILayer’s geolocation API. We will use the API to retrieve all the cities in the United States, and then populate the combo box. Here is what our __init__ funciton looks like:

def __init__(self, owner):
        self.TabControl1 = None
        self.HistoricalTab = None
        self.HistoryButton = None
        self.Calendar1 = None
        self.CurrentTab = None
        self.CurrentButton = None
        self.Image1 = None
        self.PredictionTab = None
        self.Edit2 = None
        self.PredictButton = None
        self.TitleLabel = None
        self.CityLabel = None
        self.HistoricalMemo = None
        self.DateLabel = None
        self.CurrentMemo = None
        self.SpinBox1 = None
        self.PredictLabel = None
        self.PredictLabel2 = None
        self.PredictMemo = None
        self.CityCombo = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Get all cities in a particular country
        url = "https://api.apilayer.com/geo/country/cities/US"

        payload = {}
        headers= {
        "apikey": "your_api_key"
        }

        response = requests.request("GET", url, headers=headers, data = payload)
        result = response.json()

        # Store all cities in a list and even populate the combo box
        self.cities = []
        for city in result:
            self.CityCombo.Items.Add(city["name"])
            self.cities.append(city["name"])

Now that our CityCombo box is populated, let’s head over to the HistoryButtonClick function. Here we will start off by retrieving the date from the TCalender component and, using a combination of .format() and .zfill(), convert it to an appropriate format.

def HistoryButtonClick(self, Sender):
        date = '{}-{}-{}'.format(self.Calendar1.DateTime[0], str(self.Calendar1.DateTime[1]).zfill(2), str(self.Calendar1.DateTime[2]).zfill(2)) # Storing date from calendar in the required format

Next, we will define some parameters for our API, then use the ‘historical‘ endpoint of the weatherstack API to retrieve the historical data for a selected city. Here is what our final HistoryButtonClick function looks like:

def HistoryButtonClick(self, Sender):
        date = '{}-{}-{}'.format(self.Calendar1.DateTime[0], str(self.Calendar1.DateTime[1]).zfill(2), str(self.Calendar1.DateTime[2]).zfill(2)) # Storing date from calendar in the required format
       
        params = {
        'access_key': 'your_api_access_key',
        'query': self.cities[self.CityCombo.ItemIndex],
        'historical_date': date
        }
       
        api_result = requests.get('http://api.weatherstack.com/historical', params)
        api_response = api_result.json()

        self.HistoricalMemo.Lines.Add("Location : " + api_response["location"]["name"])
        self.HistoricalMemo.Lines.Add("Min Temperature : " + str(api_response["historical"][date]["mintemp"]))
        self.HistoricalMemo.Lines.Add("Max Temperature : " + str(api_response["historical"][date]["maxtemp"]))
        self.HistoricalMemo.Lines.Add("Avg Temperature : " + str(api_response["historical"][date]["avgtemp"]))
        self.HistoricalMemo.Lines.Add("UV_Index : " + str(api_response["historical"][date]["uv_index"]))

Now similarly to the HistoryButtonClick function, we will define our CurrentClickButton. Here, instead of the ‘historical‘ endpoint, we will be using the ‘current‘ endpoint to retrieve the data weather data. We will then uses the .Add method of the TMemo component to display it on our form:

def CurrentButtonClick(self, Sender):
        params = {
        'access_key': 'your_api_access_key',
        'query': self.cities[self.CityCombo.ItemIndex]
        }
       
        api_result = requests.get('http://api.weatherstack.com/current', params)
        api_response = api_result.json()

        self.CurrentMemo.Lines.Add("Location : " + api_response["location"]["name"])
        self.CurrentMemo.Lines.Add("Temperature: " + str(api_response["current"]["temperature"]))
        self.CurrentMemo.Lines.Add("Feels Like: " + str(api_response["current"]["feelslike"]))
        self.CurrentMemo.Lines.Add("Description: " + api_response["current"]["weather_descriptions"][0])
        self.CurrentMemo.Lines.Add("Percipitation : " + str(api_response["current"]["precip"]))
        self.CurrentMemo.Lines.Add("Humidity: " + str(api_response["current"]["humidity"]))
        self.CurrentMemo.Lines.Add("Windspeed: " + str(api_response["current"]["wind_speed"]))
        self.CurrentMemo.Lines.Add("Pressure: " + str(api_response["current"]["pressure"]))
        self.CurrentMemo.Lines.Add("UV_Index: " + str(api_response["current"]["uv_index"]))
        self.CurrentMemo.Lines.Add("Visibility: " + str(api_response["current"]["visibility"]))

In addition to this, we will also use the image_url parameter generated by the API, to first save the image and then display the image on our Current tab. Here is what our final function looks like:

def CurrentButtonClick(self, Sender):
        params = {
        'access_key': 'your_api_access_key',
        'query': self.cities[self.CityCombo.ItemIndex]
        }
       
        api_result = requests.get('http://api.weatherstack.com/current', params)
        api_response = api_result.json()

        self.CurrentMemo.Lines.Add("Location : " + api_response["location"]["name"])
        self.CurrentMemo.Lines.Add("Temperature: " + str(api_response["current"]["temperature"]))
        self.CurrentMemo.Lines.Add("Feels Like: " + str(api_response["current"]["feelslike"]))
        self.CurrentMemo.Lines.Add("Description: " + api_response["current"]["weather_descriptions"][0])
        self.CurrentMemo.Lines.Add("Percipitation : " + str(api_response["current"]["precip"]))
        self.CurrentMemo.Lines.Add("Humidity: " + str(api_response["current"]["humidity"]))
        self.CurrentMemo.Lines.Add("Windspeed: " + str(api_response["current"]["wind_speed"]))
        self.CurrentMemo.Lines.Add("Pressure: " + str(api_response["current"]["pressure"]))
        self.CurrentMemo.Lines.Add("UV_Index: " + str(api_response["current"]["uv_index"]))
        self.CurrentMemo.Lines.Add("Visibility: " + str(api_response["current"]["visibility"]))

        # URL of the image you want to load
        image_url = api_response["current"]["weather_icons"][0]

        # Send a GET request to the URL to retrieve the image data
        response = requests.get(image_url)

        if response.status_code == 200:
            # Read the image data from the response content
            image_data = response.content

            # Local path to save the image
            local_path = "image.png"        
            # Save the image locally
            with open(local_path, "wb") as image_file:
                image_file.write(image_data)
           
            self.Image1.Bitmap.LoadFromFile(local_path)

Finally, navigate to the PredictButtonClick function and, like the previous functions, we will use the ‘forecast‘ endpoint to retrieve the future prediction. Additionally, we will also use the .Text property of the TSpinBox component to get the number of days. Here is what our function looks like:

def PredictButtonClick(self, Sender):
        params = {
        'access_key': 'your_api_access_key',
        'query': self.cities[self.CityCombo.ItemIndex],
        'forecast_days': self.SpinBox1.Text,
        }
       
        api_result = requests.get('http://api.weatherstack.com/forecast', params)
        api_response = api_result.json()

        forecast = api_response["forecast"]

        # Iterate through the forecast dates
        for date, date_data in forecast.items():
            self.PredictMemo.Lines.Add("Date: " + date)
            self.PredictMemo.Lines.Add("Min Temperature: " + str(date_data["mintemp"]))
            self.PredictMemo.Lines.Add("Max Temperature: " + str(date_data["maxtemp"]))
            self.PredictMemo.Lines.Add("Avg Temperature: " + str(date_data["avgtemp"]))
            self.PredictMemo.Lines.Add("UV_Index: " + str(date_data["uv_index"]))
            self.PredictMemo.Lines.Add("")  # Add an empty line for separation

Here is what our final Main.py file looks like:

import os
from delphifmx import *

# Additional Imports
import requests

class MainForm(Form):

    def __init__(self, owner):
        self.TabControl1 = None
        self.HistoricalTab = None
        self.HistoryButton = None
        self.Calendar1 = None
        self.CurrentTab = None
        self.CurrentButton = None
        self.Image1 = None
        self.PredictionTab = None
        self.Edit2 = None
        self.PredictButton = None
        self.TitleLabel = None
        self.CityLabel = None
        self.HistoricalMemo = None
        self.DateLabel = None
        self.CurrentMemo = None
        self.SpinBox1 = None
        self.PredictLabel = None
        self.PredictLabel2 = None
        self.PredictMemo = None
        self.CityCombo = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Get all cities in a particular country
        url = "https://api.apilayer.com/geo/country/cities/US"

        payload = {}
        headers= {
        "apikey": "'your_api_key'"
        }

        response = requests.request("GET", url, headers=headers, data = payload)
        result = response.json()

        # Store all cities in a list and even populate the combo box
        self.cities = []
        for city in result:
            self.CityCombo.Items.Add(city["name"])
            self.cities.append(city["name"])

    def HistoryButtonClick(self, Sender):
        date = '{}-{}-{}'.format(self.Calendar1.DateTime[0], str(self.Calendar1.DateTime[1]).zfill(2), str(self.Calendar1.DateTime[2]).zfill(2)) # Storing date from calendar in the required format
       
        params = {
        'access_key': 'your_api_access_key',
        'query': self.cities[self.CityCombo.ItemIndex],
        'historical_date': date
        }
       
        api_result = requests.get('http://api.weatherstack.com/historical', params)
        api_response = api_result.json()

        self.HistoricalMemo.Lines.Add("Location : " + api_response["location"]["name"])
        self.HistoricalMemo.Lines.Add("Min Temperature : " + str(api_response["historical"][date]["mintemp"]))
        self.HistoricalMemo.Lines.Add("Max Temperature : " + str(api_response["historical"][date]["maxtemp"]))
        self.HistoricalMemo.Lines.Add("Avg Temperature : " + str(api_response["historical"][date]["avgtemp"]))
        self.HistoricalMemo.Lines.Add("UV_Index : " + str(api_response["historical"][date]["uv_index"]))


    def CurrentButtonClick(self, Sender):
        params = {
        'access_key': 'your_api_access_key',
        'query': self.cities[self.CityCombo.ItemIndex]
        }
       
        api_result = requests.get('http://api.weatherstack.com/current', params)
        api_response = api_result.json()

        self.CurrentMemo.Lines.Add("Location : " + api_response["location"]["name"])
        self.CurrentMemo.Lines.Add("Temperature: " + str(api_response["current"]["temperature"]))
        self.CurrentMemo.Lines.Add("Feels Like: " + str(api_response["current"]["feelslike"]))
        self.CurrentMemo.Lines.Add("Description: " + api_response["current"]["weather_descriptions"][0])
        self.CurrentMemo.Lines.Add("Percipitation : " + str(api_response["current"]["precip"]))
        self.CurrentMemo.Lines.Add("Humidity: " + str(api_response["current"]["humidity"]))
        self.CurrentMemo.Lines.Add("Windspeed: " + str(api_response["current"]["wind_speed"]))
        self.CurrentMemo.Lines.Add("Pressure: " + str(api_response["current"]["pressure"]))
        self.CurrentMemo.Lines.Add("UV_Index: " + str(api_response["current"]["uv_index"]))
        self.CurrentMemo.Lines.Add("Visibility: " + str(api_response["current"]["visibility"]))

        # URL of the image you want to load
        image_url = api_response["current"]["weather_icons"][0]

        # Send a GET request to the URL to retrieve the image data
        response = requests.get(image_url)

        if response.status_code == 200:
            # Read the image data from the response content
            image_data = response.content

            # Local path to save the image
            local_path = "image.png"        
            # Save the image locally
            with open(local_path, "wb") as image_file:
                image_file.write(image_data)
           
            self.Image1.Bitmap.LoadFromFile(local_path)

    def PredictButtonClick(self, Sender):
        params = {
        'access_key': 'your_api_access_key',
        'query': self.cities[self.CityCombo.ItemIndex],
        'forecast_days': self.SpinBox1.Text,
        }
       
        api_result = requests.get('http://api.weatherstack.com/forecast', params)
        api_response = api_result.json()

        forecast = api_response["forecast"]

        # Iterate through the forecast dates
        for date, date_data in forecast.items():
            self.PredictMemo.Lines.Add("Date: " + date)
            self.PredictMemo.Lines.Add("Min Temperature: " + str(date_data["mintemp"]))
            self.PredictMemo.Lines.Add("Max Temperature: " + str(date_data["maxtemp"]))
            self.PredictMemo.Lines.Add("Avg Temperature: " + str(date_data["avgtemp"]))
            self.PredictMemo.Lines.Add("UV_Index: " + str(date_data["uv_index"]))
            self.PredictMemo.Lines.Add("")  # Add an empty line for separation

What Does the Completed Project Look Like?  

Now that everything is complete, all we need to do is open up the WeatherApp.py file and run it.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Let’s head over to the Current tab and select a city using the CityCombo box. Next, click on Get Data to retrieve the current weather information.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Now, let’s head over to the Historical tab and select a date for historical data. Next, click on the Get History button to retrieve the data.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Finally, we can even get the predicted weather for “New York City.” Head over to the Prediction tab and select the number of days for prediction. Now click on the Predict button to get the predicted data.

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Are You Ready to Create Your Own Amazing Apps?

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Congratulations! Thanks to the dynamic duo of DelphiFMX and Weatherstack, you’ve gained the skills to craft your own weather app. The app development world is within your grasp, and the possibilities are endless. Now, you’re not just forecasting the weather; you’re shaping innovative applications that can revolutionize how we engage with the world. But this is only the start. The DelphiFMX ecosystem provides a vast range of tools and resources, all at your disposal.

Ready to explore the vast app development landscape and bring your unique ideas to life? Get started now and dive into the world of app creation. 

What Are Some FAQs Related to this Post?

How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API

Do I need prior experience with Delphi to follow this tutorial?

While prior experience with Delphi could be helpful, the tutorial is designed to provide step-by-step guidance, making it accessible to both beginners and experienced developers.

Can I use Weatherstack for free, or are there subscription plans?

Weatherstack offers both free and paid subscription plans. In this tutorial, a subscription plan providing access to all endpoints is used, but you can start with the free plan, which includes access to the current weather endpoint.

Can I deploy a weather app created with DelphiFMX on multiple platforms?

Yes, one of the advantages of using DelphiFMX is its ability to create cross-platform applications. You can deploy your weather app on platforms like Windows and macOS.

Can I use the knowledge from this tutorial to create other types of apps?

Absolutely! The principles and techniques covered in this tutorial can be applied to a wide range of app development projects, not just weather apps. Delphi is a versatile tool for creating various types of applications.

Can I customize the design and features of my weather app beyond what’s covered in this tutorial? 

Yes, you can further enhance your weather app by customizing its design and adding additional features to meet your specific requirements. DelphiFMX offers flexibility for creative app development.

The post How To Create A Weather App With The Python Delphi Ecosystem and Weatherstack API first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-weather-app-with-the-python-delphi-ecosystem-and-weatherstack-api/feed/ 0 11441
How To Create A Music Player With The Python Delphi Ecosystem https://pythongui.org/how-to-create-a-music-player-with-the-python-delphi-ecosystem/ https://pythongui.org/how-to-create-a-music-player-with-the-python-delphi-ecosystem/#respond Mon, 16 Oct 2023 10:00:00 +0000 https://pythongui.org/?p=11294 Music is more than sound; it’s an emotion, a narrative, a refuge. Imagine wielding the power to design your musical universe, where every note and rhythm aligns with your desires. In this post, you will...

The post How To Create A Music Player With The Python Delphi Ecosystem first appeared on Python GUI.

]]>
Music is more than sound; it’s an emotion, a narrative, a refuge. Imagine wielding the power to design your musical universe, where every note and rhythm aligns with your desires. In this post, you will see the synergy of Python and Delphi, where we will unveil a music player that transcends expectations.

This music player app will have an option for users to create playlists as well as play, stop, and pause songs. Users can even monitor song durations and real-time timestamps. Users can easily adjust the volume and navigate through their music in 10-second intervals. Throughout this journey, we’ll introduce you to advanced Delphi components that seamlessly integrate Python’s versatility with Delphi’s strength.

How to Build a Feature-Packed Music Player With DelphiFMX? 

How To Create A Music Player With The Python Delphi Ecosystem

Let’s go over the building of a music player app in a step by step manner.

What Are the Prerequisites for this Project?

Before we dive into building our feature-packed music player with DelphiFMX, let’s ensure we have all the necessary tools and components in place.

First and foremost, make sure you have Delphi Software installed. Delphi will be our creative canvas, allowing us to craft a music player with an enticing user interface that sings with functionality.

Next up, you’ll need the Delphi4PythonExporter tool. This nifty utility acts as the bridge connecting Delphi and Python, making the integration seamless and painless.

You’ll require a text editor or an integrated development environment (IDE) that supports Python programming to code in Python. We highly recommend PyScripter, a user-friendly environment that harmoniously blends Python coding within Delphi. If you haven’t already set up these tools, consider exploring our article “Powerful Python GUI Project Setup” to help you get started on the right foot.

Finally, you will need a codec pack to playback of all your music and video files. For this, we will need the K-Lite Codec Pack, which is a free software bundle shipped with decoders needed to view any movie, video, or music file. For this tutorial, you will need to download and install the basic codec pack from their official website.

With these prerequisites in place, you’ll be all set to embark on the journey of creating a feature-packed music player that will elevate your music experience to new heights. And if you’re eager to dive right in, you can access the complete code and resources for this tutorial from our GitHub repository at the following link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Music_Player

How to Use the Delphi IDE to Create a Stunning GUI for this App?

Let’s start by launching our Delphi app and creating a new application. Search for the Create New tab on your welcome page and click on Multi-Device Application. Next, opt for the Blank Application and click on OK. For this tutorial, we’ve named our project “MusicPlayerProject.”

If you’re not well-acquainted with the different sections of the Delphi IDE, we suggest referring to our complimentary eBook bundle. This resource comprehensively covers the Delphi Python EcoSystem and all Python GUI offerings.

How To Create A Music Player With The Python Delphi Ecosystem

Now, we will start off by naming our form. Right-click on the form and select Quick Edit. Here, we will set the name of our form as MusicPlayerWindow with the caption “Music Player.” We will also rename the source file of our project from Unit1.pas to MusicPlayer.pas to help us keep track.

How To Create A Music Player With The Python Delphi Ecosystem

Next, let’s resize our form. Select your form and head over to the Object Inspector. Under the properties tab, search for the ClientWidth and ClientHeight properties and adjust the sizes accordingly.

We will add a few tabs to the form for this project. So, head over to the Palette and search for the TTabControl object. Drag and Drop this object to your form and adjust its size accordingly. Next, right-click on the TTabControl object and add two tabs to the form: Songs and Now Playing. The Songs tab will display all the songs in the app, while the Now Playing tab will serve as the main music player. We will also add a TRectangle component to the top of the form that will serve as the placeholder for the title and a button (which we will define later).

Here is what our form looks like:

How To Create A Music Player With The Python Delphi Ecosystem

Note: We will be customizing the text style of each label using the TextSettings property of the component. This will help us customize the feel of the form.

Now, let’s add a few labels to the form. Search for the TLabel component in the Palette and add it to the form. We will add a few of these components to indicate multiple things, including filename, song directory, artist, and time. We will also use them as placeholders to indicate multiple other components. Here is what our form looks like:

How To Create A Music Player With The Python Delphi Ecosystem

Next, let’s add a few buttons. Head to the Palette, search for the TButton component and add a few buttons to the form. Here, we will add a Create Playlist button, forward and backward buttons (which will change the time by 10 seconds), and Pause, Play, and Stop for the music player. Additionally, for each player button, we are going to customize their appearance by heading over to the Object Inspector and changing their style using the StyleLookup property:

How To Create A Music Player With The Python Delphi Ecosystem

This is what our form looks like so far:

How To Create A Music Player With The Python Delphi Ecosystem

Now, let’s add a few TTrackBar components. One track bar component will help adjust the volume of our music player, while the other will serve as a tracker to track the progress of our music. We will also add a TImage component that will help display the album cover of our music file. Here is what our form looks like:

How To Create A Music Player With The Python Delphi Ecosystem

Finally, we’ll add a TOpenDialog to help select files we want to play. We will also add a TTimer and a TMediaPlayer component to help us play our music files. The placement of these components does not matter as they will be invisible:

How To Create A Music Player With The Python Delphi Ecosystem

Now that our Now Playing tab is complete, head over to the Songs tab and add a TListBox component. This will serve as a placeholder for all our music files.

How To Create A Music Player With The Python Delphi Ecosystem

Now that our form is ready, the last step is to add functionality to each button. To do this, double-click on each button on the form. This will generate an OnClick method for that button and create a procedure in the .pas file, enabling us to program the button.

How To Create A Music Player With The Python Delphi Ecosystem

Due to the Delphi4PythonExporter’s lack of runtime implementation, we must include at least one comment (//) in each procedure to preserve its function when we export the form.

How To Create A Music Player With The Python Delphi Ecosystem

How to Add Functionality to this GUI?

With our forms now ready, we can begin exporting our forms. Navigate to Tools > Export To Python and click on Export Current Entire Project.

How To Create A Music Player With The Python Delphi Ecosystem

Here we will give our project the title Music Player. Now, select the directory of your choosing and click on Export.

How To Create A Music Player With The Python Delphi Ecosystem

Delphi will generate two Python and one .pyfmx file. The MusicPlayerProject.py file will be used to run the application, whereas the MusicPlayer.py file will contain the class of our form. The MusicPlayer.pyfmx contains the visual information of our form. Below are the contents of each Python file.

MusicPlayerProject.py:

from delphifmx import *
from MusicPlayer import MusicPlayerWindow

def main():
    Application.Initialize()
    Application.Title = 'Music Player'
    Application.MainForm = MusicPlayerWindow(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

MusicPlayer.py:

import os
from delphifmx import *

class MusicPlayerWindow(Form):

    def __init__(self, owner):
        self.top_rectangle = None
        self.top_heading = None
        self.create_playlist = None
        self.tab_ctrl = None
        self.songs_tab = None
        self.audio_list_box = None
        self.now_playing_tab = None
        self.audio_embedded_image = None
        self.audio_track_bar = None
        self.play_btn = None
        self.pause_btn = None
        self.stop_btn = None
        self.fwd_btn = None
        self.bwd_btn = None
        self.volume_track_bar = None
        self.vol_label = None
        self.location_label = None
        self.current_time_label = None
        self.song_name_label = None
        self.artist_label = None
        self.duration_label = None
        self.open_audio_dialog = None
        self.media_player = None
        self.timer = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MusicPlayer.pyfmx"))

    def create_playlistClick(self, Sender):
        pass

    def audio_list_boxChange(self, Sender):
        pass

    def play_btnClick(self, Sender):
        pass

    def pause_btnClick(self, Sender):
        pass

    def stop_btnClick(self, Sender):
        pass

    def fwd_btnClick(self, Sender):
        pass

    def bwd_btnClick(self, Sender):
        pass

    def volumeChange(self, Sender):
        pass

    def update_current_time(self, Sender):
        pass

The only thing we need to do now is start adding functionality to our forms. Start by opening up MusicPlayer.py in the text editor of your choice and importing the TinyTag library:

# Additional Imports
from tinytag import TinyTag

Next, head over to the __init__ function and start by adding a custom style for the form. You’ll first need to obtain the free eBook bundle, which includes various styles. Download the eBook and extract the FMX styles ZIP file to your preferred directory. Then select the style you wish to use; in this instance, we’ll opt for transparent.style from the bundle. In addition, we will also set the default value of the volume bar to 100. Our __init__ function looks like:

class MusicPlayerWindow(Form):

    def __init__(self, owner):
        # Initialize all GUI elements
        self.top_rectangle = None
        self.top_heading = None
        self.create_playlist = None
        self.tab_ctrl = None
        self.songs_tab = None
        self.audio_list_box = None
        self.now_playing_tab = None
        self.audio_embedded_image = None
        self.audio_track_bar = None
        self.play_btn = None
        self.pause_btn = None
        self.open_audio_dialog = None
        self.media_player = None
        self.timer = None
        self.stop_btn = None
        self.fwd_btn = None
        self.bwd_btn = None
        self.nxt_btn = None
        self.volume_track_bar = None
        self.vol_label = None
        self.location_label = None
        self.current_time_label = None
        self.song_name_label = None
        self.artist_label = None
        self.duration_label = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MusicPlayer.pyfmx"))

        # Set up the style manager and apply a custom style
        self.__sm = StyleManager()
        self.__sm.SetStyleFromFile(os.path.join(os.getcwd(), "StylesTransparent.style"))

        # Set the initial position of TrackBar to the middle (50%)
        self.volume_track_bar.Value = 100

Now, let’s program our Play, Pause, and Stop buttons. Head over to the play_btnClick function and start by turning the button off after it is pressed. Next, we will enable the Stop and Pause buttons, while calling the media player to play the music. Here is what our function looks like:

def play_btnClick(self, Sender):
        # Handle play button click
        self.play_btn.Enabled = False
        self.pause_btn.Enabled = True
        self.stop_btn.Enabled = True
        self.media_player.Play()

Similarly, we can add functionalities for our Stop and Pause buttons. Here is what the functions look like:

def pause_btnClick(self, Sender):
        # Handle pause button click
        self.play_btn.Enabled = True
        self.pause_btn.Enabled = False
        self.media_player.Stop()

    def stop_btnClick(self, Sender):
        # Handle stop button click
        self.stop_btn.Enabled = False
        self.pause_btn.Enabled = False
        self.play_btn.Enabled = True
        self.media_player.FileName = self.open_audio_dialog.FileName

Next, let’s add some functionality to the forward and backward buttons. Navigate to the fwd_btnClick function and start by getting the CurrentTime of the music:

def fwd_btnClick(self, Sender):
        # Handle forward button click
        current_time_seconds = self.media_player.CurrentTime / 10000000

Now add 10 seconds to the current time and then check if the duration is less than the duration of the song. If this condition is satisfied, we set the current time to the new time. Here is what the function looks like:

def fwd_btnClick(self, Sender):
        # Handle forward button click
        current_time_seconds = self.media_player.CurrentTime / 10000000
        new_time_seconds = current_time_seconds + 10
   
        if new_time_seconds < self.tag.duration:
            self.media_player.CurrentTime = round(new_time_seconds * 10000000)

Similarly, we can program the bwd_btnClick function but instead check if the new time is less than 0. Here is what the function looks like:

def bwd_btnClick(self, Sender):
        # Handle backward button click
        current_time_seconds = self.media_player.CurrentTime / 10000000
        new_time_seconds = current_time_seconds - 10
   
        if new_time_seconds >= 0:
            self.media_player.CurrentTime = round(new_time_seconds * 10000000)

Next, lets add some functionality to the volume track bar. Head over to the volumeChange function and start by getting the current volume stated in the bar. Next, assign the new volume value to the media player. Here is our final volumeChange function:

def volumeChange(self, Sender):
        # Handle volume control change
        volume = self.volume_track_bar.Value / 100.0
        self.media_player.Volume = volume

Now, let’s head over to the update_current_time function and use it to display the current time using the media_player. We will also display the current time in our current_time_label:

def update_current_time(self, Sender):
        # Update the current playback time
        current_time_seconds = self.media_player.CurrentTime / 10000000

        self.audio_track_bar.Value = current_time_seconds

        # Format the current time as MM:SS
        minutes = int(current_time_seconds // 60)
        seconds = int(current_time_seconds % 60)
        self.current_time_label.Text = f"{minutes:02}:{seconds:02}"

Next, we will move on to the create_playlistClick function. We will use this function to populate our playlist in the Songs tab. So, we will start by opening up the dialog box for file selection. Next, if the user selects the song, we will append it to the ListBoxItem and add it to our playlist. Here is what the function looks like:

def create_playlistClick(self, Sender):
        # Open a file dialog to select audio files and populate the playlist
        if self.open_audio_dialog.Execute():
            self.audio_list_box.Clear()
            mp3_files_list = self.open_audio_dialog.Files.ToList()
            self.listbox_song_paths = []
            self.listbox_items = []
            for mp3_file_path in mp3_files_list:
                self.listbox_song_paths.append(mp3_file_path)
                mp3_file_name = os.path.splitext(os.path.basename(mp3_file_path))[0]
                lb_item_audio_name = ListBoxItem(self.audio_list_box)
                lb_item_audio_name.SetProps(Parent=self.audio_list_box,
                                            Height=40,
                                            Text=mp3_file_name)
                self.listbox_items.append(lb_item_audio_name)

We are finally ready to add the main code to our Media player. Head over to the audio_list_boxChange function and start by retrieving the item selected in the list box:

def audio_list_boxChange(self, Sender):
        # Handle selection of an audio item in the list box
        selected_lb_item = self.audio_list_box.Selected

Next, change the tab to the Now Playing tab and use TinyTag to retrieve information about the selected song:

self.tab_ctrl.TabIndex = 1
        mp3_file_path = self.listbox_song_paths[self.listbox_items.index(selected_lb_item)]
       
        # Use TinyTag to retrieve audio file information
        self.tag = TinyTag.get(mp3_file_path, image=True)

        mins = self.tag.duration // 60
        sec = self.tag.duration % 60
        self.duration_label.Text = f"{int(mins)}:{int(sec)}"

Next, set the various labels we have with information about the song and update the embedded image if there is one available:

# Set various labels and update the embedded image if available
        self.audio_track_bar.Max = self.tag.duration
        self.artist_label.Text = "Artist: {}".format(self.tag.artist)
        self.location_label.Text = "Location: {}".format(mp3_file_path)
        self.song_name_label.Text = "Song Name: {}".format(selected_lb_item.Text)

        image_data = self.tag.get_image()
        if image_data is not None:
            bs = BytesStream(image_data)
            self.audio_embedded_image.Bitmap.LoadFromStream(bs)
        else:
            self.audio_embedded_image.Bitmap = None

Finally, load and play the selected audio file. Here is what our function looks like:

def audio_list_boxChange(self, Sender):
        # Handle selection of an audio item in the list box
        selected_lb_item = self.audio_list_box.Selected
        self.tab_ctrl.TabIndex = 1
        mp3_file_path = self.listbox_song_paths[self.listbox_items.index(selected_lb_item)]
       
        # Use TinyTag to retrieve audio file information
        self.tag = TinyTag.get(mp3_file_path, image=True)

        mins = self.tag.duration // 60
        sec = self.tag.duration % 60
        self.duration_label.Text = f"{int(mins)}:{int(sec)}"

        # Set various labels and update the embedded image if available
        self.audio_track_bar.Max = self.tag.duration
        self.artist_label.Text = "Artist: {}".format(self.tag.artist)
        self.location_label.Text = "Location: {}".format(mp3_file_path)
        self.song_name_label.Text = "Song Name: {}".format(selected_lb_item.Text)

        image_data = self.tag.get_image()
        if image_data is not None:
            bs = BytesStream(image_data)
            self.audio_embedded_image.Bitmap.LoadFromStream(bs)
        else:
            self.audio_embedded_image.Bitmap = None

        # Load and play the selected audio file
        self.media_player.FileName = mp3_file_path
        self.media_player.Play()

        # Set up a timer to update the current playback time
        self.timer.Interval = 1000  # Set the interval to 1000 milliseconds (1 second)
        self.timer.Enabled = True

        # Enable playback control buttons
        self.pause_btn.Enabled = True
        self.stop_btn.Enabled = True

Here is what our final MusicPlayer.py file looks like:

import os
from delphifmx import *
from tinytag import TinyTag

class MusicPlayerWindow(Form):

    def __init__(self, owner):
        # Initialize all GUI elements
        self.top_rectangle = None
        self.top_heading = None
        self.create_playlist = None
        self.tab_ctrl = None
        self.songs_tab = None
        self.audio_list_box = None
        self.now_playing_tab = None
        self.audio_embedded_image = None
        self.audio_track_bar = None
        self.play_btn = None
        self.pause_btn = None
        self.open_audio_dialog = None
        self.media_player = None
        self.timer = None
        self.stop_btn = None
        self.fwd_btn = None
        self.bwd_btn = None
        self.nxt_btn = None
        self.volume_track_bar = None
        self.vol_label = None
        self.location_label = None
        self.current_time_label = None
        self.song_name_label = None
        self.artist_label = None
        self.duration_label = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MusicPlayer.pyfmx"))

        # Set up the style manager and apply a custom style
        self.__sm = StyleManager()
        self.__sm.SetStyleFromFile(os.path.join(os.getcwd(), "StylesTransparent.style"))

        # Set the initial position of TrackBar to the middle (50%)
        self.volume_track_bar.Value = 100
   
        self.tag = None

    def create_playlistClick(self, Sender):
        # Open a file dialog to select audio files and populate the playlist
        if self.open_audio_dialog.Execute():
            self.audio_list_box.Clear()
            mp3_files_list = self.open_audio_dialog.Files.ToList()
            self.listbox_song_paths = []
            self.listbox_items = []
            for mp3_file_path in mp3_files_list:
                self.listbox_song_paths.append(mp3_file_path)
                mp3_file_name = os.path.splitext(os.path.basename(mp3_file_path))[0]
                lb_item_audio_name = ListBoxItem(self.audio_list_box)
                lb_item_audio_name.SetProps(Parent=self.audio_list_box,
                                            Height=40,
                                            Text=mp3_file_name)
                self.listbox_items.append(lb_item_audio_name)

    def audio_list_boxChange(self, Sender):
        # Handle selection of an audio item in the list box
        selected_lb_item = self.audio_list_box.Selected
        self.tab_ctrl.TabIndex = 1
        mp3_file_path = self.listbox_song_paths[self.listbox_items.index(selected_lb_item)]
       
        # Use TinyTag to retrieve audio file information
        self.tag = TinyTag.get(mp3_file_path, image=True)

        mins = self.tag.duration // 60
        sec = self.tag.duration % 60
        self.duration_label.Text = f"{int(mins)}:{int(sec)}"

        # Set various labels and update the embedded image if available
        self.audio_track_bar.Max = self.tag.duration
        self.artist_label.Text = "Artist: {}".format(self.tag.artist)
        self.location_label.Text = "Location: {}".format(mp3_file_path)
        self.song_name_label.Text = "Song Name: {}".format(selected_lb_item.Text)

        image_data = self.tag.get_image()
        if image_data is not None:
            bs = BytesStream(image_data)
            self.audio_embedded_image.Bitmap.LoadFromStream(bs)
        else:
            self.audio_embedded_image.Bitmap = None

        # Load and play the selected audio file
        self.media_player.FileName = mp3_file_path
        self.media_player.Play()

        # Set up a timer to update the current playback time
        self.timer.Interval = 1000  # Set the interval to 1000 milliseconds (1 second)
        self.timer.Enabled = True

        # Enable playback control buttons
        self.pause_btn.Enabled = True
        self.stop_btn.Enabled = True

    def update_current_time(self, Sender):
        # Update the current playback time
        current_time_seconds = self.media_player.CurrentTime / 10000000

        self.audio_track_bar.Value = current_time_seconds

        # Format the current time as MM:SS
        minutes = int(current_time_seconds // 60)
        seconds = int(current_time_seconds % 60)
        self.current_time_label.Text = f"{minutes:02}:{seconds:02}"

    def play_btnClick(self, Sender):
        # Handle play button click
        self.play_btn.Enabled = False
        self.pause_btn.Enabled = True
        self.stop_btn.Enabled = True
        self.media_player.Play()

    def pause_btnClick(self, Sender):
        # Handle pause button click
        self.play_btn.Enabled = True
        self.pause_btn.Enabled = False
        self.media_player.Stop()

    def stop_btnClick(self, Sender):
        # Handle stop button click
        self.stop_btn.Enabled = False
        self.pause_btn.Enabled = False
        self.play_btn.Enabled = True
        self.media_player.FileName = self.open_audio_dialog.FileName

    def fwd_btnClick(self, Sender):
        # Handle forward button click
        current_time_seconds = self.media_player.CurrentTime / 10000000
        new_time_seconds = current_time_seconds + 10
   
        if new_time_seconds < self.tag.duration:
            self.media_player.CurrentTime = round(new_time_seconds * 10000000)

    def bwd_btnClick(self, Sender):
        # Handle backward button click
        current_time_seconds = self.media_player.CurrentTime / 10000000
        new_time_seconds = current_time_seconds - 10
   
        if new_time_seconds >= 0:
            self.media_player.CurrentTime = round(new_time_seconds * 10000000)

    def volumeChange(self, Sender):
        # Handle volume control change
        volume = self.volume_track_bar.Value / 100.0
        self.media_player.Volume = volume

What Are the Final Results?

Now that everything is complete, it’s time to test out our app. Open up MusicPlayerProject.py and run the file.

How To Create A Music Player With The Python Delphi Ecosystem

Next, click the Create Playlist button and select the files you want to play. Now navigate to the Songs tab to see your playlist:

How To Create A Music Player With The Python Delphi Ecosystem

Finally, double-click on a song to start playing:

How To Create A Music Player With The Python Delphi Ecosystem

What Have You Learned in this Article?

How To Create A Music Player With The Python Delphi Ecosystem

Conclusively, in this tutorial, we’ve transformed a basic music player into a versatile tool. You’ve learned to craft playlists effortlessly, fine-tune playback, and enhance your music experience with song duration and timestamps.

But this is just the beginning. Delphi opens doors to endless possibilities. Whether you’re a novice or an experienced developer, it’s time to harness the power of Delphi. Elevate your software development skills, create exceptional applications, and leave your digital mark.

Delphi offers boundless opportunities. So, why wait? Dive into the world of Delphi today and turn your ideas into reality. Your next innovation is just a step away.

What Are Some Relevant FAQs?

How To Create A Music Player With The Python Delphi Ecosystem

What is DelphiFMX, and why should I use it for building a music player?

DelphiFMX is a framework for creating cross-platform applications with Delphi. It provides a powerful and user-friendly way to build applications with rich user interfaces. Using it for a music player allows you to create a visually appealing and feature-packed player easily.

Can I use other programming languages besides Python with DelphiFMX?

DelphiFMX primarily supports the Delphi programming language, but you can use external libraries like the Python4Delphi bridge to incorporate Python into your Delphi applications, as demonstrated in this tutorial.

Are there any licensing requirements for using Delphi and Python together?

Delphi and Python can be used together without any additional licensing requirements. However, make sure to review the licenses of any third-party libraries or components you use in your project.

Can I customize the appearance and behavior of Delphi components to match the design of my music player?

Yes, Delphi components are highly customizable. You can adjust properties such as colors, fonts, sizes, and styles to achieve the desired look and feel for your music player’s user interface.

What are some commonly used Delphi components for building a music player?

For a music player, you might use components like TMediaPlayer, TListBox for playlists, TButton for playback controls, TProgressBar for tracking song progress, and TTrackBar for volume control, among others.

The post How To Create A Music Player With The Python Delphi Ecosystem first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-music-player-with-the-python-delphi-ecosystem/feed/ 0 11294
Unlock the Power of Python for Deep Learning with Transformer Architecture – The Engine Behind ChatGPT https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-transformer-architecture-the-engine-behind-chatgpt/ https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-transformer-architecture-the-engine-behind-chatgpt/#respond Mon, 09 Oct 2023 10:00:00 +0000 https://pythongui.org/?p=11228 To address intricate problems, extensive amounts of data and substantial computational capabilities are essential for the functioning of deep learning algorithms. These algorithms are versatile in handling various types of data. This article will delve into...

The post Unlock the Power of Python for Deep Learning with Transformer Architecture – The Engine Behind ChatGPT first appeared on Python GUI.

]]>
To address intricate problems, extensive amounts of data and substantial computational capabilities are essential for the functioning of deep learning algorithms. These algorithms are versatile in handling various types of data. This article will delve into a comprehensive exploration of the Transformer Architecture, a prominent member of the deep learning domain and the driving force behind ChatGPT, which is presently ubiquitous and widely discussed across different platforms.

Please note: As GPT-3 and higher versions are not available for public access at the time of writing, the demonstration showcased in this article employs GPT-2.

Before we begin, let’s see the remarkable ability of ChatGPT to describe itself:

chatgpt demo transformer architecture

It can even praise itself very highly :). Read reference [2] and [3], if you want to see how powerful ChatGPT is in assisting you to understand a research paper in the deep learning field.

What is Deep Learning?

Deep learning is a subfield of machine learning that solves complex problems using artificial neural networks. These neural networks are made up of interconnected nodes arranged in multiple layers that extract features from input data. Large datasets are used to train these models, allowing them to detect patterns and correlations that humans would find difficult or impossible to detect.

Deep learning has had a significant impact on artificial intelligence. It has facilitated the development of intelligent systems capable of learning, adapting, and making decisions on their own. Deep learning has enabled remarkable progress in a variety of fields, including image and speech recognition, natural language processing, machine translation, large-language models; chatbots; & content generators (as would be reviewed in this article), image generations, autonomous driving, and many others.

example of image generated by ai using stable diffusion xl
Example of AI generated image using Stable Diffusion XL model that I generate using the following prompt: “Illustration of deep learning and AI community”.

Why Python for Deep Learning, Machine Learning, and Artificial Intelligence?

Python has gained widespread popularity as a programming language due to its versatility and ease of use in diverse domains of computer science, especially in the field of deep learning, machine learning, and AI. 

We’ve reviewed several times about why Python is great for Deep Learning, Machine Learning, and Artificial Intelligence (also all the requirements), in the following articles:

What is GPT?

GPT stands for “Generative Pre-trained Transformer,” and it is a type of artificial intelligence language model developed by OpenAI. The GPT models are built on the Transformer architecture, which is a deep learning model architecture specifically designed for natural language processing tasks.

gpt transformer architecture example on language understanding
An example of GPT architecture used for language understanding. Image source: Reference [5].

The key features of GPT are:

  1. Generative: GPT is capable of generating human-like text based on the input it receives. It can produce coherent and contextually relevant responses, making it useful for a variety of natural language generation tasks.
  2. Pre-trained: GPT models are initially trained on large-scale datasets that contain diverse text from the internet, books, articles, and other sources. This pre-training phase helps the model learn grammar, syntax, semantics, and factual knowledge from the vast amount of data it processes.
  3. Transformer architecture: The Transformer architecture is a neural network architecture that allows the model to process input text in parallel, making it more efficient and scalable compared to earlier sequential models. The self-attention mechanism in Transformers enables the model to weigh the importance of different words in the input context, leading to better contextual understanding.
  4. Transfer Learning: GPT leverages the concept of transfer learning. After pre-training on a large corpus of text, the model can be further fine-tuned on specific tasks or datasets to adapt its capabilities to more targeted use cases.

GPT has seen several iterations, with each version being an improvement over its predecessors in terms of size, performance, and language understanding capabilities. These models have found applications in various domains, including chatbots, language translation, text summarization, content generation, and more, due to their ability to understand and generate human-like text.

What is GPT-2?

GPT-2 is a large transformer-based language model with 1.5 billion parameters, trained on a dataset of 8 million web pages. GPT-2 is trained with a simple objective: predict the next word, given all of the previous words within some text. The diversity of the dataset causes this simple goal to contain naturally occurring demonstrations of many tasks across diverse domains. GPT-2 is a direct scale-up of GPT, with more than 10X the parameters and trained on more than 10X the amount of data.

GPT-2 outperforms other language models trained on specific domains (like Wikipedia, news, or books) without needing to use these domain-specific training datasets. On language tasks like question answering, reading comprehension, summarization, and translation, GPT-2 begins to learn these tasks from the raw text, using no task-specific training data.

What is Transformer architecture?

The Transformer architecture is a deep learning model architecture specifically designed for natural language processing (NLP) tasks. It was introduced in the paper “Attention is All You Need” by Vaswani et al. in 2017 (see Reference [8]) and has since become a fundamental building block for many state-of-the-art NLP models, including GPT (Generative Pre-trained Transformer) and BERT (Bidirectional Encoder Representations from Transformers).

The key innovation of the Transformer architecture is the concept of self-attention. Traditional sequence-to-sequence models, like RNNs (Recurrent Neural Networks), process input sequentially, which can lead to inefficiencies and limitations in capturing long-range dependencies. In contrast, the Transformer allows for parallel processing of input sequences, making it highly scalable and efficient.

transformer architecture diagram
The Transformer model architecture. Image source: Reference [8].

What are the main components of Transformer architecture?

1. Encoder-Decoder Structure

The Transformer architecture consists of an encoder and a decoder. In NLP tasks like machine translation, the encoder processes the input sequence, while the decoder generates the output sequence.

2. Self-Attention Mechanism

Self-attention allows the model to weigh the importance of different words in the input sequence concerning each other. It computes attention scores between all pairs of words in the sequence, and the words with higher attention scores have a stronger influence on the representation of each word. This enables the model to capture dependencies between words regardless of their distance in the sequence.

3. Multi-Head Attention

The self-attention mechanism is extended with multiple attention heads. Each head learns a different representation of the input sequence, allowing the model to capture different types of relationships and dependencies.

4. Feed-Forward Neural Networks

After the self-attention layers, the model typically employs feed-forward neural networks to process the attended representations further.

5. Positional Encoding

Since the Transformer processes words in parallel, it lacks the inherent order information found in sequential models. To address this, positional encoding is added to the input embeddings, providing the model with information about the word’s position in the sequence.

transformer architecture outperform others
Transformer architecture successfully outperforms other more classic models. Image source: Reference [7]

The Transformer architecture has shown remarkable performance improvements in various NLP tasks, and its ability to capture long-range dependencies and context has been instrumental in the success of modern language models. Its widespread adoption has transformed the NLP landscape, leading to the development of more powerful and efficient AI language models.

What are the requirements for running the GPT-2?

To perform this experiment, I use the following hardware, software, and environment setup:

Hardware

Regular laptop (I am not using any additional GPU). 

Processor: Intel(R) Core(TM) i5-8th Gen

Memory: 12Gb of RAM

Graphic: Intel(R) UHD Graphics 620

OS: Windows 10

Software

Please be very careful in following each step of installations, to avoid any complex errors!

Create new Python environment using conda

This step is very necessary to make you stay away from any problems in the future.

The following is the command to create new Python environment named gpt2_4D:

conda create --name gpt2_4D
create environment for transformer architecture

Activate the environment using this command:

conda activate gpt2_4D
activate or deactivate environment for transformer architecture

Python version: Python 3.6. 

Since GPT-2 needs TensorFlow 1.12 that is compatible only with Python 3.6., I even need to downgrade my Python version.

Use the following command to install specific Python version:

conda install python=3.6
install python 3.6 for transformer architecture

Setup for PyScripter IDE, so it can finds your recently installed Python 3.6. distribution in Windows

On PyScripter IDE, click the following menu, to load additional Python versions, in our case Python 3.6 (it even can successfully load Python that is installed in virtual environments):

Run -> Python Versions -> Setup Python Versions -> Click the + Button -> Add the C:/Users/YOUR_USERNAME/anaconda3/envs/gpt2_4D environment directory. 

If successfully loaded, it will show up like the following screenshots:

load python 3.6. env to pyscripter for transformer architecture

Python 3.6 and all the environment for running the GPT-2 is loaded successfully:

successfully load python 3.6. env to pyscripter for transformer architecture

Install TensorFlow v1.14 as already mentioned before

Use the following command to install a specific version of TensorFlow (v1.14):

pip install tensorflow==1.14.0
install tensorflow 1.14.0 for transformer architecture

If the TensorFlow version 1.14.0 not work well with you, try the following versions:

conda install -c issxia tensorflow=1.12
conda install -c issxia tensorflow=1.13.1
install tensorflow 1.12.0 for transformer architecture

Other library requirements

The following command is to install all the required library individually:

pip install fire>=0.1.3
pip install regex==2017.4.5
pip install requests==2.21.0
pip install tqdm==4.31.1
pip install toposort==1.5

Or, simply run this command, and you will install all of the requirements seamlessly:

pip install -r requirements.txt
install requirements for transformer architecture

Download models

Use the following command to install the 124M model (don’t forget to keep yourself stay on the gpt-2 folder, or if not, go to the gpt-2 folder using cd gpt-2):

python download_model.py 124M
download model 124m for transformer architecture

Or, if you prefer a bigger model, use the following command to install the 345M (but, as a consequence, it would consume very large memory, or even can’t run at all, on the regular laptop without an additional GPU):

python download_model.py 345M

Screenshots:

download model 345m for transformer architecture

How to test if the GPT-2 is already installed and working correctly?

Test it by running generate_unconditional_samples.py added with temperature parameter

Run the generate_unconditional_samples.py file using the following command:

python src/generate_unconditional_samples.py --temperature=2.0

If you installed everything correctly, you will get the following output:

test installation gpt-2 for transformer architecture

For the sake of curiosity, I let the code run for hours, and here is the output of SAMPLE 100:

test installation gpt-2 for transformer architecture

Test it by generate_unconditional_samples.py samples

Next, you can test the installation by running the generate_unconditional_samples.py code using the following command:

python src/generate_unconditional_samples.py --model_name=124M
test installation gpt-2 for transformer architecture

Again, for the sake of curiosity, I let the code run for hours, and here is the output of SAMPLE 100:

test installation gpt-2 for transformer architecture

Test it to perform interactive conversations on cmd

To do this, you need to run interactive_conditional_samples.py using the following command (if you use the lowest spec model (124M)):

And I used the following prompts:

  • First prompt: “What is Python language?
test installation gpt-2 for transformer architecture
  • Second prompt: “What is Delphi programming language?
test installation gpt-2 for transformer architecture
  • Third prompt: “How to cook delicious eggs?
test installation gpt-2 for transformer architecture
  • For the fourth prompt, I test it using the same example as the one provided by the official article by OpenAI (see Reference [6]).“Please continue the following paragraph: "In a shocking finding, scientist discovered a herd of unicorns living in a remote, previously unexplored valley, in the Andes Mountains. Even more surprising to the researchers was the fact that the unicorns spoke perfect English.
test installation gpt-2 for transformer architecture

How’s the results? Convincing enough to made-up a sci-fi or fairy tale stories, right (or even worse, generate fake news and hoaxes, as concerned and worried by the creators of GPT products)? 🙂

It is stated by OpenAI that GPT-2 generates synthetic text samples in response to the model being primed with an arbitrary input; the model is chameleon-like in that it adapts to the style and content of the conditioning text, allowing the user to generate realistic and coherent continuations about a topic of their choice, as demonstrated by the sample above.

Why not use bigger models?

“Why not use bigger models?”. You might ask.

For example, to use bigger model (in this example, 345M) use the following command:

python src/interactive_conditional_samples.py --model_name=345M

The answer is simple, it would exceed the allocated memory of a regular laptop.

test installation gpt-2 for transformer architecture

And if you still insist on using the model to answer your prompts, you might get less satisfying answers, compared to the answers provided by the lowest spec model (124M).

Here are the answers on the same questions:

test installation gpt-2 for transformer architecture
test installation gpt-2 for transformer architecture
test installation gpt-2 for transformer architecture
test installation gpt-2 for transformer architecture

How to retrain GPT-2 to generate custom text content?

Retrain GPT-2 to built Progressive Metal lyrics generator

In this section, we will retrain GPT-2 to generate any text that suits our purposes. We will explore all the required steps to retrain GPT-2 using any custom text, on Windows.

We can use any kind of text data, as long as they are in English. For example:

  1. Song lyrics
  2. Poems
  3. Short stories, light novels, novels
  4. Questions and answers
  5. Synopsis or abstract
  6. News, letters, articles, or papers

In this article, I retrained the GPT-2 with Progressive Metal lyrics, out of curiosity. I chose Progressive Metal genre to retrain GPT-2, as this genre has very specific characteristics, such as powerful, deep, dark, and more intricate and complex lyrics, compared to other genres (even compared to other Metal subgenres). The lyrics might explore concept albums or thematic lyrics that explore philosophical, spiritual, existential themes, exploring unusual sides of relationships and humanity, etc.

So, I think it must be fun to see how the machine can handle such complicated things. 🙂

Download required files

The required repository for this training is a clone and fine-tuned version of the original GPT-2 repository provided by @nshepperd. Go to the following Github link [4] and click on the “Clone or download” button.

Download 124M model

The next thing to do is to download the base model like we’ve done in the previous sections. But, this time, we downloaded the model for the GPT-2 cloned version.

First, don’t forget to navigate to the gpt-2-finetuning directory, and run the following command:

python download_model.py 124M

Preparing custom text dataset

For the experiment performed in this article, I am using collections of Progressive Metal lyrics as training data. I collected all studio album lyrics ever created by four Progressive Metal legends: Such as Dream Theater, Opeth, Porcupine Tree, and TOOL, which achieve 20,000+ lines of text file, that I save as lyrics.txt, as training data.  

I built the training data manually via copy and paste method from the following website: darklyrics.com and azlyrics.com. Once you have completed your training data, move the file to the src directory.

Encode the data

First, don’t forget to navigate to the gpt-2-finetuning directory, and run the following command:

python encode.py lyrics.txt lyrics.npz

If you run it successfully, you will get the following output:

encode custom dataset for transformer architecture

Train the data

Change the directory to gpt-2-finetuningsrc, and then, use the following command to train model using the new dataset:

python train.py --dataset lyrics.npz --batch_size 2 --learning_rate 0.0001

If everything is working correctly, the training should start and you should have the following output after a while:

load and train custom dataset for transformer architecture

From the screenshot above, we can interpret the output [1 | 45.25] loss=3.92 avg=3.92 as follow:

  1. 1: Refers to the number of training steps. Think of it as a counter that will increase by 1 after each run.
  2. 45.25: Time elapsed since the start of training in seconds. You can use the first step as reference to determine how long it takes to run one step.
  3. loss and avg: Both of them refer to the cross-entropy (log loss) and the average loss. You can use this to determine the performance of your model. In theory, as training steps increase, the loss should decrease until it converges at a certain value. The lower, the better.

How to stop the training?

You can stop the training by using Ctrl+C.

ctrl+c to stop the training of transformer architecture

By default, the model will be saved once every 1000 steps and a sample will be generated once every 100 steps.

The following are the automatically generated samples after the first 100 steps of training:

train and generate sample step100 for transformer architecture

And the following are the checkpoint files inside the run1 folder:

run1 folder for transformer architecture

The following is the complete directory to the checkpoints:

/../gpt-2-finetuning/src/checkpoint/run1

The outputs that related with our last step of training:

  1. model-431.data-00000-of-00001
  2. model-431.index
  3. model-431.meta

How to resume training from the last checkpoint?

You can simply use the following code to resume the training:

python train.py --dataset lyric.npz

Or the following command:

python train.py --dataset lyrics.npz --batch_size 2 --learning_rate 0.0001

That’s the same as before.

The following is the log loss and average loss achieved after 1000 steps of training:

loss and avg step after 1000 steps of training the transformer architecture

Let’s see what the model can do, after such a long training.

Generate samples

Create a folder for the model

In the src/models folder, you should have just one folder called 124M (if you only installed this model). 

Create another folder to store your model alongside with the original model. I made a new folder called lyric. Now, I have two folders in src/models, one is called 124M and the other is called lyric.

Go to src/checkpoint/run1 folder, and copy the following files:

  1. checkpoint
  2. model-xxxx.data-00000-of-00001
  3. model-xxxx.index
  4. model-xxxx.meta

xxxx refers to the step number. Since I have trained for 1394 steps, I have model-1394.index.

Paste them into the newly created folder (in my case, the folder is called lyric). Next, go to the 124M folder and copy the following files:

  1. encoder.json
  2. hparams.json
  3. vocab.bpe

Paste them into the lyric folder. Double check that you should have 7 files in it. With this, we are ready to generate samples.

output lyric folder after 1394 steps  of training for transformer architecture

In general, there are two ways to generate samples: By generating unconditional vs interactive conditional samples.

Generate unconditional sample

Unconditional sample refers to randomly generated samples without taking into account any user input. Think of it as a random sample. 

Make sure you are in the src directory and simply use the following code to generate samples.

python generate_unconditional_samples.py --model_name lyric

Beware of the output! Some of it may be quite humorous,  some others may use strong and profanity languages (for unknown reason, but it’s likely based on the some lyrics written by TOOL band), while some of it seems good enough in producing lyrics that are a little bit similar with progressive metal style that used in training data.

The quality of the lyrics might get better if we add the training data, or stop the training at the right time or right training step (to avoid overfitting or underfitting).

You can also get better results by removing the bad words using profanity filter API, as follow:

output generate samples for transformer architecture

For the sake of curiosity and completeness, I save all the 100 output samples into different files, and upload them to the following directory /samples/generate_unconditional_samples.py--model_name_lyric_outputs inside the following code repository.

Generate unconditional sample using parameter tuning

The most important parameters we need to know before tuning them are top_k and temperature.

top_k: Integer value controlling diversity. 1 means only 1 word is considered for each step (token), resulting in deterministic completions, while 40 means 40 words are considered at each step. 0 (default) is a special setting that means no restrictions. 40 generally is a good value.

temperature: Float value controlling randomness in boltzmann distribution. Lower temperature results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive. Higher temperature results in more random completions. Default value is 1.

For example, to generate unconditional sample using 0.8 temperature and 40 top_k, type the following command:

python generate_unconditional_samples.py --temperature 0.8 --top_k 40 --model_name lyric

For the sake of curiosity and completeness, I save all the 100 sample outputs using the command above, and upload them to the following directory /samples/generate_unconditional_samples.py--temperature0.8top_k40 inside the following code repository.

Generate interactive conditional sample

Interactive conditional sample refers to generating samples based on user input. In other words, you input some text, and GPT-2 will do its best to fill in the rest.

Type the following command to generate interactive conditional samples:

python interactive_conditional_samples.py --temperature 0.8 --top_k 40 --model_name lyric

After running the command above, type your desired prompt, for example:

Write me a lyrics in the style of Dream Theater band

And here is the screenshot of the excerpt of the output:

output generate samples for transformer architecture
Generate interactive conditional sample on PyScripter IDE

Before running the interactive_conditional_sample.py on PyScripter IDE, you need to change the model_name parameter on the interact_model function from 124M to lyric (see the line 12 on the interactive_conditional_sample.py file).

model_name='lyric'

And then, you can run the code normally, and type your prompt. For example:

Please continue the following lyrics: "Somewhere like a scene from a memory"
output generate samples pyscripter for transformer architecture
output generate lyrics samples pyscripter for transformer architecture

Conclusion

The Transformer architecture has revolutionized the field of natural language processing and machine learning as a whole. Its self-attention mechanism and parallel processing capabilities have led to remarkable breakthroughs in tasks like machine translation, sentiment analysis, and text generation (as we demonstrated in this article).

This article has highlighted and demonstrated the potential use of deep learning, specifically within the context of the Transformer architecture in the domain of music or arts, specifically in producing lyrics in certain musical genre.

I hope this article was successful in giving you a basic understanding and workflow of how to retrain GPT-2 according to your project goals.

Check out the full repository here:

github.com/Embarcadero/DL_Python04_Transformer


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL, which makes it simple to create Windows GUIs with Python


References & further readings

[1] Foong, Ng Wai. (2019).

Beginner’s Guide to Retrain GPT-2 (117M) to Generate Custom Text Content. AI2 Labs, Medium. medium.com/ai-innovation/beginners-guide-to-retrain-gpt-2-117m-to-generate-custom-text-content-8bb5363d8b7f

[2] Hakim, M. A. (2023).

How to read Machine Learning/Deep Learning papers for a busy (or lazy) man. Paper-001: “Hinton et al., 2015”. hkaLabs AI blog. hkalabs.com/blog/how-to-read-deep-learning-papers-for-a-busy-or-lazy-man-paper-001

[3] Hakim, M. A. (2023).

How to bypass the ChatGPT information cutoff? A busy (or lazy) man guide to read more recent ML/DL papers. Paper-001: “Rombach et al., 2022”. hkaLabs AI blog. hkalabs.com/blog/how-to-read-deep-learning-papers-using-bing-chat-ai-001

[4] nshepherd. (2021).

Forked and fine-tuned version of GPT-2 for custom datasets: Code for the paper “Language Models are Unsupervised Multitask Learners”. GitHub repository. github.com/nshepperd/gpt-2

[5] Radford, A., Narasimhan, K., Salimans, T., & Sutskever, I. (2018).

Improving language understanding by generative pre-training.

[6] Radford, A., Wu, J., Amodei, D., Amodei, D., Clark, J., Brundage, M., & Sutskever, I. (2019).

Better language models and their implications. OpenAI blog, 1(2).

[7] Uszkoreit, J. (2017).

Transformer: A Novel Neural Network Architecture for Language Understanding. Google Research Blog.

[8] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … & Polosukhin, I. (2017).

Attention is all you need. Advances in neural information processing systems, 30.

The post Unlock the Power of Python for Deep Learning with Transformer Architecture – The Engine Behind ChatGPT first appeared on Python GUI.

]]>
https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-transformer-architecture-the-engine-behind-chatgpt/feed/ 0 11228
How to Build An Image Editor Using DelphiFMX Python Package https://pythongui.org/how-to-build-an-image-editor-using-delphifmx-python-package/ https://pythongui.org/how-to-build-an-image-editor-using-delphifmx-python-package/#respond Mon, 18 Sep 2023 10:00:00 +0000 https://pythongui.org/?p=11191 As a developer, have you ever wanted to create an image editing tool that lets you seamlessly apply a variety of filters, adjust dimensions, and even perform advanced features like background removal? In this comprehensive...

The post How to Build An Image Editor Using DelphiFMX Python Package first appeared on Python GUI.

]]>
As a developer, have you ever wanted to create an image editing tool that lets you seamlessly apply a variety of filters, adjust dimensions, and even perform advanced features like background removal? In this comprehensive tutorial, we will harness the capabilities of DelphiFMX and merge them with image management platforms to craft an image editing application that leverages the incredible potential of AI tools with an amazing GUI. So, let’s get started right away!

How to create an image editing app with DelphiFMX? 

how-to-create-an-image-editing-app-with-delphifmx-2600139

Developing an image editing application with DelphiFMX involves a series of steps. First, install Delphi Integrated Development Environment (IDE) and the Python FireMonkey GUI framework on your computer. These are essential tools for creating the image editor. Additionally, you’ll need a text editor or an IDE that supports Python, such as PyScripter, along with the Delphi4PythonExporter tool. If you don’t have these tools already, we suggest referring to the article “Setting Up a Powerful Python GUI Project” article to help you get started.

Furthermore, it’s crucial to have the requests and cloudinary Python libraries installed. You can achieve this by executing the following commands in your command prompt:

pip install cloudinary
pip install requests

To access the source code for this tutorial, you can download it from our GitHub repository using the following link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Image_Editor_App

What kind of forms do we need for an image editing app?

Let’s begin by launching the Delphi application and initiating a new project. Go to the File menu, select New, then choose Multi-Device Application, and finally, opt for Blank Application and click OK. In this tutorial, we’ve named our project “ImageEditor.”

If you’re not well-acquainted with the different sections of the Delphi IDE, we suggest referring to our complimentary eBook bundle. This resource comprehensively covers the Delphi Python EcoSystem and all Python GUI offerings.

1-2599690

Now, let’s provide a name for our form. Right-click on the form and select QuickEdit. Here, we’ll name our form MainForm with the caption “Image Editor.”

2-8839418

We’ll also rename the source file for our MainForm to Main.pas to simplify tracking. Next, adjust the form’s dimensions in the Object Inspector using ClientWidth and ClientHeight under the properties tab or simply using the mouse.

We can use the TTabControl component of this IDE to add two tabs to our form, one for image editing and the other for background removal. Search for the component in the Palette and drop this component onto the form.

3-1935352

Next, stretch out the component so it occupies the whole form. Here is what our form looks like:

4-3685293

Right-click on the component and click on AddTabItem to add a tab to the form. As mentioned, we will add two tabs, one for image editing and the second for background removal. Next, we’ll use QuickEdit to rename the tabs to Edit and BackgroundRemoval.

5-3879101

Now, let’s incorporate a few labels that will be required for our application. To achieve this, access the standard Palette and locate the TLabel component. Then, drag and drop this component onto the form.

6-1457652

Next, we’ll customize the text style by utilizing the TextSettings property of each label. To do this, navigate to the Object Inspector and search for the TextSettings property. Click on the ellipsis button (...) adjacent to the Font property to explore options for adjusting the label according to your preferences. In this instance, we’ve configured our font family as SemiBold Segoe UI with varying font sizes for each label. Here’s what our form looks like:

7-1769559

Now, let’s add a couple of buttons to our form. For this purpose, we’ll utilize the TButton component. We’ll include two buttons in this tab: FileButton to facilitate file selection for image editing and a TransformButton to edit and display the transformed image.

8-9889248

Next, we’ll add a TImage component to the tab where the selected and edited images will be displayed. A TComboBox will also be used for giving options of all possible image filters to the user. At the same time, a TSpinBox next to it will allow the user to input the intensity of the selected filter. We will also add a TCheckBox component that, when checked, will enable users to change the image’s dimensions by specifying the height and width. We will also add two TEdit components for the user to specify the new image dimensions.

9-1991768

To complete our form, we’ll introduce the TOpenDialog component, enabling us to open a dialog box for file selection from our system. Access the Palette, search for this component, and then drag and drop it onto our form. Here is what the tab looks like:

10-3972548

Now that our Edit tab is complete, we will head to the BackgroundRemoval tab. Here, we will add a TImage component and a TButton component. Here is what the tab looks like:

11-5586346

Finally, let’s infuse some style into our form. To achieve this, you’ll need to obtain the free eBook bundle, which includes various styles. Download the eBook and extract the FMX styles ZIP file to your preferred directory. Select the style you wish to use; in this instance, we’ll opt for GoldenGraphite.style from the bundle. You can explore more DelphiFMX styles online, such as at delphistyles.com.

Go to the Palette and add the TStyleBook component to your form.

12-5036927

Double-click on the StyleBook1 component to access the Style Designer. Now click the open button, which will prompt a dialog box to appear.

13-5316630

Navigate to the .style file within the dialog box, select the file, and then click exit

Now, select the form and access the Object Inspector. Locate the StyleBook property, choose the drop-down menu, and select StyleBook1.

14-7631909

Here’s what our form looks like:

15-9277676

Now that the form is fully configured, the last step involves adding functionality to each button within the form. To achieve this, double-click on each button. This action will generate an OnClick method for that button. This will create a procedure in the .pas file corresponding to the .fmx form, enabling you to incorporate unique functionality for each button when clicked.

16-2002912

Due to the Delphi4PythonExporter’s lack of runtime implementation, including at least one comment (//) in each procedure to preserve its function when exporting the form is essential.

17-2578614

How can I export these forms into Python code?

Now that our form is ready, we can export the project by navigating to Tools > Export To Python > Export Current Entire Project.

18-6434660

Here, we will give the project the title Image Editor App. Next, select the directory of your choosing and click on Export:

19-1485474

Because we had one form, Delphi generated two Python files and one .pyfmx file. The ImageEditor.py file will be used to run the application, whereas the Main.py file contains the class for the MainForm. The Main.pyfmx file contains the visual information for the MainForm. Here are the contents for each file.

ImageEditor.py:

from delphifmx import *
from Main import MainFrom

def main():
    Application.Initialize()
    Application.Title = 'Image Editor App'
    Application.MainForm = MainFrom(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Main.py:

import os
from delphifmx import *

class MainFrom(Form):

    def __init__(self, owner):
        self.TabControl1 = None
        self.Edit = None
        self.FilenameLabel = None
        self.EffectLabel = None
        self.IntensityLabel = None
        self.WidthLabel = None
        self.HeightLabel = None
        self.TransformButton = None
        self.FileButton = None
        self.EffectComboBox = None
        self.SpinBox1 = None
        self.DimensionsCheckBox = None
        self.EditImage = None
        self.BackgroundRemoval = None
        self.RemoveBgImage = None
        self.RemoveButton = None
        self.OpenDialog1 = None
        self.StyleBook1 = None
        self.WidthEdit = None
        self.HeightEdit = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def TransformButtonClick(self, Sender):
        pass

    def FileButtonClick(self, Sender):
        pass

    def RemoveButtonClick(self, Sender):
        pass

How can I add functionality to our image editing form?

The only thing we need to do now is start adding functionality to our forms. Start by opening up Main.py in the text editor of your choice and importing some libraries:

# Additional Imports
import cloudinary
from cloudinary import uploader
from cloudinary import CloudinaryImage
import requests
import time

Next, navigate to the __init__ function. Here, we will define our effect_options in a dictionary and use it to populate our EffectComboBox. Next, we will define our Cloudinary API using our cloud credentials. Here is what our __init__ function looks like:

def __init__(self, owner):
        self.TabControl1 = None
        self.Edit = None
        self.FilenameLabel = None
        self.EffectLabel = None
        self.IntensityLabel = None
        self.WidthLabel = None
        self.HeightLabel = None
        self.TransformButton = None
        self.FileButton = None
        self.EffectComboBox = None
        self.SpinBox1 = None
        self.DimensionsCheckBox = None
        self.EditImage = None
        self.BackgroundRemoval = None
        self.RemoveBgImage = None
        self.RemoveButton = None
        self.OpenDialog1 = None
        self.StyleBook1 = None
        self.WidthEdit = None
        self.HeightEdit = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Defining different effect options
        self.effect_options = {0:"--", 1:"cartoonify", 2:"pixelate", 3:"sepia", 4:"vignette", 5:"grayscale"}

        # Populating ComboBox
        for option in list(self.effect_options.values()):
            self.EffectComboBox.Items.Add(option)

        # Configure Cloudinary with your account details
        cloudinary.config(
        cloud_name = "your_cloud_name",
        api_key = "your_api_key",
        api_secret = "your_api_secret"
        )

Next, let’s head over to the FileButtonClick function. Here, we will start by defining the title of the Dialog Box and filter the results only to show image formats:

def FileButtonClick(self, Sender):
        # Filepicker window title
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.bmp,*.webp)|*.jpg;*.jpeg;*.png;*.bmp;*.webp|All files (*.*)|*.*"

Once the user selects the image, we open it up and extract its information, including its location and name. Here is what our FilebuttonClick function looks like:

def FileButtonClick(self, Sender):
        # Filepicker window title
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.bmp,*.webp)|*.jpg;*.jpeg;*.png;*.bmp;*.webp|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            self.FilenameLabel.Text = os.path.basename(self.OpenDialog1.FileName) # Display selected image name
            self.EditImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)
            self.RemoveBgImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)
            self.public_id = self.FilenameLabel.Text.split('.')[0]

Next, we will create a BoxChecked function to turn our Width and Height edit labels on or off. Here is what the function looks like:

def BoxChecked(self, Sender):
        if self.DimensionsCheckBox.IsChecked:
            # Enable the WidthEdit and HeightEdit controls
            self.WidthEdit.Enabled = True
            self.HeightEdit.Enabled = True
        else:
            # Disable the WidthEdit and HeightEdit controls
            self.WidthEdit.Enabled = False
            self.HeightEdit.Enabled = False

Before moving forward, we will define a helper function to help us download our images from the Cloudinary cloud. Start by creating a download function inside the MainForm class. Next, we will use requests to retrieve the image using a url provided in the results parameter. The image is then saved in the path defined in the local_file_path parameter. Finally, it is then loaded onto the form using the image parameter. Here is what our final function looks like:

def Download(self, result, local_file_path, image):
        # Retrieving Image
        response = requests.get(result, stream=True)

        if response.status_code == 200:
            with open(local_file_path, "wb") as file:
                for chunk in response.iter_content(1024):
                    file.write(chunk)
            print(f"Transformed image saved to: {local_file_path}")

            # Load and display the downloaded image in the DownloadedImage control
            image.Bitmap.LoadFromFile(local_file_path)
        else:
            print("Failed to download the image.")

Now, let’s define our TransformButtonClick function. We will start by defining an empty list called transformations that will be used to pass our transformation parameters to the Cloudinary API. Next, we will check if the DimensionsCheckBox has been checked. If it has, we will add a width and height transformation to the list:

def TransformButtonClick(self, Sender):
        transformations = []
        # Adding Height and Width Parameters if Checkbox is checked
        if self.DimensionsCheckBox.IsChecked:
            if self.WidthEdit.Text.isdigit() and self.HeightEdit.Text.isdigit():
                transformations.append({"height": int(self.HeightEdit.Text), "width": int(self.WidthEdit.Text), "crop": "fill"})

Next, we will retrieve the transformation selected in the combo box as well as its intensity from the spin box. We will then add these transformations to the list and call the uploader function to upload the image with said transformation. Next, we will download the transformed image using our download function. Here is what our complete function looks like:

def TransformButtonClick(self, Sender):
        transformations = []
        # Adding Height and Width Parameters if Checkbox is checked
        if self.DimensionsCheckBox.IsChecked:
            if self.WidthEdit.Text.isdigit() and self.HeightEdit.Text.isdigit():
                transformations.append({"height": int(self.HeightEdit.Text), "width": int(self.WidthEdit.Text), "crop": "fill"})
       
        # Adding Effect Paramets along with Intensity
        if self.EffectComboBox.ItemIndex in list(self.effect_options.keys()) and self.effect_options[self.EffectComboBox.ItemIndex] != "--" and self.SpinBox1.Text.isdigit():
            if 0 < int(self.SpinBox1.Text) <= 100:
                transformations.append({"effect": "{}:{}".format(self.effect_options[self.EffectComboBox.ItemIndex], self.SpinBox1.Text)})

        # Upload the image to Cloudinary with the specified public ID
        result = uploader.upload(self.OpenDialog1.FileName, public_id=self.public_id, transformation=transformations)['secure_url']

        # Define the local file path where you want to save the image
        local_file_path = ".Imagesedited_"+self.FilenameLabel.Text  # Change to your desired local path

        # Download the transformed image and save it locally
        self.Download(result, local_file_path, self.EditImage)

Finally, we can complete our app by defining the RemoveButtonClick function. Like the TransformButtonClick function, we will make a simple API call to the Cloudinary cloud with a background_removal parameter. This parameter uses the Cloudinary AI Background Removal addon which removes the background from our image. You can learn more about this addon here. Here is what our final function looks like:

def RemoveButtonClick(self, Sender):
        self.public_id+='_removal'

        # Uploading Image with background removal API
        result = uploader.upload(self.OpenDialog1.FileName, public_id=self.public_id, background_removal = "cloudinary_ai")
        print(result)
        result= result['secure_url']
        image = CloudinaryImage(self.public_id)

        # Retrieving Image URL
        result = image.url + ".png"
        print(result)

        # Defining Local Save Path
        local_file_path = ".Imagesbg_removed_"+self.public_id+".png" # Change to your desired local path

        # Adding Time for background removal completion
        time.sleep(5)

        # Downloading Image
        self.Download(result, local_file_path, self.RemoveBgImage)

Here is what our final Main.py file looks like:

import os
from delphifmx import *

# Additional Imports
import cloudinary
from cloudinary import uploader
from cloudinary import CloudinaryImage
import requests
import time

class MainFrom(Form):
    def __init__(self, owner):
        self.TabControl1 = None
        self.Edit = None
        self.FilenameLabel = None
        self.EffectLabel = None
        self.IntensityLabel = None
        self.WidthLabel = None
        self.HeightLabel = None
        self.TransformButton = None
        self.FileButton = None
        self.EffectComboBox = None
        self.SpinBox1 = None
        self.DimensionsCheckBox = None
        self.EditImage = None
        self.BackgroundRemoval = None
        self.RemoveBgImage = None
        self.RemoveButton = None
        self.OpenDialog1 = None
        self.StyleBook1 = None
        self.WidthEdit = None
        self.HeightEdit = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Defining different effect options
        self.effect_options = {0:"--", 1:"cartoonify", 2:"pixelate", 3:"sepia", 4:"vignette", 5:"grayscale"}

        # Populating ComboBox
        for option in list(self.effect_options.values()):
            self.EffectComboBox.Items.Add(option)

        # Configure Cloudinary with your account details
        cloudinary.config(
        cloud_name = "dzte1natd",
        api_key = "558364876947471",
        api_secret = "Llc8TFU56g17mjPWK_kEgNd--mE"
        )

    def BoxChecked(self, Sender):
        if self.DimensionsCheckBox.IsChecked:
            # Enable the WidthEdit and HeightEdit controls
            self.WidthEdit.Enabled = True
            self.HeightEdit.Enabled = True
        else:
            # Disable the WidthEdit and HeightEdit controls
            self.WidthEdit.Enabled = False
            self.HeightEdit.Enabled = False

    def TransformButtonClick(self, Sender):
        transformations = []
        # Adding Height and Width Parameters if Checkbox is checked
        if self.DimensionsCheckBox.IsChecked:
            if self.WidthEdit.Text.isdigit() and self.HeightEdit.Text.isdigit():
                transformations.append({"height": int(self.HeightEdit.Text), "width": int(self.WidthEdit.Text), "crop": "fill"})
       
        # Adding Effect Paramets along with Intensity
        if self.EffectComboBox.ItemIndex in list(self.effect_options.keys()) and self.effect_options[self.EffectComboBox.ItemIndex] != "--" and self.SpinBox1.Text.isdigit():
            if 0 < int(self.SpinBox1.Text) <= 100:
                transformations.append({"effect": "{}:{}".format(self.effect_options[self.EffectComboBox.ItemIndex], self.SpinBox1.Text)})

        # Upload the image to Cloudinary with the specified public ID
        result = uploader.upload(self.OpenDialog1.FileName, public_id=self.public_id, transformation=transformations)['secure_url']

        # Define the local file path where you want to save the image
        local_file_path = ".Imagesedited_"+self.FilenameLabel.Text  # Change to your desired local path

        # Download the transformed image and save it locally
        self.Download(result, local_file_path, self.EditImage)

    def FileButtonClick(self, Sender):
        # Filepicker window title
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.bmp,*.webp)|*.jpg;*.jpeg;*.png;*.bmp;*.webp|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            self.FilenameLabel.Text = os.path.basename(self.OpenDialog1.FileName) # Display selected image name
            self.EditImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)
            self.RemoveBgImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)
            self.public_id = self.FilenameLabel.Text.split('.')[0]

    def RemoveButtonClick(self, Sender):
        self.public_id+='_removal'

        # Uploading Image with background removal API
        result = uploader.upload(self.OpenDialog1.FileName, public_id=self.public_id, background_removal = "cloudinary_ai")
        print(result)
        result= result['secure_url']
        image = CloudinaryImage(self.public_id)

        # Retrieving Image URL
        result = image.url + ".png"
        print(result)

        # Defining Local Save Path
        local_file_path = ".Imagesbg_removed_"+self.public_id+".png" # Change to your desired local path

        # Adding Time for background removal completion
        time.sleep(5)

        # Downloading Image
        self.Download(result, local_file_path, self.RemoveBgImage)

    def Download(self, result, local_file_path, image):
        # Retrieving Image
        response = requests.get(result, stream=True)

        if response.status_code == 200:
            with open(local_file_path, "wb") as file:
                for chunk in response.iter_content(1024):
                    file.write(chunk)
            print(f"Transformed image saved to: {local_file_path}")

            # Load and display the downloaded image in the DownloadedImage control
            image.Bitmap.LoadFromFile(local_file_path)
        else:
            print("Failed to download the image.")

What does the final Python image editing app look like?  

Now that everything is complete, all we need to do is open up the ImageEditor.py file and run it.

20-5197204

Next, click on the File button and load up an image file. For now, we will be loading using an image of a teacher as a reference.

21-8544310

Once you’ve selected your image, you can add an effect to your image. Here, we will add a pixelate effect with an intensity of 30.

22-7816273

Finally, click the Transform button to add the effect to your image.

23-3399836

Next, let’s head over to the Background Removal tab.

24-2855568

Now click on Remove to remove the background of the subject.

25-8817564

Are you ready to create more apps with DelphiFMX?

are-you-ready-to-create-more-apps-with-delphifmx-7094947

Creating an image editing application with DelphiFMX empowers developers to leverage AI tools and elevate their image manipulation capabilities. By seamlessly integrating the Delphi IDE with the DelphiFMX Python library, you can lay the foundation for a robust image editor. Moreover, Delphi’s flexibility allows you to harness external APIs like Cloudinary for enhanced functionality, enabling features like advanced filters, dimension adjustments, and even background removal while managing to provide one of the best GUI tools.

Ready to embark on your creative journey? Dive into the world of image editing with DelphiFMX and unlock a realm of possibilities!

What are some important FAQs about creating great apps with Python and Delphi?

what-are-some-important-faqs-in-this-domain-8085178

What are the benefits of using Delphi for image editing apps?

Delphi offers a powerful and flexible development environment for building image editing applications. It provides access to various libraries, APIs, and tools that streamline the development process and enable rich functionality.

Is DelphiFMX suitable for cross-platform development?

Yes, DelphiFMX is known for its cross-platform compatibility. You can develop apps for Windows, macOS, iOS, and Android using a single codebase, which is advantageous for reaching a wider audience.

Can I use external APIs like Cloudinary in my DelphiFMX app?

DelphiFMX allows you to integrate external APIs like Cloudinary to enhance your app’s capabilities. You can use APIs for image storage, management, and manipulation.

Can I monetize my image editing app created with DelphiFMX?

Yes, you can monetize your app through various means, such as offering it as a paid download, integrating ads, or offering in-app purchases for premium features

The post How to Build An Image Editor Using DelphiFMX Python Package first appeared on Python GUI.

]]>
https://pythongui.org/how-to-build-an-image-editor-using-delphifmx-python-package/feed/ 0 11191
How To Use LangChain and DelphiFMX To Create a Custom Chat App https://pythongui.org/how-to-use-langchain-and-delphifmx-to-create-a-custom-chat-app/ https://pythongui.org/how-to-use-langchain-and-delphifmx-to-create-a-custom-chat-app/#respond Thu, 07 Sep 2023 12:51:48 +0000 https://pythongui.org/?p=11119 These days there is a lot of discussion about deep-learning chatbots such as ChatGPT. There are packages like LangChain which make consuming these models easier. This tutorial will guide you through a project combining LangChain...

The post How To Use LangChain and DelphiFMX To Create a Custom Chat App first appeared on Python GUI.

]]>
These days there is a lot of discussion about deep-learning chatbots such as ChatGPT. There are packages like LangChain which make consuming these models easier. This tutorial will guide you through a project combining LangChain and DelphiFMX‘s innovative capabilities to craft a unique and personalized custom chat app. So, let’s get started!

What is Langchain?

How To Use LangChain and DelphiFMX To Create a Custom Chat App

LangChain is a framework for creating language model-driven applications. Language models are artificial intelligence programs that can produce text in natural language in response to inputs like questions, prompts, or documents. With LangChain, you can link a language model to additional data sources like files, databases, or web pages and communicate with them using natural language. Using different components and APIs offered by LangChain, you may also alter how the language model and application behave. With LangChain, you may create various apps, such as chatbots, code generators, document summarization tools, and more.

How to build a custom chat app with  LangChain and DelphiFMX?

How To Use LangChain and DelphiFMX To Create a Custom Chat App

In this article, we intend to go over the basics of LangChain in Python and use Openai’s LLM model to create a chat app that considers the user’s age and gives answers according to this information. So the GUI will involve two screens. Some user data is taken on the first screen, while the second screen is the chat screen with widgets like a memo, button, and textbox.

What are the prerequisites of the custom chat app project?

To create the custom chat application, you should install the Delphi IDE, the Delphi4PythonExporter tool, and the DelphiFMX library on your device. Additionally, you will need a text editor or IDE that supports Python, such as PyScripter. If you don’t have these tools installed, we recommend checking out the article “Powerful Python GUI Project Setup” to help you get started. 

Next, install Langchain and OpenAI by using the following command:

pip install langchain openai

Lastly, you can get the complete code for this project from our GitHub repository:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Custom_Chat_App

How to use a prompt template in LangChain?

You might be asking yourself, what are Prompt Templates? Why should we use them in Chatbots? In simple words, Prompt Templates are pre-defined recipes that help generate prompts for language models. These templates may include certain instructions, some examples to help the chatbot, or even specific contexts and/or questions to help the chatbot with a certain task.

Take, for example, ChatGPT. If you ask ChatGPT, “What is the definition of a Machine Learning model?” It might give you an in-depth and detailed answer. A prompt will help give ChatGPT instructions on how the user might want the question answered. For example, A prompt may append text to a query to modify the model’s output like the query above may change into “What is the definition of a Machine Learning model? Explain it to me like a 5-year-old.” This will change the answer, and the model may reduce complex words to make it easy for the user to understand.

LangChain, as a framework, provides many tools to create and work with prompt templates. Let’s start by creating a simple prompt template that helps our OpenAI chatbot. Start by creating a new file called LLMChat.py in your project directory and start importing some modules:

from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory

Next, create an LLM class with an __init__ and a getReply method:

class LLM():
    def __init__(self, name, age) -> None:
        pass

    def getReply(self, qs):
        pass

Start by initializing your name and age variables in the __init__ function and create an LLM model, a template for queries, and a ConversationBufferMemory to help store your previous conversations. You need to create your OpenAI api key and replace your key in the openai_api_key variable’s value:

class LLM():
    def __init__(self, name, age) -> None:
        self.age = age
        self.name = name

        llm = OpenAI(openai_api_key="**PUT YOUR API KEY HERE**", temperature=0) # Create instance of openai llm
        temp = "You are a nice chatbot having a conversation with a human of age {}.".format(age)
        template = temp + """ So respond appropriately and preferably in around 2 sentences.

        Previous conversation:
        {chat_history}

        New human question: {question}
        Response:"""
        prompt = PromptTemplate.from_template(template) # Create template for prompt to openai
        memory = ConversationBufferMemory(memory_key="chat_history") # Create buffer memory for multiturn conversation

Finally, we chain all the components using an LLMChain, completing our __init__ function:

def __init__(self, name, age) -> None:
        self.age = age
        self.name = name

        llm = OpenAI(openai_api_key="**PUT YOUR API KEY HERE**", temperature=0) # Create instance of openai llm
        temp = "You are a nice chatbot having a conversation with a human of age {}.".format(age)
        template = temp + """ So respond appropriately and preferably in around 2 sentences.

        Previous conversation:
        {chat_history}

        New human question: {question}
        Response:"""
        prompt = PromptTemplate.from_template(template) # Create template for prompt to openai
        memory = ConversationBufferMemory(memory_key="chat_history") # Create buffer memory for multiturn conversation
        self.conversation = LLMChain( # Chain all components
            llm=llm,
            prompt=prompt,
            memory=memory
        )

Next, navigate to the getReply method and simply use the model to generate a response to a question and then return the response. Here is what our complete LLMChat.py looks like:

from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory

class LLM():
    def __init__(self, name, age) -> None:
        self.age = age
        self.name = name

        llm = OpenAI(openai_api_key="your_openai_api_key", temperature=0) # Create instance of openai llm
        temp = "You are a nice chatbot having a conversation with a human of age {}.".format(age)
        template = temp + """ So respond appropriately and preferably in around 2 sentences.

        Previous conversation:
        {chat_history}

        New human question: {question}
        Response:"""
        prompt = PromptTemplate.from_template(template) # Create template for prompt to openai
        memory = ConversationBufferMemory(memory_key="chat_history") # Create buffer memory for multiturn conversation
        self.conversation = LLMChain( # Chain all components
            llm=llm,
            prompt=prompt,
            memory=memory
        )

    def getReply(self, qs):
        response = self.conversation({"question": qs}) # Provide conversation to LLM to get appropriate answer
        return response["text"]

How to design the user interface for our custom chat app in Delphi?

Now that our LangChain model is complete, we can start working on the user interface for our Delphi app.

Open up Delphi CE and create a new project using File > New > Multi-Device Application > Blank Application > Ok. Next, set up a name for the project. Here we are naming our project ChatApplication.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

If you are unfamiliar with the various sections of the Delphi IDE, we recommend consulting our complimentary eBook bundle, which covers the Delphi Python Ecosystem and provides insights into all Python GUI offerings.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Next, let’s rename our form by right-clicking on it and selecting QuickEdit. Here we will set our form name as BioScreen with the caption Chat Application.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Next, we’ll rename the project’s source file to help us keep track of it. Head over to the Projects tab on the top-right corner of your screen and locate Unit1.pas file. This is the source file of your form. We will rename it to Bio.pas.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Next, we’ll use the head to the Object Inspector and resize our form using the ClientWidth and ClientHeight properties under the Properties tab.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now, we’ll add a few labels to our form. Head over to the Palette and search for the TLabel component. Drop a few of these into your form.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Rename these components by right-clicking on them and opening up QuickEdit. Next, head over to the Object Inspector and customize the text style for each label using the TextSettings property based on your needs. You could additionally set the HorzAlign and VertAlign properties to Center to align your text. Here is what our form looks like:

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now, we’ll add a text box next to the Name label and a number box next to the Age label. Open up the Palette and search for the TEdit and TNumberBox components. As the name implies, the TEdit component will be used to input text to our form, whereas the TNumberBox will be used to input the age. Here is what our form looks like:

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Next, let’s add a button to our form, which will be used to open up the chat screen. For this, we will use the TButton component, so navigate to the Palette and search for the component.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Next, modify the button using its Text Settings property. Finally, rename the button and set its caption. Here we’ve named our button StartButton with the caption Start Chatting.

Here is what our form looks like:

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Finally, let’s finish our form by adding an image. Head over to the Palette and search for the TImage component. Add this component to your form.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now select the TImage component and open the MultiResBitMap property in the Properties tab of the Object Inspector. Next, click the open button and select the image you want to use.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Here is what our form looks like:

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now that our BioScreen form is complete, we can move on and create our chat screen. Head over to the projects tab, and after right-clicking on ChatApplication.exe, select Add New > Multi-Device Form.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

This will create a new form which we have named as ChatScreen, and the corresponding source file as Chat.pas. We have also renamed the form caption to Chat.

Next, let’s add a THeader and a TFooter component to our form. We also add a few labels, buttons, and an edit box to our form. Here is what our form looks like:

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Finally, we need to add a text box to display our chats. For this, we’ll add a TMemo component that will be large enough to display all our messages and have a scroll to move up and down in the chat. Here is what our final form looks like:

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now that we’ve completed our forms, it’s time to add a few final touches. To do this, download the free ebook bundle, which comes shipped with a multitude of styles that you can choose from. Once downloaded, extract the FMX styles zip. Next, select the style you want to use. Here we will be using AquaGraphite.style available in the bundle.

Now, head to the Palette and add a TStyleBook component to your form. The placement does not matter for this component, as it will be invisible.

How To Use LangChain and DelphiFMX To Create a Custom Chat App
How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now, double-click on the StyleBook1 component to open up your Style Designer. Click on the open button to open up a dialog box.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now navigate to the Dark.style file in your styles directory, select your file and click exit and save.

Select your form and head over to the Object Inspector. Here search for the StyleBook property. Now, select the drop-down menu and select StyleBook1. This will add style to your form.

Here is what our final forms look like:

How To Use LangChain and DelphiFMX To Create a Custom Chat App
How To Use LangChain and DelphiFMX To Create a Custom Chat App

How to combine everything into our finished custom chat app? 

Now that our forms are complete, we need to add some functionality to the button so we don’t lose it when we export it in Python. To do this, double-click on each button on the forms. This will add an OnClick method to that button, creating a procedure in the .pas file of the form. This allows you to add unique functionality to each button when clicked.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Because the Delphi4PythonExporter does not use run-time implementation, we must add at least one comment (//) to each procedure to preserve the function when we export the form.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

With this, we are ready to export our project. Select Tools > Export To Python > Export Current Entire Project to export the project.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Here we will give the project the title Chat Application. Next, select the directory of your choosing and click on Export:

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Once the export is complete, head over to the project directory. Delphi will generate three Python files and two .pyfmx files. The ChatApplication.py file will be used to run the application, whereas the Bio.py and Chat.py files contain the class for the BioScreen and ChatScreen forms. The .pyfmx files contain the visual information for the forms. Here are the contents for each file.

ChatApplication.py:

from delphifmx import *
from Bio import BioScreen

def main():
    Application.Initialize()
    Application.Title = 'Chat Application'
    Application.MainForm = BioScreen(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Bio.py:

import os
from delphifmx import *

class BioScreen(Form):

    def __init__(self, owner):
        self.TitleLabel = None
        self.AgeLabel = None
        self.NameLabel = None
        self.AgeNumberBox = None
        self.NameEdit = None
        self.Image1 = None
        self.StartButton = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Bio.pyfmx"))

    def StartButtonClick(self, Sender):
        pass

Chat.py:

import os
from delphifmx import *

class ChatScreen(Form):

    def __init__(self, owner):
        self.SendButton = None
        self.UserQsEdit = None
        self.Header = None
        self.HeaderLabel = None
        self.Footer = None
        self.BackButton = None
        self.ChatMemo = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Chat.pyfmx"))

    def SendButtonClick(self, Sender):
        pass

    def BackButtonClick(self, Sender):
        pass

Now, let’s begin adding functionality to our code. Start by copying and pasting the LLMChat.py file that we created earlier to the project folder. Next, open up Bio.py and import the ChatScreen form from Chat.py:

from chat import ChatScreen

Next, head over to the StartButtonClick function. Here we are simply going to create the ChatScreen, pass in our name and age variables, and then open up the screen. Here is what the StartButtonClick function looks like:

def StartButtonClick(self, Sender):
        chat = ChatScreen(self, name=self.NameEdit.Text, age=self.AgeNumberBox.Text)
        chat.Show()

Here is what our final Bio.py file looks like:

import os
from delphifmx import *
# Import chat form
from Chat import ChatScreen


class BioScreen(Form):

    def __init__(self, owner):
        self.TitleLabel = None
        self.AgeLabel = None
        self.NameLabel = None
        self.AgeNumberBox = None
        self.NameEdit = None
        self.Image1 = None
        self.StartButton = None
        self.StyleBook1 = None
        self.ErrorLabel = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Bio.pyfmx"))

    def StartButtonClick(self, Sender):
        chat = ChatScreen(self, name=self.NameEdit.Text,
                          age=self.AgeNumberBox.Text)
        chat.Show()

Next, open up Chat.py and start by importing the LLM class from the LLMChat.py file. 

from LLMChat import LLM

Now head over to the __init__ function and start by adding some additional name and age parameters to the function. Next, we’ll re-initialize the HeaderLabel with the name of our user and store the name and age in new variables. Finally, we’ll create an instance of our LLM class in the constructor. Here is what our __init__ function looks like:

def __init__(self, owner, name, age):
        self.SendButton = None
        self.UserQsEdit = None
        self.Header = None
        self.HeaderLabel = None
        self.Footer = None
        self.BackButton = None
        self.ChatMemo = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Chat.pyfmx"))

        self.HeaderLabel.Text = "{}'s Chat".format(name)
        self.age = age
        self.name = name
        self.llm = LLM(name, age)  # Create LLM chain instance

Next, in our SendButtonClick function, we’ll simply add a formatted user query to the ChatMemo. Once we get a reply from the LLM model, we will append that to the ChatMemo too. Here is what our final function looks like:

def SendButtonClick(self, Sender):
        # Add user's question to the memo for chat history
        self.ChatMemo.Lines.Add("{}: {}".format(
            self.name, self.UserQsEdit.Text))
        # Get the reponse to the question
        reply = self.llm.getReply(self.UserQsEdit.Text)
        # Add the response to the memo as well
        self.ChatMemo.Lines.Add("Chatbot:{}".format(reply))

Finally, our BackButtonClick will only be used to close the chat screen, which we can simply do using self.Destroy(). Here is what our final Chat.py file looks like:

import os
from delphifmx import *
# More required imports
from LLMChat import LLM


class ChatScreen(Form):

    def __init__(self, owner, name, age):
        self.SendButton = None
        self.UserQsEdit = None
        self.Header = None
        self.HeaderLabel = None
        self.Footer = None
        self.BackButton = None
        self.ChatMemo = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Chat.pyfmx"))

        self.HeaderLabel.Text = "{}'s Chat".format(name)
        self.age = age
        self.name = name
        self.llm = LLM(name, age)  # Create LLM chain instance

    def SendButtonClick(self, Sender):
        # Add user's question to the memo for chat history
        self.ChatMemo.Lines.Add("{}: {}".format(
            self.name, self.UserQsEdit.Text))
        # Get the reponse to the question
        reply = self.llm.getReply(self.UserQsEdit.Text)
        # Add the response to the memo as well
        self.ChatMemo.Lines.Add("Chatbot:{}".format(reply))

    def BackButtonClick(self, Sender):
        self.Destroy()

Now that our application is ready let’s test it out. Head over to ChatApplication.py and run the file.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Next, add your name and age and click on Start Chatting.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

This should open up your chat screen.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

Now simply start messaging on the chat app.

How To Use LangChain and DelphiFMX To Create a Custom Chat App

What have you learned in this custom chat app tutorial?

How To Use LangChain and DelphiFMX To Create a Custom Chat App

In today’s world of advanced communication, we’re talking about smart chatbots like ChatGPT and tools like LangChain that make them work better together. This tutorial has shown us how LangChain, DelphiFMX, and Python can be paired to make a custom chat app with an amazing GUI.

LangChain is like the main character, letting computers talk like humans using trained language models. With this magic, we’re making a chat app that talks in a smart way, depending on how old you are. We saw how Delphi allows us to add more personalization by adding the user’s name in several places of the GUI. This tutorial shows how exciting things can happen when smart tech and good GUIs come together, inviting us to change how we talk and connect using computers.

Ready to get creative? Dive into the world of DelphiFMX and start crafting your own unique apps today. Download Delphi and unleash your imagination!

What are some FAQs related to this custom chat app tutorial?

How To Use LangChain and DelphiFMX To Create a Custom Chat App

What is LangChain, and how does it relate to chat applications?

LangChain is a framework that uses language models to create text-based applications. In the context of chat apps, LangChain enables the creation of chatbots and other communication tools that understand and generate natural language responses.

Do I need to be an expert in machine learning to use LangChain?

LangChain is designed to simplify the process of using language models for developers. While some familiarity with machine learning concepts could be helpful, the framework aims to make it accessible to a wider range of developers.

What is DelphiFMX, and why is it used in this tutorial?

DelphiFMX is a graphical user interface framework that allows developers to create cross-platform applications with rich UI experiences. It’s used in this tutorial to design the user interface for the chat app.

Do I need prior experience with Delphi to follow this tutorial?

While prior experience with Delphi could be beneficial, the tutorial should provide step-by-step guidance to help you create the chat app, even if you’re new to Delphi programming.

The post How To Use LangChain and DelphiFMX To Create a Custom Chat App first appeared on Python GUI.

]]>
https://pythongui.org/how-to-use-langchain-and-delphifmx-to-create-a-custom-chat-app/feed/ 0 11119
How To Build an Iris Flower Classification GUI App With DelphiFMX https://pythongui.org/how-to-build-an-iris-flower-classification-gui-app-with-delphifmx/ https://pythongui.org/how-to-build-an-iris-flower-classification-gui-app-with-delphifmx/#respond Fri, 01 Sep 2023 02:35:24 +0000 https://pythongui.org/?p=11083 Today, the marvels of Artificial Intelligence (AI) are transforming the landscape of various classification tasks. From identifying objects in images to categorizing data in complex datasets, AI has become a driving force in solving numerous...

The post How To Build an Iris Flower Classification GUI App With DelphiFMX first appeared on Python GUI.

]]>
Today, the marvels of Artificial Intelligence (AI) are transforming the landscape of various classification tasks. From identifying objects in images to categorizing data in complex datasets, AI has become a driving force in solving numerous classification challenges.

This tutorial will create a powerful Iris Flower Classification app using DelphiFMX and Support Vector Machines (SVM). Harnessing the prowess of machine learning and the Delphi ecosystem, we will enable users to classify iris flowers accurately and efficiently. Experience the excitement of building an ML-powered app with DelphiFMX and providing users with real-time insights into flower species right at their fingertips.

Why Are Support Vector Machines Gaining Popularity?

How To Build an Iris Flower Classification GUI App With DelphiFMX

Support Vector Machines (SVM) have become increasingly popular in machine learning due to their remarkable effectiveness in classification tasks. They exhibit versatility in handling binary and multi-class classification problems, making them suitable for various applications. SVMs thrive in high-dimensional feature spaces, making them well-suited for complex datasets, including text classification, image recognition, and bioinformatics. One of their key strengths lies in their robustness against overfitting leading to reliable generalization. 

Additionally, SVMs utilize the kernel trick to efficiently deal with non-linearly separable data by transforming the feature space into a higher-dimensional space. This attribute and their memory efficiency ensure practical applicability with large datasets. Moreover, SVMs provide clear decision boundaries, contributing to their interpretability and explainability, which are essential in scenarios where understanding model reasoning is crucial. 

How to Create the Iris Flower Classification App with DelphiFMX?

How To Build an Iris Flower Classification GUI App With DelphiFMX

Creating a flower classification app involves several steps. Before we get into the detailed tutorial, let’s check the requirements for this project.

Install the RAD Studio with Delphi IDE and the DelphiFMX on your device to create the flower classification app. You will need a text editor or IDE that supports Python, such as PyScripter and the Delphi4PythonExporter tool. If you don’t have these tools installed, checking out the article “Powerful Python GUI Project Setup” is recommended. 

You should also install Python’s scikit-learn library by running the following command in the cmd:

pip install -U scikit-learn

You can retrieve the project code from the following GitHub link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Iris_Flower_Classifier

Which Dataset Can be Used for Such a Task?

For the Iris Flower Classification app, the ideal dataset to use is the famous Iris dataset from the scikit-learn library. The Iris dataset is a well-known and widely used dataset in the field of machine learning. It contains 150 samples of iris flowers, with each sample representing a different iris species: setosa, versicolor, or virginica. For each sample, four features are recorded: sepal length, sepal width, petal length, and petal width.

How to Train a Support Vector Machine Classifier?

Training an SVM classifier is very simple in Python:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

# Load the Iris dataset
iris = load_iris()
X, y = iris.data, iris.target

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train the Support Vector Machine Classifier
svm = SVC()
svm.fit(X_train, y_train)

The above code utilizes scikit-learn to train an SVM classifier for Iris flower classification. The Iris dataset is loaded, containing features and target labels representing different iris species. The data is split into training and testing sets, and an SVM classifier is instantiated. The classifier is then trained on the training data, learning to separate the iris species based on their features. The SVM algorithm aims to find the optimal decision boundary with the maximum margin between classes, making it a powerful tool for classification tasks like iris flower classification.

How to Design the User Interface with DelphiFMX?

Now that we know how to create our train our classifier let’s start creating our Delphi app.
Start by opening up Delphi CE and create a new project by navigating to File > New > Multi-Device Application > Blank Application > Ok. For this tutorial, we are naming our project IrisFlowerClassifier.

How To Build an Iris Flower Classification GUI App With DelphiFMX

If you are unfamiliar with the various sections of the Delphi IDE, we recommend consulting our complimentary eBook bundle, which covers the Delphi Python Ecosystem and provides insights into all Python GUI offerings.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Next, we will rename our form. To do this, right-click on your form and select QuickEdit. This will open up your edit box. Here we will set our form name as MainForm with the caption Iris Flower Classifier App.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Now head over to the Projects tab on the top-right corner of your screen and locate the Unit1.pas file. This is the source file of your form. We will rename it to Main.pas to help us keep track of our form.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Finally, we will resize our form to make it more appealing. Select your form and head over to the Object Inspector. Here click on the properties tab and search for the ClientWidth and ClientHeight properties. We will resize our form by setting them to 360 and 500, respectively.

How To Build an Iris Flower Classification GUI App With DelphiFMX

With the basics out of the way, we can start by adding elements to our form. Head to the Palette in the bottom-right corner and search for the TLabel component. Now drag and drop this component on your form. We will add six labels to our form. Five of our Labels will be static, i.e. they will not change and will be used as indicators. This includes our title, sepal length, sepal width, petal length, and petal width labels which we’ve named as Title, SLength, SWidth, PLength, and PWidth. One of our labels which we’ve named Result will be used to show the prediction of the flower.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Next, we will select each label and head over to the Object Inspector. Here we’ll customize the text style for each label using the TextSettings property. Click on the ellipsis button (…) next to the Font property to explore various options for modifying the label. As always, we will use the SemiBold Segue UI font family and distinct font sizes for each label. Additionally, we’ll set our labels’ HorzAlign and VertAlign properties to Center.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Here is what our form looks like:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Next, let’s add a button to our form. This button will be used to trigger the prediction function. For this, we will use the TButton component, so navigate to the Palette and search for the component.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Next, modify the button using its Text Settings property. Finally, rename the button and set its caption. Here we’ve named our button Predict with the caption Classify Flower. Here is what our form looks like:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Finally, let’s add text boxes before our labels to allow the user to input some text. To do this, open up the Palette and search for TEdit. Add this component to your form. We will follow the same naming convention as our labels but add an Edit to the end. For example, our sepal length edit box will be named as SLengthEdit. Here is what our form looks like:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Now that our form is ready, we can add a few final touches by adding styles. To do this, download the free ebook bundle, which comes shipped with a multitude of styles that you can choose from. 

Once your ebook has been downloaded, extract the FMX styles zip in your chosen directory. Next, select the style you want to use. Here we will be using AquaGraphite.style available in the bundle.

To use this style, head to the Palette and add a TStyleBook component to your form. The placement does not matter for this component, as it will be invisible.

How To Build an Iris Flower Classification GUI App With DelphiFMX
How To Build an Iris Flower Classification GUI App With DelphiFMX

Next, double-click on the StyleBook1 component. This will open up your Style Designer. Next, click on the open button to open up a dialog box.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Now navigate to the AquaGraphite.style file in your styles directory, select your file, and click exit and save. 

Now select your form and head over to the Object Inspector. Here search for the StyleBook property. Next, select the drop-down menu and select StyleBook1. This will add style to your form.

Here is what our final form looks like:

How To Build an Iris Flower Classification GUI App With DelphiFMX

How to Put it Altogether?

Now that our form is ready, we need to add some functionality to the Predict button so that we don’t lose it when we export it in Python. To do this, double-click the button on the form. This will add an OnClick method to that button, creating a procedure in the .pas file of the form. This allows you to add unique functionality to each button when clicked.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Because the Delphi4PythonExporter does not use run-time implementation, we must add at least one comment (//) to each procedure to preserve the function when we export the form.

How To Build an Iris Flower Classification GUI App With DelphiFMX

With this, we are ready to export our project. Select Tools > Export To Python > Export Current Entire Project to export the project.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Here we will give the project the title Iris Flower Classifier App. Next, select the directory of your choosing and click on Export:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Once the export is complete, head over to the project directory. Because we only had a single form, Delphi will generate two Python files and one .pyfmx file. The IrisFlowerClassifier.py file will be used to run the application, whereas the Main.py file contains the class for the MainForm. The Main.pyfmx file contains the visual information for the MainForm. Here are the contents for each file.

IrisFlowerClassifier.py:

from delphifmx import *
from Main import Form1

def main():
    Application.Initialize()
    Application.Title = 'Iris Flower Classifier App'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Main.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.SLength = None
        self.SWidth = None
        self.PLength = None
        self.PWidth = None
        self.Result = None
        self.SLengthEdit = None
        self.SWidthEdit = None
        self.PLengthEdit = None
        self.PWidthEdit = None
        self.Predict = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def PredictClick(self, Sender):
        pass

Now, let’s begin adding functionality to our code. Start by opening up Main.py and importing the relevant libraries.

# Additional imports
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

Next, head over to the __init__ function. Here we will start by loading the Iris dataset, splitting the data set into testing and training sets, and finally, training the SVC model. Here is what our __init__ function will look like:

def __init__(self, owner):
        self.Title = None
        self.SLength = None
        self.SWidth = None
        self.PLength = None
        self.PWidth = None
        self.Result = None
        self.SLengthEdit = None
        self.SWidthEdit = None
        self.PLengthEdit = None
        self.PWidthEdit = None
        self.Predict = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Load the Iris dataset
        self.iris = load_iris()
        X, y = self.iris.data, self.iris.target

        # Split the data into training and testing sets
        X_train, _, y_train, _ = train_test_split(X, y, test_size=0.2, random_state=42)

        # Train the SVC model
        self.knn = SVC()
        self.knn.fit(X_train, y_train)

Next, lets move to the PredictButton click function. This function will only be triggered when we click on the Classify Flower button. To predict our flowers, we will first need to retrieve the values from our TEdit boxes. So we will use a try-except block so that our app does not crash.

Start by taking out the length and width values for the petal and sepal and convert them into floating point numbers inside the try block. Next, convert these values into a nested list and pass them into the classifiers predict function:

def PredictClick(self, Sender):
        # User input for flower measurements
        try:
            sepal_length = float(self.SLengthEdit.Text)
            sepal_width = float(self.SWidthEdit.Text)
            petal_length = float(self.PLengthEdit.Text)
            petal_width = float(self.PWidthEdit.Text)
            new_flower = [[sepal_length, sepal_width, petal_length, petal_width]]
            predicted_species = self.knn.predict(new_flower)

Now map the predicted label to the corresponding name of the species, and show the result in the Result label:

def PredictClick(self, Sender):
        # User input for flower measurements
        try:
            sepal_length = float(self.SLengthEdit.Text)
            sepal_width = float(self.SWidthEdit.Text)
            petal_length = float(self.PLengthEdit.Text)
            petal_width = float(self.PWidthEdit.Text)
            new_flower = [[sepal_length, sepal_width, petal_length, petal_width]]
            predicted_species = self.knn.predict(new_flower)

            # Map the predicted label to the corresponding species name
            species_names = self.iris.target_names
            predicted_species_name = species_names[predicted_species[0]]
            self.Result.Text = "Species name: {}".format(predicted_species_name.capitalize())

Finally, if any of the fields are missing, we will return an error in our Result label using the except block. Here is what our PredictClick function looks like:

def PredictClick(self, Sender):
        # User input for flower measurements
        try:
            sepal_length = float(self.SLengthEdit.Text)
            sepal_width = float(self.SWidthEdit.Text)
            petal_length = float(self.PLengthEdit.Text)
            petal_width = float(self.PWidthEdit.Text)
            new_flower = [[sepal_length, sepal_width, petal_length, petal_width]]
            predicted_species = self.knn.predict(new_flower)

            # Map the predicted label to the corresponding species name
            species_names = self.iris.target_names
            predicted_species_name = species_names[predicted_species[0]]
            self.Result.Text = "Species Name: {}".format(predicted_species_name.capitalize())
        except:
            self.Result.Text = "Error! Incomplete or invalid input fields."

Here is what our final Main.py file looks like:

import os
from delphifmx import *
# Additional imports
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.SLength = None
        self.SWidth = None
        self.PLength = None
        self.PWidth = None
        self.Result = None
        self.SLengthEdit = None
        self.SWidthEdit = None
        self.PLengthEdit = None
        self.PWidthEdit = None
        self.Predict = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))
       
        # Load the Iris dataset
        self.iris = load_iris()
        X, y = self.iris.data, self.iris.target

        # Split the data into training and testing sets
        X_train, _, y_train, _ = train_test_split(X, y, test_size=0.2, random_state=42)

        # Train the SVC model
        self.knn = SVC()
        self.knn.fit(X_train, y_train)

    def PredictClick(self, Sender):
        # User input for flower measurements
        try:
            sepal_length = float(self.SLengthEdit.Text)
            sepal_width = float(self.SWidthEdit.Text)
            petal_length = float(self.PLengthEdit.Text)
            petal_width = float(self.PWidthEdit.Text)
            new_flower = [[sepal_length, sepal_width, petal_length, petal_width]]
            predicted_species = self.knn.predict(new_flower)

            # Map the predicted label to the corresponding species name
            species_names = self.iris.target_names
            predicted_species_name = species_names[predicted_species[0]]
            self.Result.Text = "Species Name: {}".format(predicted_species_name.capitalize())
        except:
            self.Result.Text = "Error! Incomplete or invalid input fields."

Does the App Meet Expectations When Tested?

Now that our application is ready, let’s test it out. Head over to IrisFlowerClassifier.py and run the file.

How To Build an Iris Flower Classification GUI App With DelphiFMX

Let’s add a few values to our app that satisfy the values for the Setosa flower:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Finally, click on the Classify button to get the prediction:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Now, let’s test it out for another random flower:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Clicking on the Classify button, we get the prediction that our random flower is actually Verginica:

How To Build an Iris Flower Classification GUI App With DelphiFMX

Are You Ready to Create ML-Powered Apps of Your Own?

How To Build an Iris Flower Classification GUI App With DelphiFMX

Building image classification apps is both a fascinating and rewarding endeavor. It empowers developers to accurately identify and classify objects within images, opening up a world of possibilities for diverse applications. We recommend exploring the Delphi ecosystem to streamline your development journey and unlock enhanced potential. With DelphiFMX at its core, alongside Delphi IDE and Delphi4PythonExporter, you gain access to a comprehensive suite of tools and frameworks for GUI development, seamlessly integrating with Python ML backends.

Are you excited to venture into the world of flower classification apps? Download the IDE to embrace the power of Delphi and embark on an enriching journey of ML-based app development! 

What Are Some FAQs Related to this Topic?

How To Build an Iris Flower Classification GUI App With DelphiFMX

What is a Support Vector Machine (SVM)?

A Support Vector Machine is a supervised machine learning algorithm used for classification and regression tasks. It aims to find the optimal hyperplane that best separates different classes in the data.

Can SVM handle imbalanced datasets?

SVMs can be sensitive to imbalanced datasets. Techniques like class weighting or using different cost functions can be applied to address this issue.

What are the advantages of using SVM over other classifiers?

SVMs are effective in high-dimensional spaces, robust against overfitting, and have good generalization properties. They work well with both small and large datasets.

What is DelphiFMX (FireMonkey)?

DelphiFMX (FireMonkey) is a powerful cross-platform GUI (Graphical User Interface) framework provided by Embarcadero’s Delphi IDE. It enables developers to create visually stunning and responsive user interfaces for applications running on multiple platforms, such as Windows, macOS, iOS, and Android, using a single codebase.

What are the key advantages of using DelphiFMX?

DelphiFMX offers several advantages, including cross-platform support, native performance on different operating systems, access to native controls, and the ability to create visually appealing apps with rich animations and effects.

Can I use third-party components with DelphiFMX?

Yes, DelphiFMX allows developers to use third-party components and libraries to extend the functionality of their applications. This flexibility enables developers to integrate additional features and tools into their projects.

The post How To Build an Iris Flower Classification GUI App With DelphiFMX first appeared on Python GUI.

]]>
https://pythongui.org/how-to-build-an-iris-flower-classification-gui-app-with-delphifmx/feed/ 0 11083
How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem https://pythongui.org/how-to-implement-an-art-style-transfer-gui-app-with-the-python-delphi-ecosystem/ https://pythongui.org/how-to-implement-an-art-style-transfer-gui-app-with-the-python-delphi-ecosystem/#respond Thu, 24 Aug 2023 16:17:03 +0000 https://pythongui.org/?p=11041 Art Style Transfer has gained immense popularity as an exciting application of AI in the art world. This article delves into the captivating realm of AI art and how art style transfer transforms ordinary images...

The post How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem first appeared on Python GUI.

]]>
Art Style Transfer has gained immense popularity as an exciting application of AI in the art world. This article delves into the captivating realm of AI art and how art style transfer transforms ordinary images into mesmerizing pieces of art. With the help of the Delphi ecosystem, we will build an Art Style Transfer app that allows users to blend the characteristics of one artwork with another, producing visually stunning and unique results. So, let’s dive right in!

What is Art Style Transfer and Why is it Exciting?

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Art Style Transfer or more technically known as Neural Style Transfer, is a technique that uses deep neural networks to apply the artistic style of one image (the style image) to the content of another image (the content image). This process results in a new image that combines the original image’s content with the style image’s visual characteristics. It opens up a world of possibilities for creating artistic and imaginative images that blend different artistic styles seamlessly. So in this tutorial, we employ deep learning to create an image in the style of another image, a process commonly referred to as neural style transfer.

What is the Python Delphi Ecosystem Consist of?

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

The Python Delphi ecosystem consists of the Delphi IDE (Integrated Development Environment) and Delphi FMX (FireMonkey), which enable developers to build cross-platform applications with visually stunning and responsive user interfaces. Delphi FMX supports multi-platform development, allowing apps to run on Windows, macOS, iOS, and Android using a single codebase. 

Additionally, the ecosystem includes the Delphi4Python Exporter, a vital tool that facilitates the seamless integration of Python code within Delphi. This integration empowers developers to leverage Python’s vast libraries and AI capabilities while harnessing the visual prowess of Delphi FMX, offering a powerful environment for creating innovative applications, particularly in AI and machine learning domains.

How to Create an Art Style Transfer App? 

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

What Are the Prerequisites for this Art Style Transfer App?

To create our art style transfer app, ensure you have Delphi IDE and the FireMonkey GUI framework installed on your device. Moreover, you will need a text editor or IDE that supports Python, such as PyScripter, along with the Delphi4PythonExporter tool for Python integration. If you don’t have these tools already, refer to the article “Powerful Python GUI Project Setup” for guidance.

Furthermore, make sure to install the required Python libraries by running the following commands in the command prompt or terminal:

pip install pillow
pip install tensorflow
pip install tensorflow-hub

Lastly, to access the code for this tutorial, you can download it from our GitHub repository through the following link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Art_Style_Transfer_App

By meeting these prerequisites, you’ll be fully equipped to dive into the exciting world of AI art and create your own art style transfer app using the Delphi ecosystem and Python libraries.

Are there any Python Libraries for Implementing the Neural Style Transfer Algorithm?

Yes, there are Python libraries available for implementing the Neural Style Transfer algorithm. One prominent library is TensorFlow Hub. TensorFlow Hub provides pre-trained models that can be used to easily apply the optimization technique to blend a content image with a style reference image, producing an output image that adopts the reference style while preserving the original image’s content.

How to Build the User Interface with Delphi?

Let’s begin by launching the Delphi CE application and creating a new project. To achieve this, navigate to File > New > Multi-Device Application > Blank Application > Ok. For this tutorial, we’ve named our project ArtStyleTransferApp.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

If you are unfamiliar with the various sections of the Delphi IDE, we recommend consulting our complimentary eBook bundle, which covers the Delphi Python Ecosystem and provides insights into all Python GUI offerings.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Let’s begin by renaming our form. Right-click on the form and select QuickEdit. This will open up an edit box, where we will set the name of our form as MainForm with the caption Art Style Transfer App.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Now, head over to the Projects tab and rename the source file of the form from Unit1.pas to Main.pas. We are doing this to help us keep track of our forms.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Now let’s start working on our form. First, we will resize our forms by heading to the Object Inspector and searching for the ClientWidth and ClientHeight in the properties tab. We will resize our form by setting them to 624 and 640, respectively.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Next, we’ll proceed by adding a few labels to our app. Access the standard palette and locate the TLabel component. Drag and drop this component onto the form to include it. We will be adding three labels to our form. The first will be a title label, Title, displayed at the top of the form. The second and third labels, StyleImageLabel and ContentImagelabel, will be used to indicate the style image and the image to be converted.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Following that, we’ll customize the text style using the TextSettings property of each label. To do so, access the Object Inspector and search for TextSettings. Click on the ellipsis button (...) next to the Font property to explore various options for modifying the label’s appearance based on your preferences. In this case, we’ve chosen the SemiBold Segoe UI font family and distinct font sizes for each label. Additionally, we’ll set our labels’ HorzAlign and VertAlign properties to Center.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Here is what our form looks like:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Next, let’s add a few buttons to our form. For this, we will use the TButton component, so navigate to the Palette and search for the component.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

We will add two Upload buttons to our form. One button called UploadStyleButton will be used to upload a style image that will be used for reference. The second upload button that, we will name UploadContentButton will help us select the file to be converted. Finally, we will add an Apply button, ApplyButton, to run the image generation algorithm.

Next, we’ll customize the text style using the TextSettings property of each button. Here is what our form looks like:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Now, we will add two TOpenDialog components to our form. These components will help us open a dialog box to select a file from our system. So open up the Palette and search for the component. Next, drag and drop this component anywhere into your form. The placement of these components will not matter as they will be invisible.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Finally, let’s finish our forms by adding some holders showing our images. Head over to the Palette and search for the TImage component. Add three of these components to your form.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Now, right-click on each component and define its name. Here we will set the left image component under Style Image as StyleImage, the component under Content Image as ContentImage, and finally, the component at the bottom as FinalImage. Here is what our form looks like:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

With this, the functional components of our form are ready. Now we can add a few final touches to make our form more visually appealing. We will do this by downloading the free ebook bundle, which comes shipped with a multitude of styles that you can choose from. 

After downloading your free ebook, extract the FMX styles zip in your chosen directory. Next, select the style you want to use. Here we will be using Drak.style available in the bundle.

To use this style, head to the Palette and add the TStyleBook component to your form. Again, the placement does not matter for this component, as this, too, will be invisible.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem
How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Double-click on the StyleBook1 component to open up your Style Designer. Next, click on the open button to open up a dialog box.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Now navigate to the Dark.style file in your styles directory, select your file and finally click on exit.

Once you’ve finalized your style, select the MainForm and head to the Object Inspector. Here we will search for the StyleBook property. Select the drop-down menu and select StyleBook1.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Here is what our final form looks like:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

How to Integrate the Style Transfer Algorithm into the App?

Before integrating the style transfer algorithm into our app, we must export it using the Delphi4Python exporter. However, exporting right now will cause the buttons to lose their function. Therefore, we will need to add functionality to each button in the form. 

To do this, double-click on each button on the form. This will add an OnClick method to that button. The procedure will be created in the .pas file of the form. This allows you to add unique functionality to each button when clicked.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Because the Delphi4PythonExporter does not use run-time implementation, we must add at least one comment (//) to each procedure to preserve the function when we export the form.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Now that our form is ready, we are ready to export. Select Tools > Export To Python > Export Current Entire Project to export the project.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Here we will give the project the title Art Style Transfer App. Next, select the directory of your choosing and click on Export:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Because we had one form, Delphi will generate two Python files and one .pyfmx file. The ArtStyleTransferApp.py file will be used to run the application, whereas the Main.py file contains the class for the MainForm. The Main.pyfmx file contains the visual information for the MainForm. Here are the contents for each file.

KMeansClustering.py:

from delphifmx import *
from Main import MainForm

def main():
    Application.Initialize()
    Application.Title = 'Art Style Transfer App'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Main.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.StyleImageLabel = None
        self.ContentImageLabel = None
        self.UploadContentButton = None
        self.UploadStyleButton = None
        self.ApplyButton = None
        self.StyleImage = None
        self.ContentImage = None
        self.FinalImage = None
        self.OpenDialog1 = None
        self.OpenDialog2 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def UploadContentButtonClick(self, Sender):
        pass

    def UploadStyleButtonClick(self, Sender):
        pass

    def ApplyButtonClick(self, Sender):
        pass

Now, the only thing we need to do is add functionality to our form. Start by opening up Main.py in the text editor of your choice and importing some libraries:

# Additional Imports
import tensorflow as tf
import numpy as np
import PIL.Image
import tensorflow_hub as hub

Next, head over to the __init__ function. Here we will use the os library to load compressed models from tensorflow. Here is what our __init__ function looks like:

def __init__(self, owner):
        self.Title = None
        self.StyleImageLabel = None
        self.ContentImageLabel = None
        self.UploadContentButton = None
        self.UploadStyleButton = None
        self.ApplyButton = None
        self.StyleImage = None
        self.ContentImage = None
        self.FinalImage = None
        self.OpenDialog1 = None
        self.OpenDialog2 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Load compressed models from tensorflow_hub
        os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'

Now let’s define a helper function called load_img that will help us load and preprocess an image using a provided path. We will start by defining the maximum dimensions as 512 and load and convert the image data type to float32.

def load_img(self, path_to_img):
        # Function to load and preprocess an image
        max_dim = 512
        img = tf.io.read_file(path_to_img)
        img = tf.image.decode_image(img, channels=3)
        img = tf.image.convert_image_dtype(img, tf.float32)

Next, we will cast the image, reshape it and finally return it. Here is what our final load_img function looks like:

def load_img(self, path_to_img):
        # Function to load and preprocess an image
        max_dim = 512
        img = tf.io.read_file(path_to_img)
        img = tf.image.decode_image(img, channels=3)
        img = tf.image.convert_image_dtype(img, tf.float32)

        shape = tf.cast(tf.shape(img)[:-1], tf.float32)
        long_dim = max(shape)
        scale = max_dim / long_dim

        new_shape = tf.cast(shape * scale, tf.int32)

        img = tf.image.resize(img, new_shape)
        img = img[tf.newaxis, :]
        return img

Next, we will define another function called tensor_to_image which, as the name implies, will help convert a tensor image to a PIL image that we can save. Here is a simple code on how we can do that:

def tensor_to_image(self, tensor):
        # Function to convert a tensor to a PIL Image
        tensor = tensor*255
        tensor = np.array(tensor, dtype=np.uint8)
        if np.ndim(tensor) > 3:
            assert tensor.shape[0] == 1
            tensor = tensor[0]
        return PIL.Image.fromarray(tensor)

Now we can move on and finish our button functions. Head to the UploadContentButtonClick function and open a dialog box using the OpenDialog1 component. We will filter the files to only show the different image files in the dialogbox. Once the user selects the image, use the .Bitmap.LoadFromFile() method to display it in the ContentImage placeholder. Here is what our final UploadContentButtonClick function looks like:

def UploadContentButtonClick(self, Sender):
        self.OpenDialog1.Title = "Select your Content Image"

        # Filtering only image formats to show for file pick
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            # Load the selected image into ContentImage component
            self.ContentImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)

Moving on, let’s define our UploadStyleButtonClick function similarly using the OpenDialog2 component. Here is what our function looks like:

def UploadStyleButtonClick(self, Sender):
        self.OpenDialog2.Title = "Select your Style Image"

        # Filtering only image formats to show for file pick
        self.OpenDialog2.Filter = "Image files (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|All files (*.*)|*.*"
       
        if self.OpenDialog2.Execute():
            # Load the selected image into StyleImage component
            self.StyleImage.Bitmap.LoadFromFile(self.OpenDialog2.FileName)

Finally, let’s complete our ApplyButtonClick function. Start by loading our images using the load_img function:

def ApplyButtonClick(self, Sender):
        content_image = self.load_img(self.OpenDialog1.FileName)
        style_image = self.load_img(self.OpenDialog2.FileName)

Next, we will load a model using tensorflow_hub and pass in our StyleImage and ContentImage to generate a stylized image.

def ApplyButtonClick(self, Sender):
        content_image = self.load_img(self.OpenDialog1.FileName)
        style_image = self.load_img(self.OpenDialog2.FileName)

        # Load the Hub model for image stylization
        hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')
        stylized_image = hub_model(tf.constant(content_image), tf.constant(style_image))[0]
        stylized_image = self.tensor_to_image(stylized_image)

Finally, we will save the stylized image locally with a specific filename and load the image to our FinalImage component. Here is what our ApplyButtonClick function looks like:

def ApplyButtonClick(self, Sender):
        content_image = self.load_img(self.OpenDialog1.FileName)
        style_image = self.load_img(self.OpenDialog2.FileName)

        # Load the Hub model for image stylization
        hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')
        stylized_image = hub_model(tf.constant(content_image), tf.constant(style_image))[0]
        stylized_image = self.tensor_to_image(stylized_image)

        # Save the stylized image locally with a specific filename
        fname = "{}_{}_result.jpg".format(os.path.splitext(os.path.basename(self.OpenDialog1.FileName))[0], os.path.splitext(os.path.basename(self.OpenDialog2.FileName))[0])
        output_path = os.path.join(os.path.dirname(self.OpenDialog1.FileName), fname)
        stylized_image.save(output_path)
       
        # Load the stylized image into the FinalImage component
        self.FinalImage.Bitmap.LoadFromFile(output_path)

Here is what our final Main.py file looks like:

import os
from delphifmx import *
# Additional Imports
import tensorflow as tf
import numpy as np
import PIL.Image
import tensorflow_hub as hub

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.StyleImageLabel = None
        self.ContentImageLabel = None
        self.UploadContentButton = None
        self.UploadStyleButton = None
        self.ApplyButton = None
        self.StyleImage = None
        self.ContentImage = None
        self.FinalImage = None
        self.OpenDialog1 = None
        self.OpenDialog2 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Load compressed models from tensorflow_hub
        os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'

    def load_img(self, path_to_img):
        # Function to load and preprocess an image
        max_dim = 512
        img = tf.io.read_file(path_to_img)
        img = tf.image.decode_image(img, channels=3)
        img = tf.image.convert_image_dtype(img, tf.float32)

        shape = tf.cast(tf.shape(img)[:-1], tf.float32)
        long_dim = max(shape)
        scale = max_dim / long_dim

        new_shape = tf.cast(shape * scale, tf.int32)

        img = tf.image.resize(img, new_shape)
        img = img[tf.newaxis, :]
        return img
   
    def tensor_to_image(self, tensor):
        # Function to convert a tensor to a PIL Image
        tensor = tensor*255
        tensor = np.array(tensor, dtype=np.uint8)
        if np.ndim(tensor) > 3:
            assert tensor.shape[0] == 1
            tensor = tensor[0]
        return PIL.Image.fromarray(tensor)

    def UploadContentButtonClick(self, Sender):
        self.OpenDialog1.Title = "Select your Content Image"

        # Filtering only image formats to show for file pick
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            # Load the selected image into ContentImage component
            self.ContentImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)

    def UploadStyleButtonClick(self, Sender):
        self.OpenDialog2.Title = "Select your Style Image"

        # Filtering only image formats to show for file pick
        self.OpenDialog2.Filter = "Image files (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|All files (*.*)|*.*"
       
        if self.OpenDialog2.Execute():
            # Load the selected image into StyleImage component
            self.StyleImage.Bitmap.LoadFromFile(self.OpenDialog2.FileName)

    def ApplyButtonClick(self, Sender):
        content_image = self.load_img(self.OpenDialog1.FileName)
        style_image = self.load_img(self.OpenDialog2.FileName)

        # Load the Hub model for image stylization
        hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')
        stylized_image = hub_model(tf.constant(content_image), tf.constant(style_image))[0]
        stylized_image = self.tensor_to_image(stylized_image)

        # Save the stylized image locally with a specific filename
        fname = "{}_{}_result.jpg".format(os.path.splitext(os.path.basename(self.OpenDialog1.FileName))[0], os.path.splitext(os.path.basename(self.OpenDialog2.FileName))[0])
        output_path = os.path.join(os.path.dirname(self.OpenDialog1.FileName), fname)
        stylized_image.save(output_path)
       
        # Load the stylized image into the FinalImage component
        self.FinalImage.Bitmap.LoadFromFile(output_path)

Now that our application is ready, let’s test it out. Head over to ArtStyleTransferApp.py and run the file.

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Next, we will upload our style and content images by clicking the Upload buttons. Here we will be using Vincent van Gogh’s Starry Night as the Style image and a picture of penguins as our Content image.

24-2961824
Source: https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1200px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg 
How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Once you’ve selected your image, it should appear on the image placeholders:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Now press the Apply button to evaluate your image. Your result image should appear in the FinalImage placeholder:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

Your file should also be saved in the same directory as your image:

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

What Are the Key Take Aways of this Tutorial?

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

In conclusion, our Art Style Transfer app demonstrates the exciting potential of AI art and the capabilities of the Delphi ecosystem in creating innovative applications. By providing users with a simple and interactive platform for artistic expression, we encourage creativity and exploration in the field of AI-generated art.

By harnessing the fusion of Delphi’s visual capabilities and Python’s extensive libraries, the Art Style Transfer app exemplifies the exciting potential of AI in the art world. Whether you’re an experienced developer or a newcomer, embracing the Delphi ecosystem can revolutionize your app development journey.

Ready to explore the captivating realm of AI art and create your own Art Style Transfer app? Unleash your creativity and join us on this fascinating journey. Download the Delphi IDE to embark on an innovative and rewarding development experience. 

What Are Some FAQs Related to this Tutorial?

How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem

How does Neural Style Transfer work?

Using a convolutional network, neural Style Transfer works by extracting content and style reference statistics from the content and style reference images. It then optimizes an output image to match the content statistics of the content image and the style statistics of the style reference image.

What is TensorFlow Hub?

TensorFlow Hub is a Python library that provides a collection of pre-trained models and modules for various tasks, including Neural Style Transfer. It simplifies the implementation of complex algorithms by offering access to pre-trained convolutional networks and other resources.

Do I need to train the model from scratch for Neural Style Transfer?

No, one of the advantages of using TensorFlow Hub is that it provides pre-trained models for Neural Style Transfer. You can use these models directly without the need for training from scratch.

Can I adjust the intensity of style transfer in the output image?

Yes, you can adjust the intensity of style transfer by controlling the weight of the style loss during optimization. This allows you to fine-tune the artistic style of the content image.

Is Neural Style Transfer computationally intensive?

Neural Style Transfer can be computationally intensive, especially when working with large images and complex styles. However, using pre-trained models from TensorFlow Hub can significantly reduce the computation time.

Are there other libraries besides TensorFlow Hub for Neural Style Transfer?

Yes, other libraries and frameworks, such as PyTorch, offer implementations of Neural Style Transfer. Each library may have its advantages and specific use cases, so developers can choose based on their preferences and project requirements.

What programming languages are supported by Delphi?

Delphi primarily supports Object Pascal as its native programming language. However, it also provides support for C++ through the use of the C++Builder IDE.

Is Delphi suitable for beginners in programming?

Delphi is considered beginner-friendly due to its visual programming features and user-friendly IDE. It provides an excellent learning platform for newcomers to programming.

The post How To Implement an Art Style Transfer GUI App with the Python Delphi Ecosystem first appeared on Python GUI.

]]>
https://pythongui.org/how-to-implement-an-art-style-transfer-gui-app-with-the-python-delphi-ecosystem/feed/ 0 11041
How To Create a K-Means Clustering Visualization App Using DelphiFMX https://pythongui.org/how-to-create-a-k-means-clustering-visualization-app-using-delphifmx/ https://pythongui.org/how-to-create-a-k-means-clustering-visualization-app-using-delphifmx/#respond Mon, 07 Aug 2023 10:00:00 +0000 https://pythongui.org/?p=10907 In this tutorial, we will explore the powerful capabilities of DelphiFMX and delve into the fascinating realm of K-means clustering visualization. Imagine easily analyzing and visualizing data patterns, empowering users to gain valuable insights and...

The post How To Create a K-Means Clustering Visualization App Using DelphiFMX first appeared on Python GUI.

]]>
In this tutorial, we will explore the powerful capabilities of DelphiFMX and delve into the fascinating realm of K-means clustering visualization. Imagine easily analyzing and visualizing data patterns, empowering users to gain valuable insights and make data-driven decisions. Join us on this exciting journey as we build a K-means clustering visualization app using DelphiFMX, leveraging its robust features and seamless integration with the K-means algorithm.

What is Unsupervised Learning and When is it Useful?

How To Create a K-Means Clustering Visualization App Using DelphiFMX - a close-up of a screen showing some code

Unsupervised learning is a type of machine learning where the model learns patterns and structures from unlabeled data without any predefined target variable. In unsupervised learning, the goal is to discover the underlying structure or relationships within the data. Unlike supervised learning, where the model is trained on labeled data with known outputs, unsupervised learning algorithms work on unannotated data. These algorithms aim to find hidden patterns, clusters, or associations within the data.

For instance, unsupervised learning algorithms can help understand the data by identifying patterns, outliers, and relationships between variables. This exploratory analysis can provide insights into the dataset before further analysis or modeling.

Clustering algorithms, such as K-means, DBSCAN, or hierarchical clustering, group similar data points together based on their features or distances. It is valuable for customer segmentation, market research, image segmentation, and anomaly detection. More applications include dimensionality reduction, feature extraction, and anomaly detection.

Which Tools Can Be Used For Creating GUIs for AI-Related Apps?

How To Create a K-Means Clustering Visualization App Using DelphiFMX - the download pages

We will leverage DelphiFMX’s powerful components and functionality to create our K-means clustering visualization app. We will design an intuitive user interface that allows users to interact with the app and input their data. The app will then perform the K-means clustering algorithm on the provided data and visualize the resulting clusters using dynamic charts and visual elements.

Creating visualization apps can be thrilling and rewarding, especially with the right tools. Delphi FMX offers a rich ecosystem that simplifies and accelerates the development process, making it an excellent choice for creating a K-means clustering visualization app. By combining the power of Delphi FMX’s GUI development tools (such as Delphi IDE and Delphi4PythonExporter) and its seamless integration capabilities, we can unlock the full potential of the K-means algorithm and provide users with an intuitive and interactive visualization experience.

How to Create a K-Means Clustering Desktop App With a Stunning GUI?

How To Create a K-Means Clustering Visualization App Using DelphiFMX - a person looking at the IDE welcome page

What Libraries and Software Do You Need for this Tutorial?

To implement the code that utilizes the Python libraries Pillow, NumPy, OpenCV (cv2), and scikit-learn (sklearn), you need to set up some prerequisites. Firstly, ensure that you have installed Delphi Software. These tools will enable you to create the K-means app with a visually appealing user interface. Additionally, make sure to have the Delphi4PythonExporter tool installed, as it facilitates seamless integration between Delphi and Python. 

You will need a text editor or integrated development environment (IDE) that supports Python programming. We recommend using PyScripter, which provides a convenient environment for editing and executing Python code within Delphi. If you don’t have these tools installed, we recommend checking out the article “Powerful Python GUI Project Setup” to help you get started.

Lastly, to run the code successfully, install the necessary Python libraries. Execute the following commands in the command prompt or terminal:

pip install pillow
pip install opencv-python
pip install numpy
pip install scikit-learn

You can access the complete code for this tutorial from our GitHub repository. Simply visit the following link to obtain the code and related resources:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/K_Means_Clustering_App

How to Create the Back-End by Implementing K-Means With SKlearn?

Once you’ve installed the necessary libraries, we are now ready to create our own K-Means class. Start by creating a new file called KMeans.py in your project directory, import the cv2 library, and import KMeans from sklearn.

import cv2
from sklearn.cluster import KMeans

Now create a class called KMeansClustering with three functions, init, load_image, and apply:

class KMeansClustering:
    def __init__(self):
        pass
   
    def load_image(self):
        pass
   
    def apply(self):
        pass

First, let’s start by defining the init function. Head over to the function and initialize the function with an additional parameter called K. This will define the number of clusters to make in an image. Next, we will define some new variables. The self.K variable will be used to define the number of clusters, whereas self.image will be used to store our image. Here is what our init function looks like:

def __init__(self, K: int):
        self.K = K  # Number of clusters for K-means algorithm
        self.image = None  # Placeholder for the image array

Next, for the load_image function, all we need to do is load an image file from the system. To do this, we will define an additional parameter called filename and then use the .imread() method to load the image file. Here is what our load_image function looks like:

def load_image(self, filename: str):
        self.image = cv2.imread(filename)  # Load the image array using OpenCV

Finally, let’s define our apply function. We will start by converting the image in the self.image variable from the BGR color space to the RGB color space. Next, we will reshape our image to produce a 2D array of pixels:

def apply(self):
        # Convert the image from BGR color space to RGB color space
        image_rgb = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)

        # Reshape the image to a 2D array of pixels
        pixels = image_rgb.reshape(-1, 3)

Once we’ve finished reformatting our image, we will apply the KMeans clustering algorithm and assign cluster labels to each pixel to create a segmented image. Finally, we will return the newly generated image. Here is what our apply function looks like:

def apply(self):
        # Convert the image from BGR color space to RGB color space
        image_rgb = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)

        # Reshape the image to a 2D array of pixels
        pixels = image_rgb.reshape(-1, 3)

        # Apply K-means clustering algorithm
        kmeans = KMeans(n_clusters=self.K, random_state=42)
        kmeans.fit(pixels)
        labels = kmeans.labels_
        centers = kmeans.cluster_centers_

        # Assign cluster labels to each pixel in the image to create a segmented image
        segmented_image = centers[labels].reshape(image_rgb.shape)

        return segmented_image

Here is what our KMeans.py file looks like:

import cv2
from sklearn.cluster import KMeans

class KMeansClustering:
    def __init__(self, K: int):
        self.K = K  # Number of clusters for K-means algorithm
        self.image = None  # Placeholder for the image array
   
    def load_image(self, filename: str):
        self.image = cv2.imread(filename)  # Load the image array using OpenCV
   
    def apply(self):
        # Convert the image from BGR color space to RGB color space
        image_rgb = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)

        # Reshape the image to a 2D array of pixels
        pixels = image_rgb.reshape(-1, 3)

        # Apply K-means clustering algorithm
        kmeans = KMeans(n_clusters=self.K, random_state=42)
        kmeans.fit(pixels)
        labels = kmeans.labels_
        centers = kmeans.cluster_centers_

        # Assign cluster labels to each pixel in the image to create a segmented image
        segmented_image = centers[labels].reshape(image_rgb.shape)

        return segmented_image

How to Create a Stunning GUI For the App?

Now that the backend of our app is ready, we can utilize the Delphi ecosystem to create a very attractive GUI for such an ML task.
Start by opening the Delphi CE application and creating a blank project by navigating to File > New > Multi-Device Application > Blank Application > Ok. In this tutorial, we have named our project KMeansClustering.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - creating a new multi device applications

If you are not familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - the ebook

Let’s start by giving the form a name. Right-click on the form and select QuickEdit. Here, we will name our form MainForm with the caption KMeansClustering App.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - reaming the main form

Next, rename the source file of our MainForm to Main.pas. This will help us keep track of our project files. Now, let’s resize the form. So go to the Object Inspector and search for ClientWidth and ClientHeight in the properties tab. We will set them to 480 and 640, respectively.

Now, let’s add a title to our app. Navigate to the standard palette and locate the TLabel component. Drag and drop this component onto the form.

How To Create a K-Means Clustering Visualization App Using DelphiFMX selecting a TLabel

Next, right-click on the label and set the Name as Title with the Text as KMeansClustering App.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - dropping the label on the form

We will now modify the text style by using the TextSettings property of the label. We will do this by navigating to the Object Inspector and searching for TextSettings. Now, click on the ellipses button (...) next to the Font property to see options for modifying the label based on your preferences. Like our other projects, we will set our font family as SemiBold Segoe UI. In addition, we will set the HorzAlign and VertAlign properties for our labels as Center.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - changing the alignment on the form

Here is what our form looks like:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - the app in preview

Next, we will add a text field to allow the user to specify the number of clusters for the algorithm. So, head over to the Palette and search for the TEdit component. Drag and drop this component into our form. Next, right-click on the component and Name it as KValue.

Here is what our form looks like:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - running the app

Next, let’s add a few buttons to our form. For this, we will use the TButton component, so navigate to the Palette and search for the component.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - selecting a button from the palette

We will add two buttons, UploadButton, to help us select the file, and an ApplyButton, to help us apply the algorithm to our image.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - main form preview

Now, we will add a TOpenDialog component, which will help us open a dialog box to select a file from our system. Open up the Palette and search for the component. Next, drag and drop this component anywhere into your form. The placement does not matter, as this component will be invisible.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - the open dialog

Finally, let’s complete our form by adding image holders for our before and after Images. Head over to the Palette and search for the TImage component. Add this component to your form.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - TImage

Next, right-click on each component to define its name. Here we will set the left image as BeforeImage and the right image as AfterImage.

How To Create a K-Means Clustering Visualization App Using DelphiFMX 1

Now that our form is ready, let’s add a few final touches by adding style. To do this, you will need to download the free ebook bundle, which comes shipped with a multitude of styles that you can choose from. 

Start by downloading your free ebook and extracting the FMX styles zip in the directory of your choosing. Next, select the style you want to use. Here we will be using AquaGraphite.style available in the bundle.

To use this style, head to the Palette and add the TStyleBook component to your form. Again, the placement does not matter for this component.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - creating a style book
How To Create a K-Means Clustering Visualization App Using DelphiFMX - the app 2

Double-click on the StyleBook1 component to open up your Style Designer. Next, click on the open button to open up a dialog box.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - the style designer

Now navigate to the .style file of your choosing in the dialog box, select your file, and finally click on exit. 

Once you’ve finalized your style, select the MainForm and head to the Object Inspector. Here we will search for the StyleBook property. Select the drop-down menu and select StyleBook1.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - stylebook

Here is what our final form looks like:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - the styled app

How to Export These Forms to Python Code?

Now that our project is complete, we only need to export it using the Delphi4Python exporter. However, exporting right now will cause the Upload and Apply buttons to lose their function. Therefore, we will need to add some functionality to each button in the form. 

To do this, double-click on each button on the form. This will add an OnClick method to that button. The procedure will be created in the .pas file of the form. This allows you to add unique functionality to each button when clicked.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - code

Because the Delphi4PythonExporter does not use run-time implementation, we must add at least one comment (//) to each procedure to preserve the function when we export the form.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - commenting out the button click code

Now that our form is ready, we are ready to export. Select Tools > Export To Python > Export Current Entire Project to export the project.

How To Create a K-Means Clustering Visualization App Using DelphiFMX - exporting the app to Python

Here we will give the project the title KMeansClustering App. Next, select the directory of your choosing and click on Export:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - exporting the project

Because we had one form, Delphi will generate two Python files and one .pyfmx file. The KMeansClustering.py file will be used to run the application, whereas the Main.py file contains the class for the MainForm. The Main.pyfmx file contains the visual information for the MainForm. Here are the contents for each file.

KMeansClustering.py:

from delphifmx import *
from Main import MainForm

def main():
    Application.Initialize()
    Application.Title = 'KMeansClustering App'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Main.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.KValue = None
        self.KLabel = None
        self.ApplyButton = None
        self.UploadButton = None
        self.OpenDialog1 = None
        self.BeforeImage = None
        self.AfterImage = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def ApplyButtonClick(self, Sender):
        pass

    def UploadButtonClick(self, Sender):
        pass

How to Put it All Together Into a Fully Functional App? 

Now that we have exported our project, all we need to do is bring it all together. Let’s start by opening up Main.py in the text editor of your choice and importing some libraries:

# Additional Imports
from KMeans import KMeansClustering
from PIL import Image
import numpy as np

Next, let’s complete our UploadButton. Head over to the UploadButtonClick function and start by opening the file picker dialog box and filtering the files to show only the image files. Once the user selects the image, use the .Bitmap.LoadFromFile() method to display it in the BeforeImage placeholder. Our final UploadButtonClick function looks like:

def UploadButtonClick(self, Sender):
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show for file pick
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.webp)|*.jpg;*.jpeg;*.png;*.webp|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            # Load the selected image into BeforeImage
            self.BeforeImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)

Next, let’s define our ApplyButtonClick function. Start by creating an instance of our KMeansClustering class and initialize it with the K value from the KValue edit box. Next, load the image using the load_image method and apply the Kmeans clustering algorithm:

def ApplyButtonClick(self, Sender):
        # Create an instance of KMeansClustering
        kmeans = KMeansClustering(int(self.KValue.Text))

        # Load the image from the stream in KMeansClustering
        kmeans.load_image(self.OpenDialog1.FileName)

        # Apply K-means clustering
        segmented_image = kmeans.apply()

Now, simply convert the segmented image to a PIL Image and save the image in the same directory as the before image. Finally, show the image in the AfterImage placeholder. Here is what our ApplyButtonClick function looks like:

def ApplyButtonClick(self, Sender):
        # Create an instance of KMeansClustering
        kmeans = KMeansClustering(int(self.KValue.Text))

        # Load the image from the stream in KMeansClustering
        kmeans.load_image(self.OpenDialog1.FileName)

        # Apply K-means clustering
        segmented_image = kmeans.apply()

        # Convert the segmented image array to PIL Image
        pil_image = Image.fromarray(segmented_image.astype(np.uint8))

        # Save the image to the same directory as the before image
        output_path = os.path.join(os.path.dirname(self.OpenDialog1.FileName), "segmented_image.png")
        pil_image.save(output_path)

        # Load the segmented image in the AfterImage
        self.AfterImage.Bitmap.LoadFromFile(output_path)

Here is what our final Main.py file looks like:

import os
from delphifmx import *
# Additional Imports
from KMeans import KMeansClustering
from PIL import Image
import numpy as np


class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.KValue = None
        self.KLabel = None
        self.ApplyButton = None
        self.UploadButton = None
        self.OpenDialog1 = None
        self.BeforeImage = None
        self.AfterImage = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def ApplyButtonClick(self, Sender):
        # Create an instance of KMeansClustering
        kmeans = KMeansClustering(int(self.KValue.Text))

        # Load the image from the stream in KMeansClustering
        kmeans.load_image(self.OpenDialog1.FileName)

        # Apply K-means clustering
        segmented_image = kmeans.apply()

        # Convert the segmented image array to PIL Image
        pil_image = Image.fromarray(segmented_image.astype(np.uint8))

        # Save the image to the same directory as the before image
        output_path = os.path.join(os.path.dirname(self.OpenDialog1.FileName), "segmented_image.png")
        pil_image.save(output_path)

        # Load the segmented image in the AfterImage
        self.AfterImage.Bitmap.LoadFromFile(output_path)

    def UploadButtonClick(self, Sender):
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show for file pick
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.webp)|*.jpg;*.jpeg;*.png;*.webp|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            # Load the selected image into BeforeImage
            self.BeforeImage.Bitmap.LoadFromFile(self.OpenDialog1.FileName)

Now that our application is ready, let’s test it out. Head over to KMeansClustering.py and run the file.

How To Create a K-Means Clustering Visualization App Using DelphiFMX app 3

Let’s first define the KValue as 3. Next, press the Upload button. This will open up a dialog box for your to select an image. Navigate to the directory of your image and open your image. Here we will be using a free stock image from Unsplash:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - example image
Source: https://images.unsplash.com/photo-1600716051809-e997e11a5d52?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=850&q=80

Once you’ve selected your image, it should appear on the BeforeImage placeholder:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - the running app

Now press the Apply button to evaluate your image. Your result image should appear in the AfterImage placeholder:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - running app 2

Your file should also be saved in the same directory as your image:

How To Create a K-Means Clustering Visualization App Using DelphiFMX - running app 3

Are You Ready to Create More Amazing GUIs With Delphi FMX?

How To Create a K-Means Clustering Visualization App Using DelphiFMX - a man holding a laptop and smiling at the display

In this tutorial, we have embarked on an exciting journey of creating a K-means clustering visualization app using Delphi FMX. We have explored the powerful capabilities of Delphi FMX and its seamless integration with the K-means algorithm, enabling us to develop an intuitive and interactive app. By empowering users with the ability to visualize and analyze their data, we can unlock valuable insights and make data-driven decisions. 

Download Delphi and start your journey into the world of K-means clustering visualization with Delphi FMX and transform how you analyze and understand data.

What Are the Top FAQs Related to this Tutorial?

How To Create a K-Means Clustering Visualization App Using DelphiFMX an image of a person with a laptop. Their web browser is looking at the FAQ page

What is K-means clustering?

K-means clustering is an unsupervised machine learning algorithm that groups similar data points into clusters based on their feature similarity. It aims to minimize the sum of squared distances between the data points and their cluster centroids.

Why use Delphi for building a K-means clustering app?

Delphi is a powerful development platform that provides a rich ecosystem and GUI framework, such as FireMonkey (FMX), for creating visually appealing and interactive applications. It seamlessly integrates with Python, enabling you to leverage Python’s machine learning libraries and algorithms.

What is Delphi FMX?

Delphi FMX (FireMonkey) is a cross-platform GUI framework provided by Delphi. It allows you to develop visually stunning user interfaces with a single codebase that can run on multiple platforms, including Windows, macOS, iOS, and Android.

How can I integrate the K-means algorithm with Delphi FMX?

Delphi FMX integrates with Python through tools like the Delphi4PythonExporter, allowing you to write and execute Python code within your Delphi application. You can use Python’s scikit-learn library to implement the K-means algorithm and leverage its clustering capabilities.

Are there any specific data requirements for K-means clustering?

K-means clustering works with numerical data and requires a predefined number of clusters (K). Ensure your data is suitable for clustering by preprocessing it and selecting an appropriate value for K based on your specific application and dataset.

The post How To Create a K-Means Clustering Visualization App Using DelphiFMX first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-k-means-clustering-visualization-app-using-delphifmx/feed/ 0 10907
Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-long-short-term-memory-networks/ https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-long-short-term-memory-networks/#respond Mon, 24 Jul 2023 10:00:00 +0000 https://pythongui.org/?p=10844 In order to solve complicated issues, deep learning algorithms need enormous volumes of data and computational power. They can operate with nearly any form of data. The Long-Short-Term Memory Networks (LSTM), one of the most...

The post Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks first appeared on Python GUI.

]]>
In order to solve complicated issues, deep learning algorithms need enormous volumes of data and computational power. They can operate with nearly any form of data. The Long-Short-Term Memory Networks (LSTM), one of the most well-known deep learning techniques, will now be examined in-depth, in this article.

What is Deep Learning?

Deep learning, a branch of machine learning, addresses intricate problems through the utilization of artificial neural networks. These networks consist of interconnected nodes organized in multiple layers, extracting features from input data. Extensive datasets are employed to train these models, enabling them to identify patterns and correlations that might be challenging or impossible for humans to perceive.

The impact of deep learning on artificial intelligence has been substantial. It has paved the way for the development of intelligent systems capable of independent learning, adaptation, and decision-making. Deep learning has led to remarkable advancements in various domains, encompassing image and speech recognition, natural language processing, machine translation, autonomous driving, and numerous others.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - diagram
An example of LSTM’s advanced architecture: GNMT (Google’s Neural Machine Translation) system. Read more on Reference [10].

Why Use Python for Deep Learning, Machine Learning, and Artificial Intelligence?

Python has gained widespread popularity as a programming language due to its versatility and ease of use in diverse domains of computer science, especially in the field of deep learning, machine learning, and AI. 

We’ve reviewed several times about why Python is great for Deep Learning, Machine Learning, and Artificial Intelligence (also all the prerequisites), in the following articles:

What is a Long-Short-Term Memory Network (LSTM)?

Long Short-Term Memory (LSTM) networks are a modified version of recurrent neural networks, which makes it easier to remember past data in memory.  LSTM is introduced to solve the performance degradation of RNNs in long-term sequences (vanishing gradient problem). Read more about it from Hochreiter, S., & Schmidhuber, J. paper (reference [4]).

LSTM is well-suited to classify, process, and predict time series given time lags of unknown duration. It trains the model by using back-propagation. In an LSTM network, three gates are present: The input gate, forget gate, and the output gate.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - LTSM architecture diagram
LSTM architecture. Image source: Reference [2].

I’ve talked a little bit about LSTM as an advanced RNN architectures, as well as GRU, in the previous deep learning article:

How does LSTM work for Machine Translation?

Sequence to Sequence modeling is one of the many intriguing uses of natural language processing. Both language translation systems and question-answering systems make extensive use of it.

The goal of sequence-to-sequence (Seq2Seq) modeling is to develop models that can convert sequences from one domain to another, such as translating English to German. The LSTM encoder and decoder execute this Seq2Seq modeling [7].

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - diagram 2

Here’s how it works:

  • Feed the embedding vectors for source sequences (German), to the encoder network, one word at a time.
  • Encode the input sentences into fixed-dimension state vectors. At this step, we get the hidden and cell states from the encoder LSTM and feed it to the decoder LSTM.
  • These states are regarded as initial states by the decoder. Additionally, it also has embedding vectors for target words (English).
  • Decode and output the translated sentence, one word at a time. In this step, the output of the decoder is sent to a softmax layer over the entire target vocabulary.

A typical seq2seq model has 2 major components: An encoder, and a decoder. Both these parts are essentially two different recurrent neural network (RNN) models combined into one giant network:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - diagram 3

How do I build and train an LSTM for Machine Translation from scratch?

Let’s get hands-on with some Python code to build and train your own LSTMs from scratch.

In this article, we will create a language translation model using seq2seq architecture and LSTM network, as it is a very famous application of neural machine translation (including Google Translate). Brace yourself, this article is a little bit more intense, compared to all my previous tutorials.

We will work with the Kaggle Bilingual Sentence Pairs dataset (reference [3]) to train the LSTM, so it can predict the unseen data, or even more, perform machine translation. The original source of the dataset is the Tatoeba Project (to download the dataset, see Reference [1 & 3]).

The actual data contains over 150,000 sentence pairs. However, we will use only the first 50,000 sentence pairs in the 1st demo, and the first 20,000 sentence pairs in the 2nd demo to reduce the training time of the model,  (of course, this will lead to not-really-satisfying results, but this article will still serve its purpose as proof-of-concept). You can increase this number if you are equipped with a powerful computer.

Hands-on and selected outputs (1st example)

This example is modified from reference [5]. The original reference already shows excellent results when predicting the unseen data in English. However, I modified the code slightly, so we can test it to predict the unseen data in German.

The following is the code example of implementing LSTM for machine translation:

# Import libraries
import string
import re
from numpy import array, argmax, random, take
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, LSTM, Embedding, RepeatVector
from keras.preprocessing.text import Tokenizer
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.sequence import pad_sequences
from keras.models import load_model
from keras import optimizers
import matplotlib.pyplot as plt

pd.set_option('display.max_colwidth', 200)

# Function to read raw text file
def read_text(filename):
    # open the file
    file = open(filename, mode='rt', encoding='utf-8')

    # read all text
    text = file.read()
    file.close()
    return text

# Split a text into sentences
def to_lines(text):
    sents = text.strip().split('n')
    sents = [i.split('t') for i in sents]
    return sents

# Load dataset
data = read_text("data/bilingual-sentence-pairs/deu.txt")
deu_eng = to_lines(data)
deu_eng = array(deu_eng)
## We will use only the first 50,000 sentence pairs to reduce the training time of the model
deu_eng = deu_eng[:50000,:]

# Remove punctuation
deu_eng[:,0] = [s.translate(str.maketrans('', '', string.punctuation)) for s in deu_eng[:,0]]
deu_eng[:,1] = [s.translate(str.maketrans('', '', string.punctuation)) for s in deu_eng[:,1]]

deu_eng

# Convert text to lowercase
for i in range(len(deu_eng)):
    deu_eng[i,0] = deu_eng[i,0].lower()
    deu_eng[i,1] = deu_eng[i,1].lower()

# Empty lists
eng_l = []
deu_l = []

# Populate the lists with sentence lengths
for i in deu_eng[:,0]:
    eng_l.append(len(i.split()))

for i in deu_eng[:,1]:
    deu_l.append(len(i.split()))
## Plot the distributions
import pylab as pl
length_df = pd.DataFrame({'eng':eng_l, 'deu':deu_l})
length_df.hist(bins = 30)
pl.suptitle("Distributions of sentence lengths (eng vs deu)")
plt.show()
## Find the max sentence length for each language
max_eng_sentence_length = max(length_df['eng'])
max_deu_sentence_length = max(length_df['deu'])
print('Max sentence length for eng: %d' % max_eng_sentence_length)
print('Max sentence length for deu: %d' % max_deu_sentence_length)

# Function to build a tokenizer
def tokenization(lines):
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(lines)
    return tokenizer

# Prepare english tokenizer
eng_tokenizer = tokenization(deu_eng[:, 0])
eng_vocab_size = len(eng_tokenizer.word_index) + 1
## Choose "7" as the max sentence length
eng_length = 7
print('English Vocabulary Size: %d' % eng_vocab_size)

# Prepare Deutch tokenizer
deu_tokenizer = tokenization(deu_eng[:, 1])
deu_vocab_size = len(deu_tokenizer.word_index) + 1
## Choose "7" as the max sentence length
deu_length = 7
print('Deutch Vocabulary Size: %d' % deu_vocab_size)

# Encode and pad sequences
def encode_sequences(tokenizer, length, lines):
    seq = tokenizer.texts_to_sequences(lines)
    ## Pad sequences with 0 values
    seq = pad_sequences(seq, maxlen=length, padding='post')
    return seq

# Model building
from sklearn.model_selection import train_test_split
## Split data into train and test set
train, test = train_test_split(deu_eng, test_size=0.2, random_state = 12)

# Prepare training data
trainX = encode_sequences(deu_tokenizer, deu_length, train[:, 1])
trainY = encode_sequences(eng_tokenizer, eng_length, train[:, 0])

# Prepare validation data
testX = encode_sequences(deu_tokenizer, deu_length, test[:, 1])
testY = encode_sequences(eng_tokenizer, eng_length, test[:, 0])

# Define the model
## Build NMT model
def define_model(in_vocab,out_vocab, in_timesteps,out_timesteps,units):
    model = Sequential()
    model.add(Embedding(in_vocab, units, input_length=in_timesteps, mask_zero=True))
    model.add(LSTM(units))
    model.add(RepeatVector(out_timesteps))
    model.add(LSTM(units, return_sequences=True))
    model.add(Dense(out_vocab, activation='softmax'))
    return model
## Model compilation
model = define_model(deu_vocab_size, eng_vocab_size, deu_length, eng_length, 512)
rms = optimizers.RMSprop(lr=0.001)
model.compile(optimizer=rms, loss='sparse_categorical_crossentropy')

# Fit the model
## Save the model with the lowest validation loss
filename = 'model.h1.28_may_23'
checkpoint = ModelCheckpoint(filename, monitor='val_loss', verbose=1, save_best_only=True, mode='min')

# Train model
history = model.fit(trainX, trainY.reshape(trainY.shape[0], trainY.shape[1], 1),
                	epochs=30, batch_size=512, validation_split = 0.2,callbacks=[checkpoint],
                	verbose=1)
## Plot validation loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['train','validation'])
plt.show()

# Prediction on unseen data
from keras.models import load_model
model = load_model('model.h1.28_may_23')
preds = model.predict_classes(testX.reshape((testX.shape[0],testX.shape[1])))

# Present the results in dataframe (eng)
def get_word(n, tokenizer):
    for word, index in tokenizer.word_index.items():
        if index == n:
            return word
    return None

preds_text_eng = []
for i in preds:
    temp = []
    for j in range(len(i)):
        t = get_word(i[j], eng_tokenizer)
        if j > 0:
            if (t == get_word(i[j-1], eng_tokenizer)) or (t == None):
                temp.append('')
            else:
                temp.append(t)
        else:
            if(t == None):
                temp.append('')
            else:
                temp.append(t)

    preds_text_eng.append(' '.join(temp))

pred_df_eng = pd.DataFrame({'actual' : test[:,0], 'predicted' : preds_text_eng})
## Print 15 rows randomly
print(pred_df_eng.head(15))

# Present the results in dataframe (deu)
def get_word(n, tokenizer):
    for word, index in tokenizer.word_index.items():
        if index == n:
            return word
    return None

preds_text_deu = []
for i in preds:
    temp = []
    for j in range(len(i)):
        t = get_word(i[j], deu_tokenizer)
        if j > 0:
            if (t == get_word(i[j-1], deu_tokenizer)) or (t == None):
                temp.append('')
        	else:
                temp.append(t)
        else:
            if(t == None):
                temp.append('')
        	else:
                temp.append(t)

    preds_text_deu.append(' '.join(temp))

pred_df_deu = pd.DataFrame({'actual' : test[:,1], 'predicted' : preds_text_deu})
## Print 15 rows randomly
print(pred_df_deu.head(15))

To execute the code provided, we can utilize the PyScripter IDE. Here are a few selected outputs:

1. Visualizing the distribution of sentence lengths (eng vs deu)

We will generate a plot to illustrate the distribution of sentence lengths. For this purpose, we will store the lengths of all English sentences in one list and the lengths of all German sentences in another.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - visualizing

2. Maximum sentence length and vocabulary size (eng vs deu)

It is quite intuitive that the maximum length of German sentences is 15, whereas for English phrases, it is 7.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - the maximum sentence length

To facilitate the utilization of a Seq2Seq model, it is necessary to convert both input and output sentences into fixed-length integer sequences. To achieve this, we employ the Tokenizer() class from Keras, which transforms our sentences into sequences of integers. These sequences are then padded with zeros to ensure uniform length across all sequences.

In order to prepare for this process, we create tokenizers for both German and English sentences. At the same time, we also counted the vocabulary size for both languages and printed them out as can be seen above.

3. Model training and saving the best result

For the training process, we will run the model for 30 epochs, utilizing a batch_size of 512 and a validation_split of 20%. This means that 80% of the data will be allocated for training the model, while the remaining 20% will be used for evaluation. Feel free to experiment and modify these hyperparameters to suit your needs.

To ensure that we capture the model’s best performance, we will employ the ModelCheckpoint() function, which saves the model with the lowest validation loss (val_loss). The resulting model with the best performance will be automatically stored in the “model.h1.28_may_23” folder.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - code 1
Here is the validation loss score for each epoch:

Epoch-01:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 1

Epoch-02:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 2

Epoch-03:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 3

Epoch-04:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 4

Epoch-05:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 5

Epoch-06:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 6

Epoch-07:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 7

Epoch-08:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 8

Epoch-09:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 9

Epoch-10:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 10

Epoch-11:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 11

Epoch-12:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 12

Epoch-13:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 13

Epoch-14:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 14

Epoch-15:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 15

Epoch-16:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 16

Epoch-17:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 17

Epoch-18:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 18

Epoch-19:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 19

Epoch-20:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 20

Epoch-21:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 21

Epoch-22:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 22

Epoch-23:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 23

Epoch-24:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 24

Epoch-25:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 25

Epoch-26:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 26

Epoch-27:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 27

Epoch-28:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 28

Epoch-29:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 29

Epoch-30:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch 30

The model training processes are executed flawlessly within the PyScripter IDE, ensuring a smooth and error-free experience without any delays or disruptions.

4. Plot train loss vs validation loss

Let’s plot and compare the training loss and the validation loss.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - plotting the loss

As you can see in the plot above, the validation loss plateaus after the 20th epoch, indicating that the model has likely converged and will not improve further with additional training.

5. Generating predictions for unseen data

The generated predictions consist of sequences represented by integers. To make these predictions more understandable, we must convert these integers back into their respective words.

Once the conversion is complete and the original sentences are placed in the test dataset while the predicted sentences are stored in a data frame, we can randomly display some instances of actual sentences compared to their corresponding predicted sentences. This allows us to assess the performance of our model:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - a code example

Prediction results (eng):

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - prediction results

For the English results, the model is doing a pretty decent job. 

Let’s do similar things for Deutsch, and here are the prediction results (deu):

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - Deutsch

Unfortunately, the predictions for Deutsch are still unsatisfactory, and in some cases, completely incorrect. For instance, the model failed to identify that “Boston” refers to a city and “Tom” is a person’s name. To identify these errors, you can cross-reference them using Google Translator.

Eventually, after enough training epochs, using more training data and building a better (or more complex) model (if you have enough computational power to do so), the results will gradually improve over time. These are the challenges we will face regularly in NLP. But these aren’t immovable obstacles.

This is how you would use LSTM to solve a sequence prediction task. Let’s try another scenario of implementation, in the next subsection.

Hands-on and selected outputs (2nd example)

This second implementation scenario refers to Reference [7]. But, that excellent blog post is implementing the neural machine translation from English to French. In this article, we will try English to Deutsch, instead. 

In this 2nd example of LSTM implementation for machine translation, we still use the same dataset, but, for the word embedding, we will utilize the GloVe (Global Vectors for Word Representation) word embeddings (see reference [8]).

The following is the second example of implementing LSTM for machine translation:

# Import libraries
import os
import sys
from keras.models import Model
from keras.layers import Input, LSTM, GRU, Dense, Embedding
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
from numpy import array # For loading GloVe data
from numpy import asarray # For loading GloVe data
from numpy import zeros # For loading GloVe data
from keras.utils import plot_model # For plotting DL models

# Set values for different parameters
BATCH_SIZE = 64
EPOCHS = 30
LSTM_NODES = 256
NUM_SENTENCES = 20000
MAX_SENTENCE_LENGTH = 50
MAX_NUM_WORDS = 20000
EMBEDDING_SIZE = 100

# Data preprocessing
input_sentences = []
output_sentences = []
output_sentences_inputs = []

count = 0
for line in open("data/bilingual-sentence-pairs/deu.txt", encoding="utf-8"):
    count += 1

    if count > NUM_SENTENCES:
        break

    if 't' not in line:
        continue

    input_sentence, output, _ = line.rstrip().split('t')

    output_sentence = output + ' <eos>'
    output_sentence_input = '<sos> ' + output

    input_sentences.append(input_sentence)
    output_sentences.append(output_sentence)
    output_sentences_inputs.append(output_sentence_input)

print("num samples input:", len(input_sentences))
print("num samples output:", len(output_sentences))
print("num samples output input:", len(output_sentences_inputs))

# Randomly print sentences
print(input_sentences[172])
print(output_sentences[172])
print(output_sentences_inputs[172])

# Tokenization (for inputs)
input_tokenizer = Tokenizer(num_words=MAX_NUM_WORDS)
input_tokenizer.fit_on_texts(input_sentences)
input_integer_seq = input_tokenizer.texts_to_sequences(input_sentences)

word2idx_inputs = input_tokenizer.word_index
print('Total unique words in the input: %s' % len(word2idx_inputs))

max_input_len = max(len(sen) for sen in input_integer_seq)
print("Length of longest sentence in input: %g" % max_input_len)

# Tokenization (for outputs)
output_tokenizer = Tokenizer(num_words=MAX_NUM_WORDS, filters='')
output_tokenizer.fit_on_texts(output_sentences + output_sentences_inputs)
output_integer_seq = output_tokenizer.texts_to_sequences(output_sentences)
output_input_integer_seq = output_tokenizer.texts_to_sequences(output_sentences_inputs)

word2idx_outputs = output_tokenizer.word_index
print('Total unique words in the output: %s' % len(word2idx_outputs))

num_words_output = len(word2idx_outputs) + 1
max_out_len = max(len(sen) for sen in output_integer_seq)
print("Length of longest sentence in the output: %g" % max_out_len)

# Padding
encoder_input_sequences = pad_sequences(input_integer_seq, maxlen=max_input_len)
print("encoder_input_sequences.shape:", encoder_input_sequences.shape)
print("encoder_input_sequences[172]:", encoder_input_sequences[172])
## Verify the integer values for "go" and "away" (sentence index 172)
print(word2idx_inputs["go"])
print(word2idx_inputs["away"])
## In the same way, padd the decoder outputs and the decoder inputs (deu):
decoder_input_sequences = pad_sequences(output_input_integer_seq, maxlen=max_out_len, padding='post')
print("decoder_input_sequences.shape:", decoder_input_sequences.shape)
print("decoder_input_sequences[172]:", decoder_input_sequences[172])
### Print the corresponding integers from the word2idx_outputs (sentence index 172)
print(word2idx_outputs["<sos>"])
print(word2idx_outputs["mach"])
print(word2idx_outputs["’ne"])
print(word2idx_outputs["fliege!"])

# Create word embeddings for the inputs by load the GloVe word vectors into memory
embeddings_dictionary = dict()

glove_file = open("data/glove/glove.6B.100d.txt", encoding="utf-8")

for line in glove_file:
    records = line.split()
    word = records[0]
    vector_dimensions = asarray(records[1:], dtype='float32')
    embeddings_dictionary[word] = vector_dimensions
glove_file.close()

## Create a matrix where the row number will represent the integer value for the word and the columns will correspond to the dimensions of the word
num_words = min(MAX_NUM_WORDS, len(word2idx_inputs) + 1)
embedding_matrix = zeros((num_words, EMBEDDING_SIZE))
for word, index in word2idx_inputs.items():
    embedding_vector = embeddings_dictionary.get(word)
    if embedding_vector is not None:
        embedding_matrix[index] = embedding_vector
## Print the word embeddings for the word "go" using the GloVe word embedding dictionary.
print(embeddings_dictionary["go"])
print(embedding_matrix[20])
## Creates the embedding layer for the input
embedding_layer = Embedding(num_words, EMBEDDING_SIZE, weights=[embedding_matrix], input_length=max_input_len)

# Create the model
## The final shape of the output: (number of inputs, length of the output sentence, the number of words in the output)
## Creates the empty output array:
decoder_output_sequences = []  # Define decoder_output_sequences variable

for seq in output_integer_seq:
    decoder_output_sequences.append(seq[1:])  # Remove the first element "<sos>"

decoder_targets_one_hot = np.zeros((
    len(input_sentences),
    max_out_len,
    num_words_output
), dtype='float32')
## Prints the shape of the decoder:
print(decoder_targets_one_hot.shape)
## To make predictions, the final layer of the model will be a dense layer, therefore we need the outputs in the form of one-hot encoded vectors.
for i, d in enumerate(decoder_output_sequences):
    for t, word in enumerate(d):
        decoder_targets_one_hot[i, t, word] = 1
## Create the encoder for LSTM:
encoder_inputs_placeholder = Input(shape=(max_input_len,))
x = embedding_layer(encoder_inputs_placeholder)
encoder = LSTM(LSTM_NODES, return_state=True)

encoder_outputs, h, c = encoder(x)
encoder_states = [h, c]
## Create the decoder for LSTM:
decoder_inputs_placeholder = Input(shape=(max_out_len,))

decoder_embedding = Embedding(num_words_output, LSTM_NODES)
decoder_inputs_x = decoder_embedding(decoder_inputs_placeholder)

decoder_lstm = LSTM(LSTM_NODES, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs_x, initial_state=encoder_states)
## Pass the output from the decoder LSTM through a dense layer, to predict decoder outputs
decoder_dense = Dense(num_words_output, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

# Compile the model
model = Model([encoder_inputs_placeholder,
           	decoder_inputs_placeholder], decoder_outputs)
model.compile(
	optimizer='rmsprop',
	loss='categorical_crossentropy',
	metrics=['accuracy']
)
## Plot our model
plot_model(model, to_file='plot_LSTMModelForMachineTranslation.png', show_shapes=True, show_layer_names=True)

# Train the model using the fit() method:
r = model.fit(
	[encoder_input_sequences, decoder_input_sequences],
	decoder_targets_one_hot,
	batch_size=BATCH_SIZE,
	epochs=EPOCHS,
	validation_split=0.1,
)

# Modifying the model for predictions
## The encoder model remains the same:
encoder_model = Model(encoder_inputs_placeholder, encoder_states)
## Modify our model to accept the hidden and cell states
decoder_state_input_h = Input(shape=(LSTM_NODES,))
decoder_state_input_c = Input(shape=(LSTM_NODES,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
## At each time step, there will be only single word in the decoder input, we need to modify the decoder embedding layer as follows:
decoder_inputs_single = Input(shape=(1,))
decoder_inputs_single_x = decoder_embedding(decoder_inputs_single)
## Create the placeholder for decoder outputs:
decoder_outputs, h, c = decoder_lstm(decoder_inputs_single_x, initial_state=decoder_states_inputs)
## To make predictions, the decoder output is passed through the dense layer:
decoder_states = [h, c]
decoder_outputs = decoder_dense(decoder_outputs)
## The final step is to define the updated decoder model, as shown here:
decoder_model = Model(
	[decoder_inputs_single] + decoder_states_inputs,
	[decoder_outputs] + decoder_states
)
## Plot our modified decoder LSTM that makes predictions:
plot_model(decoder_model, to_file='plot_modifiedLSTMModelForMachineTranslation.png', show_shapes=True, show_layer_names=True)

# Making predictions
## Create new dictionaries for both inputs and outputs where the keys will be the integers and the corresponding values will be the words:
idx2word_input = {v:k for k, v in word2idx_inputs.items()}
idx2word_target = {v:k for k, v in word2idx_outputs.items()}

## Create translate_sentence() method to accept an input-padded sequence English sentence (in the integer form) and will return the translated French sentence.
def translate_sentence(input_seq):
    states_value = encoder_model.predict(input_seq)
    target_seq = np.zeros((1, 1))
    target_seq[0, 0] = word2idx_outputs['<sos>']
    eos = word2idx_outputs['<eos>']
    output_sentence = []

    for _ in range(max_out_len):
        output_tokens, h, c = decoder_model.predict([target_seq] + states_value)
        idx = np.argmax(output_tokens[0, 0, :])

        if eos == idx:
            break

        word = ''

        if idx > 0:
            word = idx2word_target[idx]
            output_sentence.append(word)

        target_seq[0, 0] = idx
        states_value = [h, c]

    return ' '.join(output_sentence)

# Testing the model
i = np.random.choice(len(input_sentences))
input_seq = encoder_input_sequences[i:i+1]
translation = translate_sentence(input_seq)
print('-')
print('Input:', input_sentences[i])
print('Response:', translation)

Let’s run the above code using PyScripter IDE. And the following are some selected outputs:

1. Word embeddings

This part shows the implementation of word embeddings for neural machine translation.Here is the printed result of the word embeddings for the word “go” using the GloVe word embedding dictionary.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - word embeddings

check the 20th index of the word embedding matrix (the word “go”), and its shows a consistent result:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - epoch an embedded matrix

2. Plot our LSTM model for machine translation

Another interesting part of this second approach is, after we compile the model, we can plot it using tf.keras.utils.plot_model. So, we can keep tracking and communicate about all the inputs, outputs, steps, layers, etc clearly.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - keras model

3. Plot the modified model for prediction

Before making any predictions, first, we need to modify our model.

The following is the plot of our model after some modification performed to make predictions:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - plot modified model for prediction

4. Train the model

I trained the model in 30 epochs, you can modify the number of epochs to see if you can get better results. The model is trained on 18,000 sentences and tested on the remaining 2,000 sentences. You can also add the number of records if you want to get better results, and if you have capable computational resources.

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - training the model
Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - training

5. Test the model

To test the code, we will randomly choose a sentence from the input_sentences list, retrieve the corresponding padded sequence for the sentence, and will pass it to the translate_sentence() method. The method will return the translated sentence as shown below.

1st attempt of the test:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - testing

2nd attempt:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - testing 2

3rd attempt:

Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks - testing 3

Again, it seems that the results in Deutsch are still far from satisfying. To identify these errors, you can cross-reference them using Google Translator. 

Eventually, after enough training epochs, using more training data and building a better (or more complex) model (if you have enough computational power to do so), will give better and better results over time. These are the challenges we will face regularly in NLP.

Endnotes

LSTMs are a very promising solution to sequence-related problems. It has tons of very useful implementations out there, from time series prediction, weather forecasting, machine translation, speech recognition, and many more. According to Google Scholar, no other computer science paper of the 20th century is receiving as many citations per year as the original 1997 journal publication on Long Short-Term Memory (LSTM) artificial neural networks (NNs) [9]. 

However, the one disadvantage that I find about them is the difficulty in training them. A lot of data, training epochs/time, and system resources are needed to go into training even a simple model. But that is just a hardware constraint, and PyScripter IDE handles it very well, lightweight, with zero error or lag! 

I hope this article was successful in giving you a basic understanding and workflow of how these networks work.

Check out the full repository here:

github.com/Embarcadero/DL_Python03_LSTM


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL, which makes it simple to create Windows GUIs with Python.


References & further readings

[1] All sentences and translations are from Tatoeba’s (tatoeba.org) massive and awesome dataset, released under a CC-BY License.

[2] Biswal, A. (2023).

Top 10 Deep Learning Algorithms You Should Know in 2023. Simplilearn. simplilearn.com/tutorials/deep-learning-tutorial/deep-learning-algorithm

[3] Cijov, A. (2021).

Bilingual Sentence Pair: Dataset for Translator Projects. Kaggle. kaggle.com/datasets/alincijov/bilingual-sentence-pairs

[4] Hochreiter, S., & Schmidhuber, J. (1997).

Long short-term memory. Neural computation, 9(8), 1735-1780.

[5] Jain, H. (2021).

Machine Translation | Seq2Seq | LSTMs. Kaggle. kaggle.com/code/harshjain123/machine-translation-seq2seq-lstms

[6] Kumar, V. (2020).

Sequence-to-Sequence Modeling using LSTM for Language Translation. Analytics India Magazine. analyticsindiamag.com/sequence-to-sequence-modeling-using-lstm-for-language-translation

[7] Malik, U. (2022).

Python for NLP: Neural Machine Translation with Seq2Seq in Keras. StackAbuse. stackabuse.com/python-for-nlp-neural-machine-translation-with-seq2seq-in-keras

[8] Pennington, J., Socher, R., & Manning, C. D. (2014, October).

Glove: Global vectors for word representation. In Proceedings of the 2014 conference on empirical methods in natural language processing (EMNLP) (pp. 1532-1543). nlp.stanford.edu/projects/glove

[9] Schmidhuber, J. (2022).

2022: 25th anniversary of 1997 papers: Long Short-Term Memory. All computable metaverses. Hierarchical reinforcement learning (RL). Meta-RL. Abstractions in generative adversarial RL. Soccer learning. Low-complexity neural nets. Low-complexity art. Others. AI Blog. IDSIA, Lugano, Switzerland.

[10] Wu, Y., Schuster, M., Chen, Z., Le, Q. V., Norouzi, M., Macherey, W., … & Dean, J. (2016).

Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144.

The post Unlock the Power of Python for Deep Learning with Long-Short-Term Memory Networks first appeared on Python GUI.

]]>
https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-long-short-term-memory-networks/feed/ 0 10844
How To Create A Sentiment Analysis App Using DelphiFMX And AI https://pythongui.org/how-to-create-a-sentiment-analysis-app-using-delphifmx-and-ai/ https://pythongui.org/how-to-create-a-sentiment-analysis-app-using-delphifmx-and-ai/#respond Mon, 17 Jul 2023 10:00:00 +0000 https://pythongui.org/?p=10736 In today’s data-driven world, understanding the sentiment behind some text is crucial for making informed decisions. By sentiment analysis we mean working out whether tone the writer was using in their text could be categorized...

The post How To Create A Sentiment Analysis App Using DelphiFMX And AI first appeared on Python GUI.

]]>
In today’s data-driven world, understanding the sentiment behind some text is crucial for making informed decisions. By sentiment analysis we mean working out whether tone the writer was using in their text could be categorized as angry, happy, sad, enthusiastic and so on. Imagine a powerful desktop application that instantly classifies text as neutral, positive, or negative. A feedback form handler, for example, which can tell if customers are angry about something. Or a review tool for a restaurant chain which can see automatically if their clientele is mostly happy with the service and food quality. We can turn this vision into reality with the Python Delphi ecosystem and the advanced deep-learning models from Hugging Face.

In this article, we’ll explore the fusion of Delphi’s development process and the precision of deep learning. By leveraging the flexibility of Delphi’s FMX framework, we’ll create an intuitive user interface, complete with a file picker and text input, enabling users to analyze sentiment effortlessly. And to take our app to the next level, we’ll enrich the user experience and provide an understanding of the analyzed text.

Why Have Transformers Become Popular in Deep Learning?

How To Create A Sentiment Analysis App Using DelphiFMX And AI - a laptop showing some code

Transformers have become widely popular in sentiment analysis apps due to their groundbreaking impact on natural language processing (NLP). With their attention mechanism, transformers excel at capturing contextual relationships within the text, enabling more accurate sentiment analysis by capturing subtle nuances and dependencies.

Moreover, transformers have revolutionized transfer learning in sentiment analysis. Developers can leverage comprehensive language representations by pre-training models on extensive datasets and fine-tuning them on sentiment-specific tasks, saving valuable time and resources. This approach has significantly accelerated the development process of sentiment analysis apps, enabling them to decipher sentiments in a context-aware manner accurately.

Which Tools Can Be Used For Creating GUIs for ML-Powered Apps?

How To Create A Sentiment Analysis App Using DelphiFMX And AI - a laptop on the VCL and FMX libraries page

When creating GUIs for ML-powered apps, the Delphi IDE and Delphi FMX (FireMonkey) framework are powerful tools at your disposal.

The Delphi IDE provides a comprehensive set of visual design tools and components that enable you to create stunning and intuitive user interfaces for your ML-powered applications. With its drag-and-drop interface, you can easily design and customize GUI elements, such as buttons, input fields, and data displays, to create a seamless user experience.

The Delphi FMX framework is a cross-platform UI framework that allows you to build visually appealing and responsive user interfaces. FMX supports multiple platforms, including Windows, macOS, Android, and iOS, making it suitable for creating ML-powered apps that can be deployed on different devices.

Furthermore, if you’re working with ML models developed in Python, you can leverage the Delphi4PythonExporter tool. This tool seamlessly integrates Delphi and Python, allowing you to export and utilize your Python-based ML models within your Delphi application. 

How to Create a Sentiment Analysis App With a Stunning GUI for Desktop?

How To Create A Sentiment Analysis App Using DelphiFMX And AI - two people looking at the RAD Studio IDE

What Are the Prerequisites For Creating A Sentiment Analysis App?

To create a sentiment analysis app, specific prerequisites need to be met. Install Delphi IDE and the FMX Python library on your device. These tools will provide the foundation for developing the app’s graphical user interface. You will also require a text editor or IDE that supports Python, such as PyScripter, along with the Delphi4PythonExporter tool for seamless integration between Delphi and Python.

If any of these tools are not yet installed, it is recommended to refer to the article titled “Powerful Python GUI Project Setup” to assist you in getting started. In terms of Python libraries, the transformers library is essential for working with pre-trained models and performing sentiment analysis tasks. You can install this library by executing the following command:

pip install transformers

Finally, to access the code for this tutorial, you can retrieve it from the GitHub repository provided below:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Sentiment_Analysis_App

Can I Download Pre-trained Sentiment Analysis Models From Online Platforms?

Yes, you can download pre-trained models from online platforms, and one popular platform for accessing and downloading pre-trained models is Hugging Face. This platform provides a wide range of pre-trained models for various NLP tasks, including sentiment analysis, text classification, machine translation, question answering, and more. These models are trained on large datasets and have already learned language representations, making them valuable resources for building NLP applications.

To download pre-trained models from Hugging Face, you can use their Python library called “transformers.” This library lets you easily access and utilize pre-trained models in your machine-learning projects. You can select a specific model based on your task requirements, such as sentiment analysis, and then download the model files and the associated tokenizer.

Once downloaded, you can use the pre-trained model in your ML pipeline, fine-tune it on your specific dataset, or integrate it into your ML-powered app using frameworks like PyTorch or TensorFlow.

How to Create a Stunning GUI For Our Sentiment Analysis App?

Let’s start by opening up Delphi CE and creating a blank project. We will do this by selecting Multi-Device Application > Blank Application and clicking Ok. Here, we have named our project as Sentiment_Analysis_App.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - creating a new app

If you need to become more familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.

2-5716208

Let’s start by renaming our form. To do this, right-click on the form and select QuickEdit. Here we will name our form MainForm with the caption Sentiment Analysis App.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - updating the caption

Next, we will rename our source file from Unit1.pas to Main.pas to make it easier to keep track of. 

Now, we will resize our form. To do this, select the form and navigate to the Object Inspector. Here we will search for the ClientWidth and ClientHeight properties in the Properties tab. We will set these properties to 500 and 500, respectively.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the object inspector

Now let’s start adding a few labels to our form. To do this, navigate to the standard Palette and search for the TLabel component. Drag and drop this component onto the form.

How To Create A Sentiment Analysis App Using DelphiFMX And AI -  filtering for TLabel

Now modify the style by using the TextSettings property of the label. We will do this by navigating to the Object Inspector and searching for the TextSettings property. Next, click the ellipses button next to the Font property to see options for modifying the label based on your preferences. Here we will set our font family as SemiBold Segoe UI with different font sizes for each label. In addition, we will set the HorzAlign and VertAlign properties for our labels as Center.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - changing the alignment

Here is what our form looks like:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen 1

As you can see in the form, we have added three labels to our form. The Title label will serve only as a placeholder to display the title. The Result label will show the result of the sentiment analysis algorithm. Finally, the FileName label will simply display the filename.

Next, let’s add a few buttons to our form. For this, we will use the TButton component, so navigate to the Palette and search for the component.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - filtering for TButton

We will add two buttons to our form. The ResultButton will evaluate the sentiment of our input, whereas the FilePickButton will help us select a file that will be analyzed.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen 2

We have also disabled the FilePickButton by default by setting the Enabled property to False.

To allow the user to select a file, we will add a TOpenDialog component, which will help us open a dialog box to select a file from our system. So open up the Palette and search for the TOpenDialog component. Drag and drop this component anywhere on your form.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the open dialog

Now, let’s add a text box to our form to allow the user to input some text the model will analyze. To do this, open up the Palette and search for TEdit. Add this component to your form and rename it to SentimentTextEdit

Turn off this button by setting the Enabled property to False.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen 3

To complete our form, we will add a few TRadioButton components. These will help the user select the file picker or the text box to analyze some text. So open up the Palette and search for the TRadioButton component. Add this component to your form. We will add two radio buttons FilePickerRadio, and TextboxRadio, that will help us select either of them. Here is what our form looks like:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen 4

How to Create Stylish Forms in Delphi IDE?

Now that our form is ready, let’s add some style. But before that, you will need to download the free ebook bundle, which comes shipped with a multitude of styles that you can choose from. 

First, download your free ebook and extract the FMX styles zip to your chosen directory. Next, select the style you want to use. For this project, we will use AquaGraphite.style available in the bundle.

To use this style, head to the Palette and add the TStyleBook component to your form.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - a stylebook
How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen 5

Next, double-click on the StyleBook1 component to open up your Style Designer. Now, click on the open button to open up a dialog box.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - style designer

Navigate to the .style file of your choosing in the dialog box, select your file, and finally click on exit. 

Once you’ve finalized your style, select the MainForm and head to the Object Inspector. Here we will search for the StyleBook property. Select the drop-down menu and select StyleBook1.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the object inspector

Here is what our form looks like:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen with style applied

Let’s complete our form by adding an image. Start by making some room for our image. We will move all the components down by a few pixels for this. Next, head over to the Palette and search for the TImage component. Add this component to your form.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the palette, selecting TImage
How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen

Next, head to the object inspector and click on the ellipses (...) next to the MultiResBitMap property.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - bitmap

Click on the Fill All From File button and select your chosen image. Now Click on the exit button to load the image.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - editing the bitmap

Finally, adjust the image to your needs. Here is what our final form looks like:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - app screen with images

Can I Export These Forms to Python Code?

Now that the form is complete, we can export it using the Delphi4Python exporter. But before we can do that, we need to add some functionality to each button in the form. 

To do this, double-click on each button on the form. This will add an OnClick method to that button. The procedure will be created in the .pas file of the form. This allows you to add unique functionality to each button when clicked.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the code behind the screen

Because the Delphi4PythonExporter does not use run-time implementation, we must add at least one comment (//) to each procedure to preserve the function when we export the form.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - commenting out the click events

Now that our form is ready, we are ready to export. Select Tools > Export To Python > Export Current Entire Project to export the project.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - export to Python to begin the magic

Here we will give the project the title Sentiment Analysis App. Next, select the directory of your choosing and click on Export:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the project export process

Because we had one form, Delphi will generate two Python files and one .pyfmx file.The Sentiment_Analysis_App.py file will be used to run the application, whereas the Main.py file contains the class for the MainForm. The .pyfmx file contains the visual information for the MainForm. Below are the contents for each Python file.

Sentiment_Analysis_App.py:

from delphifmx import *
from Main import MainForm

def main():
    Application.Initialize()
    Application.Title = 'Sentiment Analysis App'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Main.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Result = None
        self.FileName = None
        self.FilePickButton = None
        self.ResultButton = None
        self.OpenDialog1 = None
        self.SentimentTextEdit = None
        self.TextboxRadio = None
        self.FilePickerRadio = None
        self.Image1 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def FilePickButtonClick(self, Sender):
        pass

    def ResultButtonClick(self, Sender):
        pass

How to Put it All Together Into a Full-Fledged Sentiment Analysis App? 

Now that we are done with the form, all we need to do is add functionality. Let’s start by opening up Main.py in the text editor of your choice and importing some libraries:

# Additional imports
from transformers import AutoTokenizer, AutoModelForSequenceClassification

Next, head over to the __init__ function and initialize the model and tokenizer for the transformer model. Here we will use the "ProsusAI/finbert" sentiment analyzer model available on HuggingFace. Here is what our final __init__ function looks like:

def __init__(self, owner):
        self.Title = None
        self.Result = None
        self.FileName = None
        self.FilePickButton = None
        self.ResultButton = None
        self.OpenDialog1 = None
        self.SentimentTextEdit = None
        self.TextboxRadio = None
        self.FilePickerRadio = None
        self.Image1 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Initialize model and tokenizer
        self.tokenizer = AutoTokenizer.from_pretrained("ProsusAI/finbert")
        self.model = AutoModelForSequenceClassification.from_pretrained("ProsusAI/finbert")

Next, navigate to the FilePickButtonClick function. Here we will open the file picker dialog box and filter the files to show only the .txt files. Our final FilePickButtonClick function looks like:

def FilePickButtonClick(self, Sender):
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show
        self.OpenDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"

        if self.OpenDialog1.Execute():
                    self.FileName.Text = "Filename: " + os.path.basename(self.OpenDialog1.FileName)

Now, let’s define our ResultButtonClick function. We will start by checking which radio button is checked. If the TextboxRadio button is checked, we will extract the text from the SentimentTextEdit text box and store it in our text variable. We will then use our predict function (which we will define later) to predict the sentiment of the text. The predict function will also display the sentiment in the Result label:

def ResultButtonClick(self, Sender):
        if self.TextboxRadio.IsChecked:
            text = self.SentimentTextEdit.Text
            print(text)
            self.predict(text)

Next, if the FilePickerRadio button is checked, we open the text file and store the data in the text variable. We then use the predict function to predict the sentiment. Our final ResultButtonClick function looks like:

def ResultButtonClick(self, Sender):
        if self.TextboxRadio.IsChecked:
            text = self.SentimentTextEdit.Text
            print(text)
            self.predict(text)
        elif self.FilePickerRadio.IsChecked:
            with open(self.OpenDialog1.FileName, 'r') as file:
                text = file.read()
            print(text)
            self.predict(text)
        else:
            pass

Now, let’s define our predict function. We will start by processing our text to generate tokens. We will then pass these tokens to the model to generate an output based on the text. We then extract the output from the last layer of the model to get the predicted_label. Next, we use the predicted_label and the model config to decode our prediction. Here is what our predict function looks like:

def predict(self, text):
        tokens = self.tokenizer.encode_plus(text, return_tensors='pt', padding=True, truncation=True)
        output = self.model(**tokens)
        logits = output.logits
        predicted_label = logits.argmax().item()

        self.Result.Text = "Result: " + self.model.config.id2label[predicted_label]

Finally, we need a way to enable/disable our textbox and button based on which radio button is ticked. We will do this by first opening up Main.pyfmx and creating an OnChange event for both our TextboxRadio and FilePickerRadio buttons.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the screen's code

Next, let’s define our RadioChange function. Open up Main.py and create a new RadioChange function. We define this function by checking if the TextboxRadio button is checked. If checked, we enable the SentimentTextEdit text box and disable the FilePickButton. Otherwise, if the FilePickerRadio button is checked, we simply turn off the SentimentTextEdit text box and enable the FilePickButton. Here is what our RadioChange function looks like:

def RadioChange(self, Sender):
        if self.TextboxRadio.IsChecked:
            self.SentimentTextEdit.Enabled = True
            self.FilePickButton.Enabled = False
        if self.FilePickerRadio.IsChecked:
            self.SentimentTextEdit.Enabled = False
            self.FilePickButton.Enabled = True

Here is what our final Main.py file looks like:

import os
from delphifmx import *

# Additional imports
from transformers import AutoTokenizer, AutoModelForSequenceClassification

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Result = None
        self.FileName = None
        self.FilePickButton = None
        self.ResultButton = None
        self.OpenDialog1 = None
        self.SentimentTextEdit = None
        self.TextboxRadio = None
        self.FilePickerRadio = None
        self.Image1 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        # Initialize model and tokenizer
        self.tokenizer = AutoTokenizer.from_pretrained("ProsusAI/finbert")
        self.model = AutoModelForSequenceClassification.from_pretrained("ProsusAI/finbert")

    def FilePickButtonClick(self, Sender):
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show
        self.OpenDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"

        if self.OpenDialog1.Execute():
                    self.FileName.Text = "Filename: " + os.path.basename(self.OpenDialog1.FileName)

    def ResultButtonClick(self, Sender):
        if self.TextboxRadio.IsChecked:
            text = self.SentimentTextEdit.Text
            print(text)
            self.predict(text)
        elif self.FilePickerRadio.IsChecked:
            with open(self.OpenDialog1.FileName, 'r') as file:
                text = file.read()
            print(text)
            self.predict(text)
        else:
            pass

    def predict(self, text):
        tokens = self.tokenizer.encode_plus(text, return_tensors='pt', padding=True, truncation=True)
        output = self.model(**tokens)
        logits = output.logits
        predicted_label = logits.argmax().item()

        self.Result.Text = "Result: " + self.model.config.id2label[predicted_label]

    def RadioChange(self, Sender):
        if self.TextboxRadio.IsChecked:
            self.SentimentTextEdit.Enabled = True
            self.FilePickButton.Enabled = False
        if self.FilePickerRadio.IsChecked:
            self.SentimentTextEdit.Enabled = False
            self.FilePickButton.Enabled = True

Now that our application is ready, let’s test it out. Head over to Sentiment_Analysis_App.py and run the file.

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen  more screen

Now let’s test our application by selecting the Textbox radio button. This will enable the text box. Next, add some text to test out:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - testing the screen

Finally, click on the Analyze Sentiment button to check out the result:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen

Similarly, we can test out the file picker by selecting the File Picker radio button. This enables the Select File button. Now press the button to open a dialog box and select a text file to analyze. For now, we will be using test.txt. Here are the contents of our file: “The movie was an absolute disaster, with terrible acting, a nonsensical plot, and cringe-worthy dialogue. I wouldn’t recommend it to anyone.”

Once you’ve selected your text file, your file name should appear on the FileName label:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen

Now click on the Analyze Sentiment button to check out the result:

How To Create A Sentiment Analysis App Using DelphiFMX And AI - screen

What Are the Key Takeaways?

How To Create A Sentiment Analysis App Using DelphiFMX And AI - a happy man looking at a laptop screen showing a download page

Congrats! We have successfully created a Sentiment Analysis app by leveraging Delphi’s powerful IDE, Delphifmx Python library, and incorporating a deep learning model from Hugging Face. This user-friendly application allows users to classify text as neutral, positive, or negative, empowering them to extract valuable insights from textual data. Delphi’s versatility, extensive features, and cross-platform capabilities make it an ideal choice for developers looking to build innovative applications. 

With the fusion of Delphi and deep learning, the possibilities are boundless. Begin your app development journey with Delphi and unlock the potential to create special applications that revolutionize how we analyze and interpret sentiment in text.

What Are Some FAQs About this Topic?

How To Create A Sentiment Analysis App Using DelphiFMX And AI - the FAW page on a laptop

What is Delphi?

Delphi is an IDE that allows developers to build applications using the Object Pascal programming language. It provides various tools and components for creating GUI-based applications across various platforms.

What is sentiment analysis?

Sentiment analysis determines a given text’s sentiment or emotional tone, such as a review, social media post, or customer feedback. It involves classifying the text as positive, negative, or neutral, providing insights into the writer’s opinion or attitude.

What is a deep learning model?

A deep learning model is a machine learning model that utilizes artificial neural networks with multiple layers to learn and extract complex patterns and representations from data. Deep learning models have been particularly successful in various domains, including NLP tasks like sentiment analysis.

What is Hugging Face?

Hugging Face is an open-source platform that provides a wide range of pre-trained models and tools for NLP. It offers resources such as transformer models, tokenizers, and libraries like Transformers, facilitating the development and deployment of NLP applications.

Can Delphi be used for building machine-learning applications?

Yes, Delphi can be used for building machine-learning applications. With its versatile IDE and frameworks like Delphi FMX, developers can create visually appealing and user-friendly GUIs for ML-powered applications. Additionally, tools like Delphi4PythonExporter enable integration with Python-based machine learning models, expanding the capabilities of Delphi in the ML domain.

The post How To Create A Sentiment Analysis App Using DelphiFMX And AI first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-sentiment-analysis-app-using-delphifmx-and-ai/feed/ 0 10736
How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem https://pythongui.org/how-to-create-an-ml-powered-food-classification-app-using-the-python-delphi-ecosystem/ https://pythongui.org/how-to-create-an-ml-powered-food-classification-app-using-the-python-delphi-ecosystem/#respond Fri, 14 Jul 2023 01:46:23 +0000 https://pythongui.org/?p=10660 In this tutorial, we will unleash the power of machine learning and Delphi’s ecosystem to create an ingenious food classification app. Experience the future of food identification, empowering users to make informed choices with real-time...

The post How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem first appeared on Python GUI.

]]>
In this tutorial, we will unleash the power of machine learning and Delphi’s ecosystem to create an ingenious food classification app. Experience the future of food identification, empowering users to make informed choices with real-time analysis, all at their fingertips. Let’s dive into the exciting journey of building an ML-powered food classification app using Delphi. 

What ML Models Are Used For Classification Tasks?

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - a person editing some Python code

Classification tasks in machine learning utilize various models that have proven effective in producing accurate results. These models include logistic regression for binary classification, decision trees for hierarchical partitioning, random forests for ensemble learning, and support vector machines for optimal hyperplane separation. 

In recent years, neural networks, particularly deep learning models, have gained immense popularity due to their ability to learn complex patterns and hierarchies in data. Neural networks, especially transformers, have gained prominence, excelling in NLP and image classification tasks.  For instance, the Swin and Vision Transformer (ViT) leverages the power of transformers to process image patches, enabling effective classification based on visual information. Transformers capture complex dependencies and have revolutionized NLP with self-attention and multi-head attention mechanisms. Their adaptability to diverse data domains makes them a powerful choice for accurate classification in machine-learning applications.

Which Tools Can Be Used For Creating GUIs for ML-based Apps?

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - The Delphi ecosystem

Delphi CE (Community Edition), Delphi4PythonExporter, and Delphi FMX (FireMonkey) are excellent choices for creating GUIs specifically tailored for ML-based apps. Delphi CE provides a comprehensive, integrated development environment (IDE) that enables rapid application development with various components and controls for creating visually appealing interfaces. It allows seamless integration with ML backends implemented in Python using frameworks like TensorFlow and PyTorch.

Delphi FMX, a cross-platform GUI framework, empowers developers to create visually stunning and responsive interfaces for ML-based apps. With Delphi FMX, developers can design seamless GUIs on various platforms, including Windows, macOS, iOS, and Android. The framework supports integrating ML models developed with Python frameworks, such as TensorFlow, PyTorch, or Hugging Face, into the Delphi FMX-based interfaces.

How to Create a Food Classification Desktop App?

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - the RAD Studio IDE

Creating a food classification desktop app involves several steps. Before we get into the detailed tutorial, let’s look at the requirements for this project.

What Are the Prerequisites For this Article?

Install Delphi CE and the FireMonkey GUI framework on your device to create the food classification app. You will need a text editor or IDE that supports Python, such as PyScripter and the Delphi4PythonExporter tool. If you don’t have these tools installed, we recommend checking out the article “Powerful Python GUI Project Setup” to help you get started. 

You should also install transformers and pillow Python libraries by running the following commands in the cmd:

pip install pillow
pip install transformers

You can grab the code for this tutorial from our GitHub repository using the following link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Food_Image_Classifier

How to Download Pre-trained Models From HuggingFace?

You can follow a few simple steps to download pre-trained models from Hugging Face. Start by visiting the Hugging Face Model Hub website at https://huggingface.co/models. Once there, you can search for the specific pre-trained model you need using relevant keywords or for specific model names. For instance, if you are looking for a pre-trained model for food classification, you can search for “food classification” or specific model names associated with food classification.

You can Import the necessary modules in your Python script by replacing <model> with the specific model you want to use:

from transformers import <model>

Then load the pre-trained model using the from_pretrained() method while replacing <model> with the model class you imported and <model_name> with the name or path of the pre-trained model:

model = <model>.from_pretrained('<model_name>')

This will download the pre-trained weights if not already cached on your system. Now, you can use the loaded model for your tasks by calling its appropriate methods or attributes. For instance, you will have to get its feature extractor to extract features from unseen data before providing it to the model. You can refer to the documentation of the specific model class for more details on how to use it. 

For this tutorial, we will use a food classification model that classifies images into 7 categories (apple pie, falafel, french toast, ice cream, ramen, sushi, and tiramisu). This pre-trained model is finetuned on the Swin transformer model:

https://huggingface.co/Kaludi/Food-Classification

You can grab the code for this tutorial from our GitHub repository using the following link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/Food_Image_Classifier

What Kind of a GUI Can We Create For Such an App?

Using the Delphi ecosystem, we can create a very attractive GUI for such an ML task.

How to Create Stylish Delphi Forms?

We will start by opening the Delphi CE application and creating a blank project. To do this, navigate to File > New > Multi-Device Application > Blank Application > Ok. In this tutorial, we have named our project MLFoodClassifier.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - new multi device application

If you are not familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - free e-book

To start, let’s give our form a name. Right-click on the form and select QuickEdit. Here, we will name our form MainForm with the caption Food Classification App.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - naming the form

We will also rename the source file of our MainForm to Main.pas to make it easier to keep track of. Next, we will resize the form. So go to the Object Inspector and search for ClientWidth and ClientHeight in the properties tab. We will set them to 360 and 500, respectively.

Next, let’s start by adding a few labels to our app. To do this, navigate to the standard palette and locate the TLabel component. Next, drag and drop this component onto the form.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - selecting TLabel from the palette

Next, we’ll modify the text style by using the TextSettings property of each label. To do this, navigate to the Object Inspector and search for TextSettings. Click on the ellipses button (...) next to the Font property to see options for modifying the label based on your preferences. Here we have set our font family as SemiBold Segoe UI with different font sizes for each label. In addition, we will set the HorzAlign and VertAlign properties for our labels as Center.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - setting the horizontal alignment

Here is what our form looks like:

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - form 1

As you can see, we have added 4 TLabel components, Title, FileName, FileNameLabel, and ResultLabel. The FileName label will be used to display the file name of the image to be classified, whereas the ResultLabel will help us display the output of our classifier.

Next, let’s add a few buttons to our form. For this, we will use the TButton component, so navigate to the Palette and search for the component.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - adding a button

We will add two buttons, FileSelectButton, to help us select the file to classify, and a ClassifyButton, to help us evaluate our image.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - form

To complete our form, we will add a TOpenDialog component, which will help us open up a dialog box to select a file from our system. So open up the Palette and search for the component. Next, drag and drop this component into your form.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - TOpenDialog
How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - form

Finally, let’s add some style to our form. For this, you will need to download the free ebook bundle which comes shipped with various styles. Download your free ebook and extract the FMX styles zip to your chosen directory. Next, select the style you want to use. For this we will be using GoldenGraphite.style available in the bundle. You can find more DelphiFMX styles online, such as at delphistyles.com.

Now head to the Palette and add the TStyleBook component to your form.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - stylebook
How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - form

Next, double-click on the StyleBook1 component. This will open up your Style Designer. Now, click on the open button. This will open up a dialog box.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - the style designer

Navigate to the .style file of your choosing in the dialog box, select your file, and finally click on exit. Now select the form and head over to the Object Inspector. Here we will search for the StyleBook property. Select the drop-down menu and select StyleBook1.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - the stylebook

Here is what our MainForm looks like:

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - the main form

Now that the form is complete, the final step will be to add some functionality to each button in the form. To do this, double-click each button. This will add an OnClick method to that button. The procedure will be created in the .pas file corresponding to the .fmx form. This allows you to add unique functionality to each button when clicked.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - adding code

Because the Delphi4PythonExporter does not use run-time implementation, we will need to add at least one comment (//) to each procedure to preserve the function when we export the form.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - select button code

How to Export These Forms into Python Scripts?

Now that our form is ready, we can export it using the Delphi4Python exporter. Save our project by selecting Tools > Export To Python > Export Current Entire Project.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - exporting the project to Python

Here we will give the project the title MLFoodClassifier. Next, select the directory of your choosing and click on Export:

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - project exporting

Delphi will generate two Python files and one .pyfmx file. The MLFoodClassifier.py file will be used to run the application, whereas the Main.py file contains the class for the MainForm. The .pyfmx file contains the visual information for the MainForm. Below are the contents for each Python file.

Main.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.FileNameLabel = None
        self.ResultLabel = None
        self.FileName = None
        self.FileSelectButton = None
        self.ClassifyButton = None
        self.OpenDialog1 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def FileSelectButtonClick(self, Sender):
        pass

    def ClassifyButtonClick(self, Sender):
        pass

MLFoodClassifier.py:

from delphifmx import *
from Main import MainForm

def main():
    Application.Initialize()
    Application.Title = 'MLFoodClassifier'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

How to Develop This Project Into a Fully Functional App? 

Now that we are done with the form, all we need to do is add functionality to our form. Let’s start by opening up Main.py in the text editor of your choice. We will start by importing some libraries:

# Additional imports
from PIL import Image
from transformers import AutoModelForImageClassification, AutoImageProcessor

Next, head over to the __init__ function and initialize your transformer models. Here we will be using the Kaludi food classification model available on HuggingFace. Additionally, we will also set the FileName label as empty:

self.FileName.Text = ""
       
        # Loading pre-trained transformer model and feature extractor during app initialization
        self.extractor = AutoImageProcessor.from_pretrained("Kaludi/Food-Classification")
        self.model = AutoModelForImageClassification.from_pretrained("Kaludi/Food-Classification")

Here is what our final __init__ function looks like:

def __init__(self, owner):
        self.Title = None
        self.FileNameLabel = None
        self.ResultLabel = None
        self.FileName = None
        self.FileSelectButton = None
        self.ClassifyButton = None
        self.OpenDialog1 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        self.FileName.Text = ""
       
        # Loading pre-trained transformer model and feature extractor during app initialization
        self.extractor = AutoImageProcessor.from_pretrained("Kaludi/Food-Classification")
        self.model = AutoModelForImageClassification.from_pretrained("Kaludi/Food-Classification")

Now let’s code our FileSelectButton. Head over to the FileSelectButtonClick method, and start by adding a title to the dialog box:

# Filepicker window title
        self.OpenDialog1.Title = "Select an Image"

Next, we will filter the files only to show image files in different formats:

# Filtering only image formats to show
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.gif;*.bmp, *.webp)|*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.webp|All files (*.*)|*.*"

Finally, if the user presses the open button, we will save the directory of the file in Filename. Here is our FileSelectButtonClick function code:

def FileSelectButtonClick(self, Sender):
        # Filepicker window title
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.gif;*.bmp, *.webp)|*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.webp|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            self.FileName.Text = os.path.basename(self.OpenDialog1.FileName) # Display selected image

Finally, to evaluate the image, we will need to complete the ClassifyButton. Head over to the ClassifyButtonClick method and start by opening the image file:

def ClassifyButtonClick(self, Sender):
        # Load image from local file
        image = Image.open(self.OpenDialog1.FileName)

Next, preprocess the image using the image processor:

# Preprocess image
        inputs = self.extractor(images=image, return_tensors="pt")

Finally, make the prediction using the model. Here is what our final ClassifyButtonClick method looks like:

def ClassifyButtonClick(self, Sender):
        # Load image from local file
        image = Image.open(self.OpenDialog1.FileName)

        # Preprocess image
        inputs = self.extractor(images=image, return_tensors="pt")

        # Make prediction
        outputs = self.model(**inputs)
        predicted_class_idx = outputs.logits.argmax(-1).item()
        predicted_class = self.model.config.id2label[predicted_class_idx]

        self.ResultLabel.Text = "Result: " + predicted_class # Display prediction

Here is what our final Main.py file looks like:

import os
from delphifmx import *

# Additional imports
from PIL import Image
from transformers import AutoModelForImageClassification, AutoImageProcessor

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.FileNameLabel = None
        self.ResultLabel = None
        self.FileName = None
        self.FileSelectButton = None
        self.ClassifyButton = None
        self.OpenDialog1 = None
        self.StyleBook1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        self.FileName.Text = ""
       
        # Loading pre-trained transformer model and feature extractor during app initialization
        self.extractor = AutoImageProcessor.from_pretrained("Kaludi/Food-Classification")
        self.model = AutoModelForImageClassification.from_pretrained("Kaludi/Food-Classification")


    def FileSelectButtonClick(self, Sender):
        # Filepicker window title
        self.OpenDialog1.Title = "Select an Image"

        # Filtering only image formats to show
        self.OpenDialog1.Filter = "Image files (*.jpg;*.jpeg;*.png;*.gif;*.bmp, *.webp)|*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.webp|All files (*.*)|*.*"
       
        if self.OpenDialog1.Execute():
            self.FileName.Text = os.path.basename(self.OpenDialog1.FileName) # Display selected image

    def ClassifyButtonClick(self, Sender):
        # Load image from local file
        image = Image.open(self.OpenDialog1.FileName)

        # Preprocess image
        inputs = self.extractor(images=image, return_tensors="pt")

        # Make prediction
        outputs = self.model(**inputs)
        predicted_class_idx = outputs.logits.argmax(-1).item()
        predicted_class = self.model.config.id2label[predicted_class_idx]

        self.ResultLabel.Text = "Result: " + predicted_class # Display prediction

Now that our code is ready, it’s time to test our app. Head over to the MLFoodClassifier.py and run the file.

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - form

Next, press the Select Image button. This will open up a dialog box for your to select an image. Navigate to the directory of your image and open your image. Here we will be using a sample image from wikipedia:

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - a strawberry ice cream image
Source: https://en.wikipedia.org/wiki/Strawberry_ice_cream

Once you’ve selected your image your file name should appear on the FileName label:

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - form

Now press the Classify button to evaluate your image. Your result should appear in the ResultLabel:

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - form

Are You Ready to Create Your Own Image Classification Apps?

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - the TWebBrowser

Creating your image classification apps can be exciting and rewarding. With the right tools and techniques, you can develop powerful applications to classify and identify objects in images accurately. We highly recommend exploring the Delphi ecosystem to streamline your development process and unlock even more possibilities. Delphi CE, Delphi4PythonExporter, and Delphi FMX provide a comprehensive suite of tools and frameworks for GUI development and seamless integration with Python ML backends.

So, are you ready to dive into the world of image classification apps? Get started with Delphi and transform your ML-based app development journey now!

What Are the FAQs Related to This Topic?

How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem - The FAQ Web page

Can I use pre-trained models for food classification, or is self-training required?

Yes, you can leverage pre-trained models for food classification. Pretrained models trained on large-scale datasets can provide excellent performance. However, fine-tuning or training your models on a specific food dataset can yield better results.

What are the challenges in food classification?

Food classification faces challenges such as variations in food appearance, lighting conditions, occlusions, and complex backgrounds. It requires handling large amounts of data and ensuring the model’s generalization across different food categories.

How do I improve the accuracy of my food classification model?

You can try data augmentation, transfer learning, fine-tuning, model ensemble, and experimenting with different architectures or hyperparameters to improve accuracy.

What is Delphi?

Delphi is an integrated development environment (IDE) that allows developers to build cross-platform applications using the Object Pascal programming language. It provides powerful tools and libraries for creating visually appealing and feature-rich applications.

Is Delphi suitable for beginners?

Yes, Delphi is beginner-friendly. It offers a visually-driven development environment with a drag-and-drop interface, making it easy for beginners to create GUI applications without extensive coding knowledge. Delphi also provides comprehensive documentation and a supportive community.

The post How To Create An ML-Powered Food Classification App Using The Python Delphi Ecosystem first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-an-ml-powered-food-classification-app-using-the-python-delphi-ecosystem/feed/ 0 10660
How to Create A Hi-Lo Game With DelphiFMX Python GUI Package https://pythongui.org/how-to-create-a-hi-lo-game-with-delphifmx-python-gui-package/ https://pythongui.org/how-to-create-a-hi-lo-game-with-delphifmx-python-gui-package/#respond Mon, 03 Jul 2023 10:00:00 +0000 https://pythongui.org/?p=10301 Do you want to learn how to use Python GUI to make an entertaining and challenging game? Look no further than the Hi-Lo game! This game is a great practice for beginning and intermediate Python...

The post How to Create A Hi-Lo Game With DelphiFMX Python GUI Package first appeared on Python GUI.

]]>
Do you want to learn how to use Python GUI to make an entertaining and challenging game? Look no further than the Hi-Lo game! This game is a great practice for beginning and intermediate Python programmers because it demands players predict a randomly generated integer inside a given range. In this post, we’ll walk you through the process of using the Python and Delphi ecosystem to construct the Hi-Lo game. After reading this article, you can wow your friends and advance your Python programming abilities. So, let’s get started!

What Are the Rules of a Hi-Lo Game?

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - what Are the Rules of a Hi-Lo Game?

The Hi-Lo app for Android is a fast-paced game that challenges your mind on the go. The app presents you with a random number as the starting number, and your goal is to guess whether the next number will be higher or lower. If you guess correctly, the app reveals the next number, and you continue to the next round. However, if you guess incorrectly, the game ends, and your score is based on the number of correct guesses you made in a row. Your aim is to achieve the highest score possible by making correct guesses for as long as you can. 

Why Use Delphi For Python to Create this App?

Delphi for Python is a useful set of tools for Python developers looking to create such a game with efficient and visually appealing Graphical User Interfaces (GUIs). These tools, such as Delphi FMX provides powerful tools and cross-platform support, enabling developers to build flexible and sophisticated GUIs that operate across multiple platforms without writing separate code for each. Delphi’s UI design tools, including the Delphi4PythonExporter tool, can help accelerate development and ensure functional and aesthetically appealing GUIs. The open-source Delphi Community Edition and PythonFMXBuilder are also available for developers who prefer to work with open-source tools. Delphi for Python can help streamline the development process and ensure smooth and efficient operation across all platforms.

How to Create an Amazing Hi-Lo App?

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - a user with the RAD Studio IDE open on his computer screen

What Are the Prerequisites for this App?

To create the memory game desktop app, you must install Delphi and the FireMonkey GUI framework on your device. Additionally, you will need a text editor or IDE that supports Python, such as PyScripter and the Delphi4PythonExporter tool.

If you don’t have these tools installed, we recommend checking out the article “Powerful Python GUI Project Setup” to help you get started. Once you have all the required tools, you can proceed with the tutorial to create your memory game desktop app using Delphi

You can grab the code for this tutorial from our GitHub repository using the following link: https://github.com/Embarcadero/PythonBlogExamples/tree/main/HiLo_Game

How To Create Basic Forms For this App in Delphi CE?

We will start by opening the Delphi CE application and creating a blank project. To do this, navigate to File > New > Multi-Device Application > Blank Application > Ok. In this tutorial, we have named our project HiLoGame.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - creating the form

If you are not familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - free e-book

To start, let’s give our form a name. Right-click on the form and select QuickEdit. Here, we will name our form MainForm with the caption MainMenu.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - naming the main form

Next, we need to resize our form which will help it fit in our Android devices. So, go to the object inspector and search ClientHeight and ClientWidth in the properties tab. We will set them to 500 and 360, respectively.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the object inspector

Moreover, we will also rename the source file of our MainMenu form to MainMenu.pas to make it easier to keep track of.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the project manager

As you may have guessed, this form will serve as the main screen of our app where the users will be greeted and can start the game. Now what we will need to do is enhance the user experience by adding components to our app. First, let’s start by adding a title to our app. To do this, navigate to the standard palette and locate the TLabel component. Next, drag and drop this component onto the form.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - selecting the TLabel from the component palette

Next, let’s modify the text style. To do this we will use the TextSettings property. So, navigate to the Object Inspector and search for TextSettings. Select Font beneath it and click “...” to see options for modifying the label’s font, size, and style based on your preferences. Here we have set our font family as Segoe UI with a font size of 48.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the font dialog

Next, we will center the text using the HorzAlign and VertAlign properties in TextSettings. So select the label component and select the adjust the properties to Center.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the object inspector

Additionally, we must follow intuitive naming convention for our app components so that they can be tracked more easily. Therefore, we will name our TLabel component “Title” with the “Memory Game” text.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - screen 1

Next, let’s add another label that will display the rules for our app.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package -  screen 2

Next, we need a way to navigate to our game form where we will be playing our game. To do this, we will be using a TButton component. So go to the Palette and add a button using the TButton component.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - selecting a button
How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - screen 3

Now, let’s make this button a bit more appealing. Let’s change the font size to Segoe UI with a font size of 18 and change the size of the button. Additionally, we will name the button Start and display the text as “START”. Here is what our form looks like:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - screen 4

Finally, let’s adjust the form’s background color by navigating to the Object Inspector and selecting the form’s fill property.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the brush designer

Here is what our form looks like:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - chaning colors

Finally, we can explore the power of styles using DelphiFMX. To do this you will need to download the free ebook bundle which comes with a variety of styles. Download your FMX styles zip file and extract it into your desktop. Next, select a style that you want to use. You can find other styles online, such as delphistyles.com. For now we will be using Light.style available in the bundle.

Head to Palette and TStyleBook object to your form

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - searching in the component palette for a stylebook
How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - applying a style

Next, double click on the object. This will open up your Style Designer. Now press the click on the open button.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the style designer

Navigate to the .style file of your choosing and click on exit. Now select the form and head over to the Object Inspector. Here we will search for the StyleBook property. Select the drop down menu and select StyleBook1.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - stylebook 1

This will apply the style to your form. Here is what our final MainForm looks like:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - applying the style

Now that we are done with the main menu, let’s create a new form that will display our game. So right-click on HiLoGame.exe and select Add New > Multi-Device Form.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - selecting add new in the project manager

This will create a new form that will serve the main game. Here we have named the form as GameForm and its corresponding source file as Game.pas. We also used QuickEdit to change the form Caption to HiLo Game and changed its dimension to match our MainForm.

Now, let’s start by changing the background of our form using the fill property.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the brush designer

Next, we will add labels and buttons to our form. We will first add three labels to our form. The first label, which we will name Number will help show the number that is to be predicted. The next label is the ScoreLabel which will display the current score of the user. For now, we will set the default caption of Number as “-” and the ScoreLabel as “Score :0”. Finally, we add a third label StatusLabel right below the ScoreLabel to help us display some information. We will set its default caption as empty.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - a pretty screen

Finally, we will add 3 buttons to our app. The HighButton and LowButton will help the user predict whether the next number will be high or low, respectively. The AgainButton will help the user restart the game.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the screen is taking shape

Additionally, we will set the AgainButton as disabled by selecting the button and setting its Enabled property as False.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - object inspector

Finally, apply the style of your choosing to your form. Here is what our final GameForm looks like:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - screen with style applied

Now that our forms are complete, the final step is to add functionality to each button. So go to each form and double-click each button to add an OnClick method to that button. The procedure will be created in the .pas file corresponding to the .fmx form. This allows you to add unique functionality to each button when clicked.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - adding the click code

After creating the OnClick method for each button, add at least one comment (//) to each procedure. This is recommended to preserve the method when you export the form as a Python file, as we do not export the run-time implementation using the Delphi4PythonExporter.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - adding a comment to the click code

Can I Export This GUI to Python Code?

Now that our forms are ready, we can save our project as a Python script by selecting Tools > Export To Python > Export Current Entire Project.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - exporting the GUI code

Here rename your project to HiLoGame, and select the main form as MainForm. Finally, select the directory of your choosing and click Export:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - exporting the project

Delphi will generate 5 files, 3 Python scripts named MainMenu.py, Game.py, and HiLoGame.py. The HiLoGame.py is used to launch our Delphi app, while Game.py, MainMenu.py python files contain the classes for the individual forms. Along with the Python file for each form, Delphi also generates a .pyfmx script of the same name as each form that contains the visual information of that form. Here are the contents of each file.

HiLoGame.py:

from delphifmx import *
from MainMenu import MainForm

def main():
    Application.Initialize()
    Application.Title = 'HiLoGame'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

MainMenu.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Rules = None
        self.Start = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainMenu.pyfmx"))

    def StartClick(self, Sender):
        pass

Game.py:

import os
from delphifmx import *

class GameForm(Form):

    def __init__(self, owner):
        self.ScoreLabel = None
        self.Number = None
        self.HighButton = None
        self.LowButton = None
        self.AgainButton = None
        self.StatusLabel = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Game.pyfmx"))

    def HighButtonClick(self, Sender):
        pass

    def LowButtonClick(self, Sender):
        pass

    def AgainButtonClick(self, Sender):
        pass

How Can I Add Functionality to This Amazing GUI?

Now that our forms are ready, we can add functionality to our game. Let’s start with our MainForm. So open up MainMenu.py and navigate to the StartClick function. 
The MainForm only serves the purpose of launching the game. The StartClick will enable us to launch our GameForm. So start by importing the GameForm, from Game.py:

from Game import GameForm

Next, in the StartClick function, create a new variable named Game, and initialize it with a new instance of the GameForm. Now, we will simply use the Show() method to display our GameForm. Here is what the StartClick function looks like:

def StartClick(self, Sender):
        Game = GameForm(self)
        Game.Show()

Finally, lets display the rules of the game by defining them in the Rules label. This is done using the .Text property of the label component:

self.Rules.Text = """Rules: nThe rules for the game are simple.
The game will generate a random number between 1 and 10.
Your job will be to predict whether the next number will be higher or lower than the current number.
        """

Here are the contents of our final MainMenu.py:

import os
from delphifmx import *
from Game import GameForm


class MainForm(Form):
    def __init__(self, owner):
        self.Title = None
        self.Rules = None
        self.Start = None
        self.LoadProps(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainMenu.pyfmx")
        )

        self.Rules.Text = """Rules: nThe rules for the game are simple.
The game will generate a random number between 1 and 10.
Your job will be to predict whether the next number will be higher or lower than the current number.
        """

    def StartClick(self, Sender):
        Game = GameForm(self)
        Game.Show()

Now, lets open up Game.py and start coding our game.

Let’s start by navigating to our __init__ function. The first thing we will need to do is create a variable named self.Score and initialize it to a value of 0. This will help keep track of our score.

self.Score = 0

Next, we import the random library in our Game.py file.

import random

Now, navigate to the __init__ function and generate a random integer between 0 and 10. Next, we display this value to our Number label using the .Text property. Here is what our __init__ function looks like:

def __init__(self, owner):
        self.ScoreLabel = None
        self.Number = None
        self.HighButton = None
        self.LowButton = None
        self.AgainButton = None
        self.StatusLabel = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Game.pyfmx"))

        # Additional initializations
        self.Score = 0
        self.GuessNumber = random.randint(0, 10)  # Generate a random number between 0 and 10
        self.Number.Text = str(self.GuessNumber)

Next, let’s define a function called __UpdateGame that takes in a single string parameter compare to compare the GuessNumber to the selected button. The compare parameter will either be a > or a < string that will help compare the current GuessNumber. We start by clearing the StatusLabel of any text and then storing the current GuessNumber in a new variable called prev. We will use prev to check whether the guess is correct or not. 

Next, we then generate a new random number and store it in GuessNumber and, finally, display the next number into our Number label regardless of the users’ prediction.

def __UpdateGame(self, compare):
        self.StatusLabel.Text = ""  # Clear the status label each time button clicked
        prev = self.GuessNumber  # Store the guess number
        self.GuessNumber = random.randint(0, 10)  # Generate a new random number within a range
        self.Number.Text = str(self.GuessNumber)

Now that we have our guess number, we start comparing. We will use an if statement to check which button the user has pressed based on the compare parameter. If compare equals “>“, then the user presses the HighButton. We then check if the last number is greater than the new number. If this is true, we update the Status label to show that the user was correct. We then increment the Score, and display it as a string into our ScoreLabel. Similarly, if the user presses the LowButton, the compare parameter will be defined as “<“, which we would then use to compare whether the user predicts the next number to be less than or equal to the current number.

def __UpdateGame(self, compare):
        self.StatusLabel.Text = ""  # Clear the status label each time button clicked
        prev = self.GuessNumber  # Store the guess number
        self.GuessNumber = random.randint(0, 10)  # Generate a new random number within a range
        self.Number.Text = str(self.GuessNumber)
        if compare==">" and prev > self.GuessNumber: # If the player guessed lower and the new number is actually lower
            self.StatusLabel.Text = "That's right"
            self.Score +=1  # Increment the score
            self.ScoreLabel.Text = "Score:" + str(self.Score)  
        elif compare=="<" and prev <= self.GuessNumber:  # If the player guessed higher and the new number is actually higher
            self.StatusLabel.Text = "That's right"
            self.Score +=1  # Increment the score
            self.ScoreLabel.Text = "Score:" + str(self.Score)

Finally, if the user guesses the number wrong, then we simply set the StatusLabel to “GAME OVER“. We then disable the HighButton, and LowButton buttons and enable the AgainButton. Here is what our final __UpdateGame function looks like:

def __UpdateGame(self, compare):
        self.StatusLabel.Text = ""  # Clear the status label each time button clicked
        prev = self.GuessNumber  # Store the guess number
        self.GuessNumber = random.randint(0, 10)  # Generate a new random number within a range
        self.Number.Text = str(self.GuessNumber)
        if compare==">" and prev > self.GuessNumber: # If the player guessed lower and the new number is actually lower
            self.StatusLabel.Text = "That's right"
            self.Score +=1  # Increment the score
            self.ScoreLabel.Text = "Score:" + str(self.Score)  
        elif compare=="<" and prev <= self.GuessNumber:  # If the player guessed higher and the new number is actually higher
            self.StatusLabel.Text = "That's right"
            self.Score +=1  # Increment the score
            self.ScoreLabel.Text = "Score:" + str(self.Score)
        else:  # If the player guessed wrong
            self.StatusLabel.Text = "GAME OVER"
            self.LowButton.Enabled = False  # Disable the low button
            self.HighButton.Enabled = False  # Disable the high button
            self.AgainButton.Enabled = True  # Enable the again button

Now that our __UpdateFunction is ready, all we need to do is call it in the HighButtonClick and LowButtonClick functions. If the HighButton button is pressed, we call the HighButtonClick function with the __UpdateFunction with the “<” parameter. Similarly, if the LowButtion is pressed, we call the LowButtonClick function with the “>” parameter in the LowButtonClick function. Here is what our button functions look like:

def HighButtonClick(self, Sender):
        self.__UpdateGame("<")  # If the high button is clicked, update the game

    def LowButtonClick(self, Sender):
        self.__UpdateGame(">")  # If the low button is clicked, update the game

We are now ready to implement our final AgainButtonClick function.

The purpose of the AgainButtonClick function is to reset the game. This button will only be enabled when the game ends, which we have defined in our __UpdateFunction. Therefore, to implement this function, we all need to generate a new random number, reset all the buttons, and reset all the labels to their default values. Here is what our AgainButtonClick function looks like:

def AgainButtonClick(self, Sender):
        self.Score = 0  # Reset the score to 0
        self.ScoreLabel.Text = "Score:" + str(self.Score)  # Update the score label
        self.GuessNumber = random.randint(0, 10)  # Generate a new random number between 0 and 10
        self.Number.Text = str(self.GuessNumber)  
        self.LowButton.Enabled = True  # Enable the low button
        self.HighButton.Enabled = True  # Enable the high button
        self.AgainButton.Enabled = False  # disable the again button
        self.StatusLabel.Text = ""  # Clear the status label

Here is what our final Game.py file looks like:

import os
from delphifmx import *
import random

class GameForm(Form):

    def __init__(self, owner):
        self.ScoreLabel = None
        self.Number = None
        self.HighButton = None
        self.LowButton = None
        self.AgainButton = None
        self.StatusLabel = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Game.pyfmx"))

        # Additional initializations
        self.Score = 0
        self.GuessNumber = random.randint(0, 10)  # Generate a random number between 0 and 10
        self.Number.Text = str(self.GuessNumber)

    def __UpdateGame(self, compare):
        self.StatusLabel.Text = ""  # Clear the status label each time button clicked
        prev = self.GuessNumber  # Store the guess number
        self.GuessNumber = random.randint(0, 10)  # Generate a new random number within a range
        self.Number.Text = str(self.GuessNumber)
        if compare==">" and prev > self.GuessNumber: # If the player guessed lower and the new number is actually lower
            self.StatusLabel.Text = "That's right"
            self.Score +=1  # Increment the score
            self.ScoreLabel.Text = "Score:" + str(self.Score)  
        elif compare=="<" and prev <= self.GuessNumber:  # If the player guessed higher and the new number is actually higher
            self.StatusLabel.Text = "That's right"
            self.Score +=1  # Increment the score
            self.ScoreLabel.Text = "Score:" + str(self.Score)
        else:  # If the player guessed wrong
            self.StatusLabel.Text = "GAME OVER"
            self.LowButton.Enabled = False  # Disable the low button
            self.HighButton.Enabled = False  # Disable the high button
            self.AgainButton.Enabled = True  # Enable the again button

    def HighButtonClick(self, Sender):
        self.__UpdateGame("<")  # If the high button is clicked, update the game

    def LowButtonClick(self, Sender):
        self.__UpdateGame(">")  # If the low button is clicked, update the game

    def AgainButtonClick(self, Sender):
        self.Score = 0  # Reset the score to 0
        self.ScoreLabel.Text = "Score:" + str(self.Score)  # Update the score label
        self.GuessNumber = random.randint(0, 10)  # Generate a new random number between 0 and 10
        self.Number.Text = str(self.GuessNumber)  
        self.LowButton.Enabled = True  # Enable the low button
        self.HighButton.Enabled = True  # Enable the high button
        self.AgainButton.Enabled = False  # disable the again button
        self.StatusLabel.Text = ""  # Clear the status label

How Does the Desktop App look like?

Now, we can run our app by executing HiLoGame.py. Here is what MainForm looks like:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the running app

We can start the game by clicking the START button. Here is what our GameForm looks like:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the game in action

Can I Create an Android App From this Code?

Now that our HiLoGame is running let’s convert this into an Android application.

But before we can create our app, we need to make important changes to the code to allow us to run our project on Android. Let’s create a new file named HiLoGame_Android.py and paste the contents of HiLoGame.py.

Next, open up the HiLoGame_Android.py file and start making some changes. Firstly, because Delphi initialed Android applications automatically, we don’t need to initialize it or set a title manually. The Application.MainForm doesn’t need to be initialized either but just needs a variable. Finally, like the MainForm initialization, we don’t need to launch or destroy the program as Android handles both tasks. Here are the contents of our final HiLoGame_Android.py:

from delphifmx import *
from MainMenu import MainForm

def main():
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()

if __name__ == '__main__':
    main()

Now open up FMXBuilder and click on Project > New project on the toolbar. Enter the name of the project that you want to build here. Here we define our project as HiLoGame.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - creating a new project

Next, add your Python and .pyfmx files by right-clicking on the App and selecting Add file. We won’t add HiLoGame.py, but instead will be adding the HiLoGame_Android.py. HiLoGame.py will only be used to run our desktop application.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - add a file

Now, right-click on HiLoGame_Android.py file and set it to the main file.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - setting the py file to main

Now that everything is ready, we must create the .apk file for the app using the Build Project button.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - building the project

When the .apk is fully generated, you will be prompted with a “Build process done” message in the Messages box. You can then check out your generated file in the pathtoPythonFMXBuilderGUIexeFolderappsHiLoGamebin folder.

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the lcoation of the APK

Now, you must copy the .apk file into your phone’s storage. Next, install this file by accessing it on your Android device. Once your app is installed, you can use it like any other app on your phone.

Does the App Run as Expected on an Android Device?

Here is what our app looks like:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - testing the app on an Android device

When we press the start button, we are taken to the main game screen:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the game running on an Android device

Upon making a correct guess, the user is prompted and their score is incremented:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - running on Android

Upon an incorrect guess for the next number, the user is prompted and the play again button is enabled while the other two buttons are disabled:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the game in action

Now, we can reset the game and play again:

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - a screen

Are You Ready to Create Other Android Apps with Delphi For Python?

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - are you ready?

With the help of a robust ecosystem of development tools and libraries, cross-platform compatibility, and access to the FireMonkey GUI framework, DelphiFMX is a strong and adaptable solution for Python developers. DelphiFMX is the perfect option for developers wishing to create cross-platform games that may appeal to a wider audience, including Android users, thanks to its aesthetically pleasing and highly functional user interfaces.

We invite Python developers interested in producing aesthetically appealing and highly functioning games to learn more about DelphiFMX and utilize its features and tools. You can speed up the app creation process and produce apps that work flawlessly on several platforms with DelphiFMX. 

So, what are you waiting for? Start building your next app with DelphiFMX today.

What Are Some FAQs Related to this Article?

How to Create A Hi-Lo Game With DelphiFMX Python GUI Package - the FAQ screen showing on a monitor

Can I create apps for mobile devices using DelphiFMX?

DelphiFMX provides cross-platform support, allowing developers to build apps for various mobile devices, including Android and iOS.

What is the best approach to building games with Python and DelphiFMX?

The best approach to building games with Python and DelphiFMX is to start with a clear design and choose appropriate game mechanics. Then, utilize the features of DelphiFMX to create a visually appealing and highly functional user interface. Finally, optimize the game’s performance and test it thoroughly before release.

What resources are available to help me learn how to use DelphiFMX for game development?

Many resources are available to help you learn how to use DelphiFMX for game development. The Embarcadero website provides documentation, tutorials, and sample projects to get you started. Additionally, there are online communities and forums where developers can ask questions and share ideas about game development with DelphiFMX. Lastly, Delphi’s ebook would help you understand the entire Delphi ecosystem much better, allowing you to kickstart your career in Python GUI!

Is Python the only language I can use with DelphiFMX for app development?

No, DelphiFMX supports several programming languages, including C++ and Object Pascal. However, Python developers may find it beneficial to use DelphiFMX. It provides an efficient way to build graphical user interfaces (GUIs) and supports cross-platform development, making it easier to create apps that work across multiple devices and operating systems.

The post How to Create A Hi-Lo Game With DelphiFMX Python GUI Package first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-hi-lo-game-with-delphifmx-python-gui-package/feed/ 0 10301
How To Create a Memory Game For Android With DelphiFMX Python Package https://pythongui.org/how-to-create-a-memory-game-for-android-with-delphifmx-python-package/ https://pythongui.org/how-to-create-a-memory-game-for-android-with-delphifmx-python-package/#respond Tue, 06 Jun 2023 14:48:44 +0000 https://pythongui.org/?p=10184 Memory games have long been a popular way to kill time while improving cognitive skills. It’s no surprise that, with the increase of mobile devices, memory games have made their way onto our smartphones and...

The post How To Create a Memory Game For Android With DelphiFMX Python Package first appeared on Python GUI.

]]>
Memory games have long been a popular way to kill time while improving cognitive skills. It’s no surprise that, with the increase of mobile devices, memory games have made their way onto our smartphones and tablets. If you want to create a memory game for Android devices, Delphi is a strong tool to assist you. In this article, we’ll look at how to make a memory game for Android with Delphi, a rapid application creation tool.

Why Create a Memory Game Using Delphi For Python?

How To Create a Memory Game For Android With DelphiFMX Python Package

Using Delphi for Python to create a memory game can be advantageous for Python developers looking for an efficient way to build Graphical User Interfaces (GUIs) for their game. Delphi for Python gives developers powerful tools and cross-platform support. It allows them to build visually appealing and functional user interfaces that operate across multiple platforms without writing separate code for each. Developers can build sophisticated and flexible GUIs with access to the FireMonkey GUI framework, making the development process faster and more efficient.

Furthermore, Delphi’s UI design tools, such as the Delphi4PythonExporter tool, can help accelerate development while ensuring that the resulting GUIs are functional and aesthetically appealing. Finally, Delphi Community Edition and PythonFMXBuilder are open-source tools ideal for developers who prefer to work with open-source tools whenever feasible. In conclusion, using Delphi for Python to create a memory game can assist Python developers in streamlining their development process and ensuring that their game works smoothly and efficiently across all platforms.

How to Create this Game as a Desktop App?

How To Create a Memory Game For Android With DelphiFMX Python Package - creating the app with a laptop

Delphi offers powerful tools that make developing visually appealing and engaging games easily. So, let’s dive in and start creating your own memory game for Android using Delphi.

What Are the Requirements to Create this App?

To create the memory game desktop app, you must have Delphi installed on your device and the FireMonkey GUI framework. Additionally, you will need a text editor or IDE that supports Python, such as PyScripter and the Delphi4PythonExporter tool.

If you don’t have these tools installed, we recommend checking out the article “Powerful Python GUI Project Setup” to help you get started. Once you have all the required tools, you can proceed with the tutorial to create your memory game desktop app using Delphi

You can grab the code for this tutorial from our GitHub repository using the following link: https://github.com/Embarcadero/PythonBlogExamples/tree/main/Memory_Game

How to Create Forms in Delphi CE?

Begin by opening Delphi CE and creating a blank application. To do this, navigate to File > New > Multi-Device Application > Blank Application > Ok. In this tutorial, we have named our project MemoryGame.

How To Create a Memory Game For Android With DelphiFMX Python Package - a screenshot of the IDE

If you are not familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.

How To Create a Memory Game For Android With DelphiFMX Python Package - Ebook splash screen

To start, let’s give our form a name. Right-click on the form and select QuickEdit. Here, we will name our form MainForm with the caption MainMenu.

How To Create a Memory Game For Android With DelphiFMX Python Package - Screen 1

Next, let’s resize our form. Go to the object inspector and search ClientHeight and ClientWidth in the properties tab. We will set them to 500 and 360, respectively.

How To Create a Memory Game For Android With DelphiFMX Python Package - altering the client height

We will also rename the source file of our main form to MainMenu.pas to make it easier to keep track of.

How To Create a Memory Game For Android With DelphiFMX Python Package - project manager

This form will be the primary screen where users can start the game. To enhance the user experience, let us add a label that will display the title of our app. To do this, navigate to the standard palette and locate the TLabel component. Next, drag and drop this component onto the form.

How To Create a Memory Game For Android With DelphiFMX Python Package - palette

To modify the text style to reflect the title, we will use TextSettings. Navigate to the Object Inspector and locate TextSettings. Select Font beneath it and click “...” to see options for modifying the label’s font, size, and style based on your preferences. Here we have set our font family as Britannic with a font size of 48.

How To Create a Memory Game For Android With DelphiFMX Python Package - fonts

Rename each label’s text by right-clicking on the label and selecting Quick Edit. Following an intuitive naming convention for the labels is crucial so they can be tracked more easily. Here, we called our TLabel component “Title” with the text “Memory Game“.

How To Create a Memory Game For Android With DelphiFMX Python Package - main screen

Here we also centered the text using the HorzAlign and VertAlign properties to ensure that the text appears symmetrical.

How To Create a Memory Game For Android With DelphiFMX Python Package - changing the alignment

We can adjust the form’s background color by navigating to the Object Inspector and selecting the form’s fill property.

How To Create a Memory Game For Android With DelphiFMX Python Package - picking colors
11-7149161

Finally, we need a method for navigating to the next form where the main game would be played. To accomplish this, go to the Palette and add a button using the TButton component.

How To Create a Memory Game For Android With DelphiFMX Python Package - searching for a button
How To Create a Memory Game For Android With DelphiFMX Python Package - Screen  with the button

Let’s give this button a suitable name. Additionally, we changed the font size and style of these button texts (as we did for the TLabels above) to make them more prominent. Here, we used Segoe UI with a font size of 18.

How To Create a Memory Game For Android With DelphiFMX Python Package - fonts

After making these changes, our form will be much more visually appealing:

How To Create a Memory Game For Android With DelphiFMX Python Package - memory game screen

Now, let’s add some styles to our forms using the power of DelphiFMX styles. The Delphi ebook bundle comes shipped with a variety of styles that you can use for your applications.

So first download the free ebook bundle and extract the styles zip file into a folder of your choosing. Now select the style you want to choose, for this project we will be using Light.style. You can find other styles online, such as delphistyles.com.

Head to the Palette and search of the TStyleBook object. Add this to your form.

How To Create a Memory Game For Android With DelphiFMX Python Package - adding a stylebook
How To Create a Memory Game For Android With DelphiFMX Python Package - stylebook on the main form

Next, double click on the object. This will open up your Style Designer. Now press the click on the open button.

How To Create a Memory Game For Android With DelphiFMX Python Package - the style designer

Now head to the directory of your extracted style files, select the style of your choosing, and click on exit. Next, select the form and head over to the Object Inspector. Here we will search for the StyleBook property. Select the drop down menu and select StyleBook1.

How To Create a Memory Game For Android With DelphiFMX Python Package - filtering the object inspector to look for the stylebook

This will apply the style to your form. Here is what our final MainForm looks like:

How To Create a Memory Game For Android With DelphiFMX Python Package - main screen

Now that we are done with the main form of our app, let’s create a new form that will display our Memory Game. So right-click on MemoryGame.exe and select Add New > Multi-Device Form.

How To Create a Memory Game For Android With DelphiFMX Python Package - add a new multi device form

This will create a new form which we have named as GameForm, and the corresponding source file as Game.pas. We have also renamed the form caption to Memory Game, and changed the form dimensions to match our MainForm.

Next, let’s start by adding labels and buttons to our form. We will first add two labels to the top of our form which we will name ScoreLabel and TriesLabel, with the captions Score: and Tries: respectively. These labels will help us display the score the player has scored as well as the number of tries they have made.

How To Create a Memory Game For Android With DelphiFMX Python Package - the score screen

We have also changed their font style to Britannica with a font size of 24.

Next, we will add 8 buttons to our form that will help us play our game.

How To Create a Memory Game For Android With DelphiFMX Python Package - score screen expanded

For each button we added a default caption as ? and named each of them as Button1, Button2, and so on. We also added two extra buttons Back and Reset that will help us navigate our forms. As you can see we have disabled the Reset button by default which will only open when the player has finished the game.

Finally, we added 3 new labels to the form. The Card1 and Card2 label will help the user remember the card he had selected in his try. The additional label, which we have named Status, lies right above the Back and Reset buttons. It will help display the status of the game. Finally add the Light style to our form. Here is what our final form looks like:

How To Create a Memory Game For Android With DelphiFMX Python Package - final form appearance

Now that our forms are ready, the last step would be to add functionality to each button. So navigate to each form and double-click each button to create an OnClick method for that button in your .pas file corresponding to your .fmx form. This will enable you to add distinct functionality for each button when clicked.

How To Create a Memory Game For Android With DelphiFMX Python Package - editing the code in the IDE

After creating the OnClick method for each button, adding at least one comment (//) to each procedure is recommended to preserve it when you save the Python file. As we do not export the run-time implementation using the Delphi4PythonExporter, there is no need to write any run-time implementation code.

How To Create a Memory Game For Android With DelphiFMX Python Package - editing in the IDE 2

How Can We Export this App as Python Code?

Now that our forms are ready, we can save our project as a Python script by selecting Tools > Export To Python > Export Current Entire Project.

How To Create a Memory Game For Android With DelphiFMX Python Package - exporting the final project

Here rename your project to MemoryGame, and select the main form as MainForm. Finally, select the directory of your choosing and click Export:

How To Create a Memory Game For Android With DelphiFMX Python Package - the export project screen settings

Delphi will generate 5 files, 3 Python scripts named MainMenu.py, Game.py, and MemoryGame.py. The Game.py, MainMenu.py python files contain the classes for the individual forms, and the MemoryGame.py is used to launch our Delphi app. Along with each Python file, Delphi also generates a .pyfmx script of the same name as each form that contains the visual information of that form. Now, let’s take a look at the exported Python files.

MemoryGame.py:

from delphifmx import *
from MainMenu import MainForm

def main():
    Application.Initialize()
    Application.Title = 'MemoryGame'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Game.py:

import os
from delphifmx import *

class GameForm(Form):

    def __init__(self, owner):
        self.ScoreLabel = None
        self.TriesLabel = None
        self.Button1 = None
        self.Button2 = None
        self.Button3 = None
        self.Button4 = None
        self.Button5 = None
        self.Button6 = None
        self.Button7 = None
        self.Button8 = None
        self.Button9 = None
        self.Button10 = None
        self.BackButton = None
        self.ResetButton = None
        self.Card1Label = None
        self.Card2Label = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Game.pyfmx"))

    def Button1Click(self, Sender):
        pass

    def Button2Click(self, Sender):
        pass

    def Button3Click(self, Sender):
        pass

    def Button4Click(self, Sender):
        pass

    def Button5Click(self, Sender):
        pass

    def Button6Click(self, Sender):
        pass

    def Button7Click(self, Sender):
        pass

    def Button8Click(self, Sender):
        pass

    def Button9Click(self, Sender):
        pass

    def Button10Click(self, Sender):
        pass

    def BackButtonClick(self, Sender):
        pass

    def ResetButtonClick(self, Sender):
        pass

MainMenu.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.StartButton = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainMenu.pyfmx"))

    def StartButtonClick(self, Sender):
        pass

How to Add Functionality to This App Using the Delphi FMX Library?

Now that our forms are ready, we can start adding functionality to our game. Let’s start by opening up MainMenu.py and navigating to the StartButtonClick function. 

The MainForm only serves the purpose of launching the game and the StartButtonClick will help us do that. So start by importing the GameForm, from Game.py:

from Game import GameForm

Next, in the StartButtonClick function, create a new variable named Game, and create a new instance of the GameForm. We will then use the Show() method to display our GameForm. Here is what the StartButtonClick function looks like:

def StartButtonClick(self, Sender):
        Game = GameForm(self)
        Game.Show()

Here is what our MainMenu.py looks like:

import os
from delphifmx import *
from Game import GameForm

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.StartButton = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainMenu.pyfmx"))

    def StartButtonClick(self, Sender):
        Game = GameForm(self)
        Game.Show()

Now that our MainForm is ready, let’s now add functionality to our GameForm. Start by opening Game.py and navigating to the __init__ function. In the __init__ function the first thing we will have to do is initialize our score and tries. Along with this we will keep track of the previous attempt by the user and add a flag that will help us later on:

self.prev = (self.Button1, "") # Store the first selected card data
        self.score = 0 # Game score counter
        self.tries = 0 # Tries counter
        self.flag = 0 # Flag to check if one complete try/guess has been made

Next, we will call a function called __RandomizeCards(), which we will define later:

# Randomly assign values to all cards at the start
        self.__RandomizeCards()

Here is what our final __init__ function looks like:

def __init__(self, owner):
        self.Button1 = None
        self.Button2 = None
        self.Button3 = None
        self.Button4 = None
        self.Button5 = None
        self.Button6 = None
        self.Button7 = None
        self.Button8 = None
        self.Button9 = None
        self.Button10 = None
        self.ScoreLabel = None
        self.Card1Label = None
        self.Card2Label = None
        self.Status = None
        self.BackButton = None
        self.ResetButton = None
        self.TriesLabel = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Game.pyfmx"))

        # Randomly assign values to all cards at the start
        self.__RandomizeCards()

        self.prev = (self.Button1, "")  # Store the first selected card data
        self.score = 0  # Game score counter
        self.tries = 0  # Tries counter
        self.flag = 0  # Flag to check if one complete try/guess has been made

Now the lets move on and define the __RandomizeCards() function. Let’s start by importing random:

# Additional imports
import random

The __RandomizeCards() function uses the Keys from all the buttons that we have defined for our GameForm. It then shuffles a bunch of alphabets that we have defined in our values variable. Finally, it assigns each button a sigle value by the means of a dictionary. This dictionary is stored in a new variable called self.d. Here is what our final __RandomizeCards() function looks like:

def __RandomizeCards(self):
        # Define the keys for the dictionary
        keys = ["Button1", "Button2", "Button3", "Button4", "Button5",
                "Button6", "Button7", "Button8", "Button9", "Button10"]

        # Define the values to randomly select from
        values = ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E"]

        # Shuffle the values randomly
        random.shuffle(values)

        # Create the dictionary
        self.d = dict(zip(keys, values))

Now let’s define our Back and Reset buttons. Start by going to the BackButtonClick function. Here all we need to do is destroy the current form. So here is what our BackButtonClick function will look like:

# Go back to the main screen
    def BackButtonClick(self, Sender):
        self.Destroy()

Next, we need to define our Reset button. The Reset button will call the __RandomizeCards function once again, while resetting the tries, score, flag and all the necessary labels of our form. It will then disable the Reset button and reset the text on all the buttons on our form. Here is what our ResetButtonClick function will look like:

# Play game again so bring back to initial state
    def ResetButtonClick(self, Sender):
        # Randomize the card/button values and reset all labels
        self.__RandomizeCards()
        self.prev = (self.Button1, "")
        self.score = 0
        self.tries = 0
        self.flag = 0
        self.TriesLabel.Text = "Tries: "
        self.ScoreLabel.Text = "Score: "
        self.Status.Text = ""
        self.ResetButton.Enabled = False

        # Hide all cards/buttons (so show ?) and enable them so that they can be clicked
        Buttons = [self.Button1, self.Button2, self.Button3, self.Button4, self.Button5,
                   self.Button6, self.Button7, self.Button8, self.Button9, self.Button10]
        for Button in Buttons:
            Button.Text = "?"
            Button.Enabled = True

Now let’s define the main functionality of our game. To do this, let’s create a function called __Functionality that takes in two parameters, the button that presses it, as well as the name of the button. The function uses the name parameter in self.d to get the value assigned to it:

def __Functionality(self, Button, name):
        val = self.d[name]  # Get value against this button

Now that we have our value, we need to check whether the user is one his first or second try. To do this we will use the flag variable. If flag is equal to 1 then the user is on his second try.

Now if the user is on his second try, we first need to update the tries label and reset the flag to 0:

def __Functionality(self, Button, name):
        val = self.d[name]  # Get value against this button

        # If one complete try has been done
        if self.flag == 1:
            self.tries += 1  # Then increase tries counter
            self.TriesLabel.Text = "Tries: "+str(self.tries)
            self.flag = 0  # Reset tires flag

Next, we need to check whether the value of the previous try was the same as this new try. For this we will use the self.prev variable. Now if the new values match, we increment the score and update the relevant labels. Additionally, we also disable the new selected button, as well as the previous button. 

Finally, once we have made the relevant updates, we need to check if the current score is equal to 5. This would indicate that the user has selected all buttons, and thus has won the game. In this case, we update the Status label and enable the Reset button. Here is what our __Functionality function looks like so far:

def __Functionality(self, Button, name):
        val = self.d[name]  # Get value against this button

        # If one complete try has been done
        if self.flag == 1:
            self.tries += 1  # Then increase tries counter
            self.TriesLabel.Text = "Tries: "+str(self.tries)
            self.flag = 0  # Reset tires flag

            # If the two cards/buttons selected are the same
            if self.prev[1] == val:
                self.score += 1  # Then increase score counter
                self.ScoreLabel.Text = "Score: "+str(self.score)
                Button.Text = val  # Show the value behind
                Button.Enabled = False  # Disable the cards/buttons so that they cannot be clicked
                self.prev[0].Enabled = False

                # If score is 5 then all the cards/buttons have been matched
                if self.score == 5:
                    self.Status.Text = "You Win!"
                    self.ResetButton.Enabled = True  # Now reset button can be clicked

Now, we add a check if the two buttons selected are not the same. In that case, we show the respective cards in the Card1Label and Card2Label, we then hide the previous button and reset the self.prev variable:

def __Functionality(self, Button, name):
        val = self.d[name]  # Get value against this button

        # If one complete try has been done
        if self.flag == 1:
            self.tries += 1  # Then increase tries counter
            self.TriesLabel.Text = "Tries: "+str(self.tries)
            self.flag = 0  # Reset tires flag

            # If the two cards/buttons selected are the same
            if self.prev[1] == val:
                self.score += 1  # Then increase score counter
                self.ScoreLabel.Text = "Score: "+str(self.score)
                Button.Text = val  # Show the value behind
                Button.Enabled = False  # Disable the cards/buttons so that they cannot be clicked
                self.prev[0].Enabled = False

                # If score is 5 then all the cards/buttons have been matched
                if self.score == 5:
                    self.Status.Text = "You Win!"
                    self.ResetButton.Enabled = True  # Now reset button can be clicked

            # If the two cards/buttons selected are not the same
            else:
                # Show the respective values below the cards
                self.Card1Label.Text = "Card 1: " + self.prev[1]
                self.Card2Label.Text = "Card 2: " + val
                Button.Text = val
                Button.Text = "?"  # Hide the cards again0
                self.prev[0].Text = "?"

Finally, to complete the function we add an else for when the user is on his first try. The Card1Label and Card2Label will remain the same, but the selected button flips to show the value behind it. We then update the flag to 1 and then update the self.prev variable. Here is what our completed __Functionality function looks like:

def __Functionality(self, Button, name):
        val = self.d[name]  # Get value against this button

        # If one complete try has been done
        if self.flag == 1:
            self.tries += 1  # Then increase tries counter
            self.TriesLabel.Text = "Tries: "+str(self.tries)
            self.flag = 0  # Reset tires flag

            # If the two cards/buttons selected are the same
            if self.prev[1] == val:
                self.score += 1  # Then increase score counter
                self.ScoreLabel.Text = "Score: "+str(self.score)
                Button.Text = val  # Show the value behind
                Button.Enabled = False  # Disable the cards/buttons so that they cannot be clicked
                self.prev[0].Enabled = False

                # If score is 5 then all the cards/buttons have been matched
                if self.score == 5:
                    self.Status.Text = "You Win!"
                    self.ResetButton.Enabled = True  # Now reset button can be clicked

            # If the two cards/buttons selected are not the same
            else:
                # Show the respective values below the cards
                self.Card1Label.Text = "Card 1: " + self.prev[1]
                self.Card2Label.Text = "Card 2: " + val
                Button.Text = val
                Button.Text = "?"  # Hide the cards again0
                self.prev[0].Text = "?"

        # If just one card/button has been selected and
        # the other has to be selected to complete the guess
        else:
            self.Card1Label.Text = "Card 1:"
            self.Card2Label.Text = "Card 2:"
            Button.Text = val  # Show the value behind
            self.flag += 1  # Increase flag to show that first card selected from the try and one more left
            self.prev = (Button, val)  # Store this button info to compare

Now all we need to do is call the __Functionality function in each button. So head over to each button and call the function. Here is what this looks like for Button1:

def Button1Click(self, Sender):
        self.__Functionality(self.Button1, "Button1")

Here is what our final Game.py file looks like:

import os
from delphifmx import *
# Additional imports
import random


class GameForm(Form):

    def __init__(self, owner):
        self.Button1 = None
        self.Button2 = None
        self.Button3 = None
        self.Button4 = None
        self.Button5 = None
        self.Button6 = None
        self.Button7 = None
        self.Button8 = None
        self.Button9 = None
        self.Button10 = None
        self.ScoreLabel = None
        self.Card1Label = None
        self.Card2Label = None
        self.Status = None
        self.BackButton = None
        self.ResetButton = None
        self.TriesLabel = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Game.pyfmx"))

        # Randomly assign values to all cards at the start
        self.__RandomizeCards()

        self.prev = (self.Button1, "")  # Store the first selected card data
        self.score = 0  # Game score counter
        self.tries = 0  # Tries counter
        self.flag = 0  # Flag to check if one complete try/guess has been made

    def __RandomizeCards(self):
        # Define the keys for the dictionary
        keys = ["Button1", "Button2", "Button3", "Button4", "Button5",
                "Button6", "Button7", "Button8", "Button9", "Button10"]

        # Define the values to randomly select from
        values = ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E"]

        # Shuffle the values randomly
        random.shuffle(values)

        # Create the dictionary
        self.d = dict(zip(keys, values))

    def __Functionality(self, Button, name):
        val = self.d[name]  # Get value against this button

        # If one complete try has been done
        if self.flag == 1:
            self.tries += 1  # Then increase tries counter
            self.TriesLabel.Text = "Tries: "+str(self.tries)
            self.flag = 0  # Reset tires flag

            # If the two cards/buttons selected are the same
            if self.prev[1] == val:
                self.score += 1  # Then increase score counter
                self.ScoreLabel.Text = "Score: "+str(self.score)
                Button.Text = val  # Show the value behind
                Button.Enabled = False  # Disable the cards/buttons so that they cannot be clicked
                self.prev[0].Enabled = False

                # If score is 5 then all the cards/buttons have been matched
                if self.score == 5:
                    self.Status.Text = "You Win!"
                    self.ResetButton.Enabled = True  # Now reset button can be clicked

            # If the two cards/buttons selected are not the same
            else:
                # Show the respective values below the cards
                self.Card1Label.Text = "Card 1: " + self.prev[1]
                self.Card2Label.Text = "Card 2: " + val
                Button.Text = val
                Button.Text = "?"  # Hide the cards again0
                self.prev[0].Text = "?"

        # If just one card/button has been selected and
        # the other has to be selected to complete the guess
        else:
            self.Card1Label.Text = "Card 1:"
            self.Card2Label.Text = "Card 2:"
            Button.Text = val  # Show the value behind
            self.flag += 1  # Increase flag to show that first card selected from the try and one more left
            self.prev = (Button, val)  # Store this button info to compare

    # Implement this functionality when any of the 10 buttons/cards are selected
    def Button1Click(self, Sender):
        self.__Functionality(self.Button1, "Button1")

    def Button2Click(self, Sender):
        self.__Functionality(self.Button2, "Button2")

    def Button3Click(self, Sender):
        self.__Functionality(self.Button3, "Button3")

    def Button4Click(self, Sender):
        self.__Functionality(self.Button4, "Button4")

    def Button5Click(self, Sender):
        self.__Functionality(self.Button5, "Button5")

    def Button6Click(self, Sender):
        self.__Functionality(self.Button6, "Button6")

    def Button7Click(self, Sender):
        self.__Functionality(self.Button7, "Button7")

    def Button8Click(self, Sender):
        self.__Functionality(self.Button8, "Button8")

    def Button9Click(self, Sender):
        self.__Functionality(self.Button9, "Button9")

    def Button10Click(self, Sender):
        self.__Functionality(self.Button10, "Button10")

    # Go back to the main screen
    def BackButtonClick(self, Sender):
        self.Destroy()

    # Play game again so bring back to initial state
    def ResetButtonClick(self, Sender):
        # Randomize the card/button values and reset all labels
        self.__RandomizeCards()
        self.prev = (self.Button1, "")
        self.score = 0
        self.tries = 0
        self.flag = 0
        self.TriesLabel.Text = "Tries: "
        self.ScoreLabel.Text = "Score: "
        self.Status.Text = ""
        self.ResetButton.Enabled = False

        # Hide all cards/buttons (so show ?) and enable them so that they can be clicked
        Buttons = [self.Button1, self.Button2, self.Button3, self.Button4, self.Button5,
                   self.Button6, self.Button7, self.Button8, self.Button9, self.Button10]
        for Button in Buttons:
            Button.Text = "?"
            Button.Enabled = True

Can I Create this Game for Android Devices?

How To Create a Memory Game For Android With DelphiFMX Python Package - a laptop showing the free ebook download page

Let’s proceed to convert our time widget application into an Android application.

As the Delphi4Python Exporter only exports the initialization logic for desktop-based applications, we need PythonFMXBuilder to convert it to an Android app. To begin, open FMXBuilder, click on the toolbar’s Project > New project option, and provide the project’s name. We named ours MemoryApp.

How To Create a Memory Game For Android With DelphiFMX Python Package - create new project dialog

Before adding our Python files, we must modify some code to allow our project to run on Android. First, we need to create a new file called MemoryGame_Android.py and copy the contents of MemoryGame.py. Next, add your Python and other supporting project files used to build your application. We won’t add MemoryGame.py; it will only run our desktop application.

How To Create a Memory Game For Android With DelphiFMX Python Package - finding the .py project code

Right-click on the MemoryGame_Android.py file and set it as the main file. Before building the app, we need to make some important code changes.

How To Create a Memory Game For Android With DelphiFMX Python Package - setting the main execution point

In Android applications, Delphi applications are automatically initialized. Therefore, we don’t need to initialize or set a title manually. The Application.MainForm variable only needs to be initialized without launching or destroying the program because Android handles both tasks.

How To Create a Memory Game For Android With DelphiFMX Python Package - this is what main looks like

After making the necessary code changes, save the file.

Now connect your mobile to your computer device and enable USB tethering. Next, click on the refresh icon and select your device from the drop down menu.

How To Create a Memory Game For Android With DelphiFMX Python Package - selecting your device from the dropdown menu

Finally, choose your device and click on the Run Project button. This will install the app on your Android phone and run it.

29-1547677

This will install the app directly on your mobile device.

Is this App Working as Expected?

Now that our app is ready, you can launch it on your Android device and be greeted with the MainForm screen:

How To Create a Memory Game For Android With DelphiFMX Python Package - testing the finished game app

Next click on the START button, which will open up the GameForm:

How To Create a Memory Game For Android With DelphiFMX Python Package - testing the finished game app 2

As you can see the Reset button is disabled and will only open when the game has finished. You can then start playing the game. Clicking on each button will reveal the letter behind that button:

How To Create a Memory Game For Android With DelphiFMX Python Package - testing the finished game app 3

If you don’t guess your alphabet in your try, then the Card1 and Card2 labels show your previous attempt:

How To Create a Memory Game For Android With DelphiFMX Python Package - testing the finished game app 4

If you can guess a button correctly, then your score increments and the buttons get disabled:

How To Create a Memory Game For Android With DelphiFMX Python Package - testing the finished game app 5

Finally, you can continue along with the game until you get everything right:

How To Create a Memory Game For Android With DelphiFMX Python Package - testing the finished game app 6

As you can see the Reset button gets enabled once the game is finished. You can click on it to restart the game with new random alphabets.

Are You Ready to Create Other Apps With Delphi?

How To Create a Memory Game For Android With DelphiFMX Python Package - a man looking at a laptop screen which he is holding in his hand. The laptop is showing the RAD Studio 11.3 download page

To summarize, developing a memory game for Android with Delphi is a rewarding experience for developers looking to hone their skills and build engaging applications. Developers can quickly build visually appealing and functional user interfaces that work on multiple devices using Delphi’s powerful tools and cross-platform support. Whether you’re an experienced developer or a beginner, this piece has given you the information you need to create your own memory game for Android using Delphi.

Now that you’ve learned how to make a memorization game in Delphi for Android, it’s time to put your knowledge to use. You can improve your coding skills and make a game that is engaging and enjoyable to play by doing so. Remember to test your game on various devices to ensure it works smoothly and efficiently. 

Why wait? Start making your own memory game with Delphi for Android today to advance your programming skills.

What Are Some FAQs Related to this Tutorial?

How To Create a Memory Game For Android With DelphiFMX Python Package - a laptop showing the FAQ page of the website

What is Delphi?

Delphi is a rapid application development tool for Windows that allows developers to create Graphical User Interfaces (GUIs) quickly and easily.

What is FireMonkey?

FireMonkey is a powerful, flexible GUI framework to create visually appealing and functional user interfaces.

Is Delphi for Python a good choice for developing memory games?

Delphi for Python is a great solution for developers looking to create memory games quickly and efficiently, with cross-platform support and powerful tools.

Do I need previous programming experience to use Delphi for Python?

Some programming experience is recommended, but beginners can still use Delphi for Python to create simple applications and gradually improve their skills.

Can I create a memory game for other platforms besides Android using Delphi for Python?

Yes, Delphi for Python provides cross-platform support, allowing you to create memory games that work on various platforms such as Windows, macOS, iOS, and more.

Are there any open-source tools available for Delphi for Python?

Delphi Community Edition and PythonFMXBuilder are open-source tools that offer an ideal solution for developers who prefer open-source tools whenever possible.

The post How To Create a Memory Game For Android With DelphiFMX Python Package first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-memory-game-for-android-with-delphifmx-python-package/feed/ 0 10184
Unlock the Power of Python for Deep Learning with Recurrent Neural Networks https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-recurrent-neural-networks/ https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-recurrent-neural-networks/#respond Tue, 30 May 2023 10:00:00 +0000 https://pythongui.org/?p=10347 Deep learning algorithms can work with almost any type of data and require massive amounts of computing power and data to solve complex problems. Let us now take a deep dive into one of the...

The post Unlock the Power of Python for Deep Learning with Recurrent Neural Networks first appeared on Python GUI.

]]>
Deep learning algorithms can work with almost any type of data and require massive amounts of computing power and data to solve complex problems. Let us now take a deep dive into one of the most well-known deep learning algorithms: the Recurrent Neural Network (RNN).

If you are looking for Convolutional Neural Network algorithm, read our article about it here:

What is Deep Learning?

Deep learning is a subfield of machine learning that solves complex problems using artificial neural networks. These neural networks are made up of interconnected nodes arranged in multiple layers that extract features from input data. Large datasets are used to train these models, allowing them to detect patterns and correlations that humans would find difficult or impossible to detect.

Deep learning has had a significant impact on artificial intelligence. It has facilitated the development of intelligent systems capable of learning, adapting, and making decisions on their own. Deep learning has enabled remarkable progress in a variety of fields, including image and speech recognition, natural language processing, machine translation, autonomous driving, and many others.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks - diagram of RNN
Example of how RNN used to build Google’s autocompleting feature. Image source: Reference [2].

7 reasons why Python is the perfect choice for Deep Learning

Python has grown in popularity as a programming language due to its versatility and ease of use in a wide range of computer science domains, particularly deep learning. Python has emerged as a top choice among many Machine Learning, Deep Learning, AI, and Data Science professionals due to its extensive range of libraries and frameworks specifically tailored for deep learning.

Here are seven reasons why Python is an excellent deep learning language:

1. Easy to learn

Python is a simple and easy-to-learn language, making it an excellent choice for beginners who want to learn deep learning.

2. Abundant libraries and frameworks

Python has a vast number of libraries and frameworks for deep learning, including TensorFlow, PyTorch, and Keras, which provide a lot of functionality and make it easy to build deep learning models.

3. Great community support

Python has a large and active community that provides excellent support, documentation, and resources for deep learning developers.

4. Versatile language

Python is a versatile language that can be used for a variety of tasks, including data science, automation, and web development.

5. Rapid prototyping

Python’s ease of use and simplicity make it easy to prototype deep learning models quickly.

6. Good visualization libraries

Python has excellent visualization libraries such as Matplotlib, which makes it easier to visualize data and results.

7. Cross-platform support

Python is a cross-platform language, which means that it can be used on multiple operating systems, including Windows, Mac, and Linux.

What is a Recurrent Neural Network (RNN)?

Quoting Reference [10]: “Recurrent neural networks have been an important focus of research and development during the 1990s. They are designed to learn sequential or time-varying patterns. A recurrent net is a neural network with feedback (closed loop) connections [5]. Examples include BAM, Hopfield, Boltzmann machine, and recurrent back propagation nets [8].

Recurrent neural network techniques have been applied to a wide variety of problems. Simple partially recurrent neural networks were introduced in the late 1980s by several researchers including Rumelhart, Hinton, and Williams [12] to learn strings of characters. Many other applications have addressed problems involving dynamical systems with time sequences of events.”

Below is how an unfolded RNN looks like:

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks - an example of an RNN
Structure of unfolded RNN. Image source: Reference [2].

The image below are the comparison between the scheme of 2 advanced RNN example (LSTM and GRU): 

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks - how an RNN works

Illustration of (a) LSTM and (b) gated recurrent units. (a) i, f and o are the input, forget and output gates, respectively. c and c-7359483 denote the memory cell and the new memory cell content. (b) r and z are the reset and update gates, and h and h are the activation and the candidate activation. Image source: Reference [4].

Are there any advanced RNN architectures?

Long Short-Term Memory (LSTM): What is it, and how does it work?

Long Short-Term Memory (LSTM) is a type of recurrent neural network (RNN) that is designed to handle the issue of the vanishing gradient problem faced by traditional RNNs. LSTMs were first proposed by Hochreiter and Schmidhuber in 1997 and have since been used in a wide range of applications, including speech recognition, machine translation, and image captioning [9].

LSTM networks have a unique architecture that allows them to store and access information over long periods. They are built with memory cells that can retain information over time, and gates that control the flow of information into and out of the memory cells. The gates are made up of sigmoid activation functions that determine how much information is passed on to the next time step. The input gate controls how much new information is added to the memory cell, while the output gate determines how much information is output from the memory cell to the next time step. The forget gate is responsible for deciding which information to discard from the memory cell. LSTM networks are designed to learn which information to remember and which to forget, making them well-suited for tasks that require the retention of long-term dependencies.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks - a diagram of a LSTM unit
A schema for LSTM neural network architecture. Image source: Reference [7].

Gated-Recurrent units (GRU): What are they, and how do they work?

Gated Recurrent Units (GRUs) are a type of recurrent neural network (RNN) architecture that was proposed by Cho, et al. in 2014 [4]. Like LSTMs, GRUs are designed to address the issue of the vanishing gradient problem in traditional RNNs. However, GRUs have a simpler architecture than LSTMs, which makes them faster and easier to train.

GRUs have two gates, a reset gate and an update gate, that control the flow of information in the network. The update gate decides how much of the previous hidden state should be retained, and how much new information should be added to the current hidden state. The reset gate determines how much of the previous hidden state should be forgotten and how much new information should be added to the current hidden state. The reset and update gates work together to allow the network to selectively remember or forget information over time, enabling it to handle long-term dependencies. GRUs have been used in a variety of applications, including machine translation, speech recognition, and image captioning, and have shown competitive performance compared to LSTMs while requiring fewer computational resources.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks - diagram of a GRU unit
A diagram for a one-unit Gated Recurrent Unit (GRU). Image source: Reference [6].

How do RNN work to forecast stock prices?

02_rnnarchitecturetoforecaststockprices-8336768
Image source: Reference [1].

The diagram above depicts a simplified representation of recurrent neural networks. If we use simple data to forecast stock prices [46,55,49,45,60,…], each input from X0 to Xt will contain a past value. For example, X0 has 46 and X1 has 55, and these values are used to predict the next number in a sequence [1].

How do I build and train a Recurrent Neural Network from scratch?

Let’s get hands-on with some Python code to build and train your own RNN from scratch.

We will train the LSTM and GRU models to forecast the stock price using Kaggle’s MasterCard stock dataset from May 25th, 2006 to October 11th, 2021 (to download the dataset, see Reference [11]). This is a simple project-based tutorial where we will analyze data, preprocess the data to train it on advanced RNN models, and finally evaluate the results (source: Reference [1]).

Prerequisites for building and training RNNs with Python

The following are some of the prerequisites for performing RNNs with Python in this project:

1. Use pandas for data manipulation

Read more about it here:

Here is a demo video featuring Python pandas, along with other very useful Python libraries:
https://www.youtube.com/watch?v=xvvxgypmqcI

2. NumPy is used for data manipulation in Python

Read more about it here:

3. matplotlib.pyplot for data visualization with Python

Read more about how to use Matplotlib with Python here:

4. scikit-learn for scaling and evaluation

The following article explains how to use scikit-learn in a Delphi app with Python.

5. TensorFlow for modeling

To find out about TensorFlow, which is very popular for AI with Python read the following article. We will also set seeds for reproducibility.

Demo video:

6. Keras for modeling

Keras is one of the de facto standards for Python and AI. 

Demo video:

7. Set seed for reproducibility

We will also set seeds for reproducibility.

Hands-on and selected outputs

The following is the code example for RNN:

# Import libraries.
## Data manipulation.
import numpy as np
import pandas as pd
## Data visualization.
import matplotlib.pyplot as plt
## Scaling & evaluation.
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
## Modeling.
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout, GRU, Bidirectional
from tensorflow.keras.optimizers import SGD
from tensorflow.random import set_seed
## Set seed.
set_seed(455)
np.random.seed(455)

# EDA (exploratory data analysis).
## Load data, handle datetime, & drop unnecessary columns.
dataset = pd.read_csv(
    "data/Mastercard_stock_history.csv", index_col="Date", parse_dates=["Date"]
).drop(["Dividends", "Stock Splits"], axis=1)
print(dataset.head())
## Descriptive statistics.
print(dataset.describe())
## Identify the missing values.
print(dataset.isna().sum())
## Split train-test set, and also plot it.
tstart = 2016
tend = 2020
def train_test_plot(dataset, tstart, tend):
    dataset.loc[f"{tstart}":f"{tend}", "High"].plot(figsize=(16, 4), legend=True)
    dataset.loc[f"{tend+1}":, "High"].plot(figsize=(16, 4), legend=True)
    plt.legend([f"Train (Before {tend+1})", f"Test ({tend+1} and beyond)"])
    plt.title("MasterCard stock price")
    plt.show()
train_test_plot(dataset, tstart, tend)

# Data preprocessing
## Really split the dataset into a train-test set this time.
def train_test_split(dataset, tstart, tend):
    train = dataset.loc[f"{tstart}":f"{tend}", "High"].values
    test = dataset.loc[f"{tend+1}":, "High"].values
    return train, test
training_set, test_set = train_test_split(dataset, tstart, tend)
## Standardize the data using MinMaxScaler, to avoid any outliers/anomalies.
sc = MinMaxScaler(feature_range=(0, 1))
training_set = training_set.reshape(-1, 1)
training_set_scaled = sc.fit_transform(training_set)
## Setup training steps (you can reduce or increase the number of steps to optimize model performance).
def split_sequence(sequence, n_steps):
    X, y = list(), list()
    for i in range(len(sequence)):
        end_ix = i + n_steps
        if end_ix > len(sequence) - 1:
            Break
        seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
        X.append(seq_x)
        y.append(seq_y)
    return np.array(X), np.array(y)
n_steps = 60
features = 1
## Split into samples.
X_train, y_train = split_sequence(training_set_scaled, n_steps)
## Reshaping X_train to fit on the LSTM model.
X_train = X_train.reshape(X_train.shape[0],X_train.shape[1],features)

# LSTM model.
## The LSTM architecture.
model_lstm = Sequential()
model_lstm.add(LSTM(units=125, activation="tanh", input_shape=(n_steps, features)))
model_lstm.add(Dense(units=1))
## Compiling the model.
model_lstm.compile(optimizer="RMSprop", loss="mse")
model_lstm.summary()
## Train model.
model_lstm.fit(X_train, y_train, epochs=50, batch_size=32)

# LSTM Results.
## Implement to the test dataset (repeat preprocessing, standardize, transform & split into samples, reshape, predict, and inverse transform the predictions into standard form).
dataset_total = dataset.loc[:,"High"]
inputs = dataset_total[len(dataset_total) - len(test_set) - n_steps :].values
inputs = inputs.reshape(-1, 1)
### Scaling.
inputs = sc.transform(inputs)
### Split into samples.
X_test, y_test = split_sequence(inputs, n_steps)
### Reshape.
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], features)
### Prediction.
predicted_stock_price = model_lstm.predict(X_test)
### Inverse transform the values.
predicted_stock_price = sc.inverse_transform(predicted_stock_price)
## Plot real vs predicted line chart (visualize the difference between actual & predicted values).
def plot_predictions(test, predicted):
    plt.plot(test, color="gray", label="Real")
    plt.plot(predicted, color="red", label="Predicted")
    plt.title("MasterCard Stock Price Prediction")
    plt.xlabel("Time")
    plt.ylabel("MasterCard Stock Price")
    plt.legend()
    plt.show()
def return_rmse(test, predicted):
    rmse = np.sqrt(mean_squared_error(test, predicted))
    print("The root mean squared error is {:.2f}.".format(rmse))
plot_predictions(test_set,predicted_stock_price)
## Print out RMSE.
return_rmse(test_set,predicted_stock_price)

# GRU model.
## The GRU architecture.
model_gru = Sequential()
model_gru.add(GRU(units=125, activation="tanh", input_shape=(n_steps, features)))
model_gru.add(Dense(units=1))
## Compiling the model.
model_gru.compile(optimizer="RMSprop", loss="mse")
model_gru.summary()
## Train model.
model_gru.fit(X_train, y_train, epochs=50, batch_size=32)

# GRU Results.
GRU_predicted_stock_price = model_gru.predict(X_test)
GRU_predicted_stock_price = sc.inverse_transform(GRU_predicted_stock_price)
plot_predictions(test_set, GRU_predicted_stock_price)
## Print out RMSE.
return_rmse(test_set,GRU_predicted_stock_price)

Let’s run the above code using PyScripter IDE. The following are a selection of the outputs:

1. Descriptive statistics

The .describe() function allows us to thoroughly examine the data. Let’s concentrate on the High column because we’ll be using it to train the model. We can also choose Close or Open columns for a model feature, but High makes more sense because it tells us how high the share prices were on the given day.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Output 1

2. Train-test split and visualize it

The train_test_plot function plots a simple line graph with three arguments: dataset, tstart, and tend. The tstart and tend are time limits expressed in years. We can modify these arguments to examine specific time periods. The line plot is split into two sections: train and test. This will allow us to decide how the test dataset will be distributed.

MasterCard’s stock price has been rising since 2016. It experienced a drop in the first quarter of 2020, but recovered to a stable position in the second half of the year. Our test dataset spans one year, from 2021 to 2022, with the remaining data used for training.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Output 2

3. LSTM model summary

The model consists of a single hidden layer of LSTM and an output layer. You can play around with the number of units, as more units will produce better results. For this experiment, we will set LSTM units to 125, tanh as activation, and set input size.

We don’t have to create LSTM or GRU models from scratch because the TensorFlow library is user-friendly. To construct the model, we will simply use the LSTM or GRU modules.

Finally, we will compile the model with an RMSprop optimizer with mean square error (mse) as the loss function.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Summary 3.

4. Train the LSTM model

The model will be trained using 50 epochs and 32 batch_sizes. You can adjust the hyperparameters to shorten the training time or improve the results. The model training was completed successfully with the lowest possible loss.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Summary 4.

5. LSTM results

The plot_predictions function will generate a line chart comparing Real and Predicted values. This will enable us to see the difference between the actual and predicted values.The return_rmse function takes in test and predicted arguments and prints out the root mean square error (rmse) metric.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Summary 5.

The single-layered LSTM model performed well, as shown by the line plot above.

6. LSTM RMSE

The results appear promising, with the model achieving 6.70 rmse on the test dataset.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Summary 6.

7. GRU model summary

To properly compare the results, we’ll keep everything the same and simply replace the LSTM layer with the GRU layer. The model structure consists of a single GRU layer with 125 units and an output layer.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Summary 7.

8. Train the GRU model

The model was trained successfully with 50 epochs and a batch_size of 32.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Summary 8.

9. GRU results

As we can see, the Real and Predicted values are relatively close. The predicted line chart almost perfectly matches the actual values.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. Example of the GRU results.

10. GRU RMSE

The GRU model achieved 5.50 rmse on the test dataset, outperforming the LSTM model.

Unlock the Power of Python for Deep Learning with Recurrent Neural Networks. The GRU RMSE.

Congratulations, now you have learned how to build and train a Recurrent Neural Network (RNN) from scratch, and successfully run it inside PyScripter IDE with high speed & performance.

Visit our other AI-related articles here:


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL, which makes it simple to create Windows GUIs with Python.


References & further readings

[1] Awan, A. A. (2022).

Recurrent Neural Network Tutorial (RNN). DataCamp Blog. datacamp.com/tutorial/tutorial-for-recurrent-neural-network

[2] Biswal, A. (2023).

Top 10 Deep Learning Algorithms You Should Know in 2023. Simplilearn. simplilearn.com/tutorials/deep-learning-tutorial/deep-learning-algorithm

[3] ChatGPT, personal communication, May 14, 2023.

[4] Chung, J., Gulcehre, C., Cho, K., & Bengio, Y. (2014).

Empirical evaluation of gated recurrent neural networks on sequence modeling. arXiv preprint arXiv:1412.3555.

[5] Fausett, L. (1994).

Fundamentals of neural networks. Prentice Hall, Englewood Cliffs, NJ, 7632.

[6] fdeloche. (2017).

A diagram for a one-unit Gated Recurrent Unit (GRU). Wikimedia. commons.wikimedia.org/wiki/ File:Gated_Recurrent_Unit.svg

[7] fdeloche. (2017).

A schema for LSTM neural network architecture. Wikimedia. commons.wikimedia.org/wiki/File:Long_Short-Term_Memory.svg

[8] Hecht-Nielsen, R. (1990).

Neurocomputing. Addison-Wesley, Reading, PA.

[9] Hochreiter, S., & Schmidhuber, J. (1997).

Long short-term memory. Neural computation, 9(8), 1735-1780.

[10] Medsker, L. R., & Jain, L. C. (2001).

Recurrent neural networks. Design and Applications, 5, 64-67.

[11] Rahman, K. (2023).

MasterCard Stock Data – Latest and Updated: MasterCard Stock Data – Downloaded using a Python Script and Yahoo! Finance API. Kaggle. kaggle.com/datasets/kalilurrahman/mastercard-stock-data-latest-and-updated

[12] Rumelhart, D. E., Hinton, G. E., and Williams, R. J. (1986).

Learning internal representations by error propagation, in Parallel Distributed Processing: Explorations in the Microstructure of Cognition. Rumelhart, D. E. and McClelland, J. L., Eds., MIT Press, Cambridge, 45.

The post Unlock the Power of Python for Deep Learning with Recurrent Neural Networks first appeared on Python GUI.

]]>
https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-recurrent-neural-networks/feed/ 0 10347
How to Create a BMI App With Delphi Ecosystem And Python https://pythongui.org/how-to-create-a-bmi-app-with-delphi-ecosystem-and-python/ https://pythongui.org/how-to-create-a-bmi-app-with-delphi-ecosystem-and-python/#comments Wed, 24 May 2023 02:09:28 +0000 https://pythongui.org/?p=10455 Are you interested in building an application that can calculate Body Mass Index (BMI) using Python GUI? Look no further, as we will guide you through creating a BMI app with Python. BMI is essential...

The post How to Create a BMI App With Delphi Ecosystem And Python first appeared on Python GUI.

]]>
Are you interested in building an application that can calculate Body Mass Index (BMI) using Python GUI? Look no further, as we will guide you through creating a BMI app with Python. BMI is essential for monitoring and maintaining a healthy lifestyle, making it a great project for beginners and intermediate-level Python programmers. 

With the help of Python and the Delphi ecosystem, you can create an easy-to-use and interactive BMI app that anyone can use. In this post, we’ll provide a step-by-step guide to building a BMI app using Python GUI. So, let’s begin exploring the world of Python GUI programming!

Why is a BMI Calculator App Important?

How to Create a BMI App With Delphi Ecosystem And Python. Python GUI page

A BMI calculator app is useful because it allows people to monitor and track their body mass index, which is an important indicator of their overall health and well-being.  

Such an app can be useful for individuals who want to maintain a healthy weight or for healthcare professionals who need to monitor their patients’ health. It can also detect potential health issues, such as obesity, leading to serious health problems like heart disease, diabetes, and stroke.

With the help of a BMI calculator app, users can easily track their BMI and get feedback on their progress toward achieving a healthy weight. Additionally, these apps often provide helpful tips on maintaining a healthy diet and lifestyle, making them an excellent tool for promoting healthy habits and overall wellness.

What Information do you Need to Calculate the BMI?

To calculate BMI (Body Mass Index), you need two pieces of information:

  1. Weight: The weight of the person in kilograms (kg) or pounds (lbs).
  2. Height: The height of the person in meters (m) or feet (ft) and inches (in).

Using these two pieces of information, you can calculate the BMI using the following formula:

BMI = Weight (kg) / Height² (m²)

Alternatively, you can use the following formula if you weigh pounds and height in inches:

BMI = (Weight (lbs) / Height² (in²)) x 703

Once you have calculated the BMI, you can use it to determine the weight status of the person based on the following categories:

  • Underweight: BMI less than 18.5
  • Normal weight: BMI between 18.5 and 24.9
  • Overweight: BMI between 25 and 29.9
  • Obese: BMI of 30 or higher

BMI is a useful tool for determining weight status but ignores things like muscle mass and body composition. Therefore, checking in with a healthcare professional for a more thorough health assessment is best.

What Kinds of Tools can be Useful in Building This App?

How to Create a BMI App With Delphi Ecosystem And Python. Delphi VCL page

Delphi for Python is a powerful tool for developers who want to create cross-platform desktop applications using Python. With its comprehensive features, including powerful user interface (UI) design tools and cross-platform support, Delphi for Python can help developers create desktop applications that operate smoothly across multiple platforms. 

The Delphi FMX framework enables developers to build visually appealing and efficient GUIs that work seamlessly on Windows, macOS, iOS, and Android devices. The Delphi Community Edition is a free, open-source version of the Delphi IDE, and the PythonFMXBuilder is also available for developers who prefer to work with open-source tools. With Delphi for Python, developers can reduce the time and effort required to develop cross-platform desktop applications, ensure consistent and reliable operation across all platforms, and create robust and feature-rich applications.

How Can You Create A BMI Calculator for Android Using These Tools?

How to Create a BMI App With Delphi Ecosystem And Python. The IDE.

What Are the Software Requirements to Complete this Task?

Before we dive into creating a BMI app with Delphi Ecosystem and Python, there are a few things you will need to have installed on your machine:

  1. Delphi IDE: You can download the community edition from the Embarcadero website for free.
  2. Delphi4PythonExporter tool: You can install this plugin by searching for it in the Delphi CE environment.
  3. Python: You can download the latest version of Python from the official website.
  4. Python4Delphi and PythonFMXBuilder: This library allows you to call Python functions from Delphi code. You can download it from the Python4Delphi Github repository.
  5. PyScripter or any other IDE that supports Python.

If you haven’t installed any of these tools, we recommend checking out the article “Powerful Python GUI Project Setup” to help you get started. In addition, you should have a basic understanding of Python and Delphi programming concepts to follow along with this tutorial.

Once you have all the required tools, you can proceed with the tutorial to create your BMI app using Delphi Ecosystem and Python.

You can grab the code for this tutorial from our GitHub repository using the following link:

https://github.com/Embarcadero/PythonBlogExamples/tree/main/BMI_Calculator_App

Let’s get started with creating our BMI Calculator App!

How to Create a Form in Delphi CE?

Let us start by opening Delphi CE and creating our first blank project. We will do this by clicking Create a new Project… under the Develop tab.

How to Create a BMI App With Delphi Ecosystem And Python. Creating a  new project

Next, select Multi-Device Application:

How to Create a BMI App With Delphi Ecosystem And Python. Multi device application

Finally, select Blank Application and click Ok.

How to Create a BMI App With Delphi Ecosystem And Python. Choosing a new blank appllication.

For this tutorial, we have named our project as BMI_Calculator_App.

How to Create a BMI App With Delphi Ecosystem And Python. Editing the form.

Let’s start by giving our form a name. To do this, right-click on the form and select QuickEdit. Here, we will name our form MainForm with the caption BMI Calculator.

How to Create a BMI App With Delphi Ecosystem And Python. Project manager window.

If you need to become more familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.

How to Create a BMI App With Delphi Ecosystem And Python. Ebook image.

Next, we need to resize our form. To do this, head to the object inspector and search for ClientHeight and ClientWidth. Here, we will set them to 500 and 360, respectively.

How to Create a BMI App With Delphi Ecosystem And Python. The object inspector.

This form will serve as the main view of our application, where the user will be able to calculate their BMI. Therefore, let us add some components to this form to make it more functional. 

First, let’s add a few labels to make it look more like an app. To do this, head on over to the Palette and search for the TLabel Component. Then, drag and drop this component into the form.

How to Create a BMI App With Delphi Ecosystem And Python. Tool palette.

Next, right-click on the label and go to QuickEdit. Here we will give the name Title, and caption of BMI Calculator App.

How to Create a BMI App With Delphi Ecosystem And Python. Editing the app's title.

Now let’s modify the text style. Again, select the label and head to the Object Inspector. Next, search for TextSettings and click on the ... right next to the Font property to modify the label’s font, size, and style based on your preferences.

How to Create a BMI App With Delphi Ecosystem And Python. Choosing a font.

Now, center the text using the HorzAlign and VertAlign properties in TextSettings. So select the label component, and again, under the TextSettings select the HorzAlign and VertAlign properties and adjust the properties to Center.

How to Create a BMI App With Delphi Ecosystem And Python. Changing the alignment.

Here is what our form looks like:

How to Create a BMI App With Delphi Ecosystem And Python. App screen 1.

Similarly, let’s have a few more labels that will indicate the input fields for our app.

How to Create a BMI App With Delphi Ecosystem And Python. App screen 2.

Note that we have also added another label Status in the form that is not visible as it does not have any text. We will use this to display error messages to the user.

Now, we need to add a button that will help our user calculate their BMI and send them to the next form. For this, we will be using a TButton component. So go to the Palette and add a button using the TButton component.

How to Create a BMI App With Delphi Ecosystem And Python. TButton.
How to Create a BMI App With Delphi Ecosystem And Python. App screen 4.

Next, we will modify this button to make it more appealing. But before that, we need to change the text on the Button. So right-click the button and, using QuickEdit, rename it to ResultsButton with the caption Results.

How to Create a BMI App With Delphi Ecosystem And Python. Quick edit screen.

Next, select the button and head to TextSettings. Here we will change the font size to Segoe UI with a font size of 16 and change the size of the button.

How to Create a BMI App With Delphi Ecosystem And Python. App screen 5.

Our MainForm is almost complete. Now, we just need to add two more components allowing the user to input their measurements. Head to the Palette and search for the TEdit Label. Again, we will use QuickEdit to give these components intuitive names. Here we are adding 3 TEdit components WeightEdit, HeightFeetEdit, and HeightInchEdit, that, as the name implies, allow our users to input their weight and height, respectively.

How to Create a BMI App With Delphi Ecosystem And Python. App screen  6.

Finally, we must allow users to add their weight in either imperial or metric units. To do this, we will use a radio button. So again, head to the Palette and search for the TRadioButton component.

How to Create a BMI App With Delphi Ecosystem And Python. The palette, searching for TRadioButton.

We will add two radio buttons to our form, giving them a name of PoundsRadio, and KgRadio. We will also modify their appearance using TextSettings.

How to Create a BMI App With Delphi Ecosystem And Python. App screen 8.

Finally, let’s adjust the form’s background color by navigating to the Object Inspector and selecting the form’s fill property.

How to Create a BMI App With Delphi Ecosystem And Python. Using the brush designer.

This completes our MainForm. Now let’s create a new form that will display our app. So right-click on BMI_Calculator_App.exe and select Add New > Multi-Device Form.

How to Create a BMI App With Delphi Ecosystem And Python. The add new screen.

This will create a new form that will serve the result screen. Here we have named the form ResultsForm and its corresponding source file Results.pas. We also changed its dimension to match our MainForm.

Next, similarly to our MainForm let’s add color to our ResultsForm and add a few labels and buttons. This form will only be used to display the results to our users. Here is what our form looks like:

How to Create a BMI App With Delphi Ecosystem And Python. App screen 9.

Finally, we add a DetailsLabel to display a custom message to our users based on their BMI.

How to Create a BMI App With Delphi Ecosystem And Python. App screen

Now that our forms are completed, we must ensure that the buttons remain functional when we export our application as a Python project. To do this, go to each form and double-click each button to add an OnClick method to that button. The procedure will be created in the .pas file corresponding to the .fmx form.

How to Create a BMI App With Delphi Ecosystem And Python. The empty code blocks.

Next, add at least one comment (//) to each procedure. This will ensure the procedure is preserved when you export it as a Python file.

How to Create a BMI App With Delphi Ecosystem And Python. Adding some comments as place holders.

Can this Form be Easily Exported Into Python Code?

To export our project as Python scripts, we only need to select Tools > Export To Python > Export Current Entire Project.

How to Create a BMI App With Delphi Ecosystem And Python. Export the project.

Next, we name our project BMI Calculator, and select the main form as MainForm. Finally, select the directory of your choosing and click Export:

How to Create a BMI App With Delphi Ecosystem And Python. Project exporter screen.

This will generate 3 Python scripts and 2 .pyfmx scripts in our specified directory. The BMI_Calculator_App.py is used to launch our Delphi app, while Results.py, and Main.py Python files contain the classes for the individual forms. Along with the Python file for each form, Delphi also generates a .pyfmx script of the same name as each form that contains the visual information of that form. Here are the contents of each file.

BMI_Calculator_App.py:

from delphifmx import *
from Main import MainForm

def main():
    Application.Initialize()
    Application.Title = 'BMI Calculator'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Main.py:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.WeightEdit = None
        self.HeightFeetEdit = None
        self.ResultsButton = None
        self.HeightLabel = None
        self.WeightLabel = None
        self.Title = None
        self.PoundsRadio = None
        self.KgRadio = None
        self.FeetLabel = None
        self.HeightInchEdit = None
        self.InchLabel = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def ResultsButtonClick(self, Sender):
        pass

Results.py:

import os
from delphifmx import *

class ResultsForm(Form):

    def __init__(self, owner):
        self.BMIScore = None
        self.Label1 = None
        self.DetailsLabel = None
        self.CategoryLabel = None
        self.Title = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Results.pyfmx"))

How to Add Functionality to this Application?

Now that our Python scripts are ready let’s start adding functionality to our code. Start by opening our MainForm in Main.py and navigating to the __init__ function.

In our __init__ function, we will only initialize a new variable self.BMI that will store the BMI of our individual. This will then be passed to the ResultsForm, where it will be displayed. Here is what our __init__ function looks like:

def __init__(self, owner):
        self.WeightEdit = None
        self.HeightFeetEdit = None
        self.ResultsButton = None
        self.HeightLabel = None
        self.WeightLabel = None
        self.Title = None
        self.PoundsRadio = None
        self.KgRadio = None
        self.FeetLabel = None
        self.HeightInchEdit = None
        self.InchLabel = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        self.BMI = 0 # Initialize BMI that would be calculated and sent to next form

Next, let’s create a GetBMI function that uses the height and weight of our individual to calculate the BMI of our user:

def GetBMI(self, weight, heightft, heightin):
        # For BMI Calculation, Weight should be in kg and Height in meters
        if self.PoundsRadio.IsChecked:
            weight = weight / 2.205
        height = heightft * 0.3048 + heightin * 0.0254 # Conversion to meters
        return round(weight / (height**2), 2) # BMI = Weight/ (Height)^2

The BMI function checks whether the radio button for lbs is checked. If it is, it adds a conversion layer to convert the weight in pounds back into kilograms. It then uses the weight and height to generate a BMI based on our formula earlier and rounds it to 2 decimal places.

Now, let’s add functionality to our Results button. Head to the ResultsButtonClick function and start by checking whether the user has input in any fields. If the user does not have input in any fields, we use the Status label to display an error.

def ResultsButtonClick(self, Sender):
        # Error Handling
        if (self.PoundsRadio==False and self.KgRadio==False) or self.HeightFeetEdit.Text=="" or self.HeightInchEdit.Text=="" or self.WeightEdit.Text=="":
            self.Status.Text = "Please fill in all fields"

Next, we check whether the height input in inches is between 0 and 11:

elif int(self.HeightInchEdit.Text) < 0 or int(self.HeightInchEdit.Text) > 11:
            self.Status.Text = "Give inches between 0 and 11"

Finally, if there are no errors, we call the GetBMI function and send the BMI to our results form. First, we import the ResultsForm from the Results.py file:

from Results import ResultsForm

We call the GetBMI function and store its result in a separate variable. Then, we create an instance of the ResultsForm and use the .Show() method to show the form. Here is what our final ResultsButtonClick function looks like:

def ResultsButtonClick(self, Sender):
        # Error Handling
        if (self.PoundsRadio==False and self.KgRadio==False) or self.HeightFeetEdit.Text=="" or self.HeightInchEdit.Text=="" or self.WeightEdit.Text=="":
            self.Status.Text = "Please fill in all fields"
        elif int(self.HeightInchEdit.Text) < 0 or int(self.HeightInchEdit.Text) > 11:
            self.Status.Text = "Give inches between 0 and 11"
        # If no errors
        else:
            self.BMI = self.GetBMI(float(self.WeightEdit.Text), int(self.HeightFeetEdit.Text), int(self.HeightInchEdit.Text))
            self.results = ResultsForm(self, BMI=self.BMI)
            self.results.Show()

Here is what our final Main.py looks like:

import os
from delphifmx import *
from Results import ResultsForm
class MainForm(Form):

    def __init__(self, owner):
        self.WeightEdit = None
        self.HeightFeetEdit = None
        self.ResultsButton = None
        self.HeightLabel = None
        self.WeightLabel = None
        self.Title = None
        self.PoundsRadio = None
        self.KgRadio = None
        self.FeetLabel = None
        self.HeightInchEdit = None
        self.InchLabel = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

        self.BMI = 0 # Initialize BMI that would be calculated and sent to next form

    def ResultsButtonClick(self, Sender):
        # Error Handling
        if (self.PoundsRadio==False and self.KgRadio==False) or self.HeightFeetEdit.Text=="" or self.HeightInchEdit.Text=="" or self.WeightEdit.Text=="":
            self.Status.Text = "Please fill in all fields"
        elif int(self.HeightInchEdit.Text) < 0 or int(self.HeightInchEdit.Text) > 11:
            self.Status.Text = "Give inches between 0 and 11"
        # If no errors
        else:
            self.BMI = self.GetBMI(float(self.WeightEdit.Text), int(self.HeightFeetEdit.Text), int(self.HeightInchEdit.Text))
            self.results = ResultsForm(self, BMI=self.BMI)
            self.results.Show()

    def GetBMI(self, weight, heightft, heightin):
        # For BMI Calculation, Weight should be in kg and Height in meters
        if self.PoundsRadio.IsChecked:
            weight = weight / 2.205
        height = heightft * 0.3048 + heightin * 0.0254 # Conversion to meters
        return round(weight / (height**2), 2) # BMI = Weight/ (Height)^2

Next, let’s move onto the ResultsForm. Open up Results.py and head to the __init__ function. As you may see, when we initialized the ResultsForm in the MainForm we passed in a BMI value that cannot be passed onto the original form. To ensure that the ResultsForm uses the value we passed, we will modify the __init__ function to take in this value:

def __init__(self, owner, BMI):

Next, we store this BMI in a new variable self.BMI and display this to our BMIScore label using the .Text property.

self.BMIScore.Text = str(BMI)
        self.BMI = BMI

Now, we define a dictionary with our custom messages that will be displayed based on the user’s weight category:

self.Detail = {
            "Underweight": "Your BMI indicates that you are underweight, which may increase your risk of health problems. You should consult a doctor or a dietitian to develop a healthy eating plan that can help you gain weight in a safe and sustainable way.",
            "Healthy": "Your BMI indicates that you are in a healthy weight range, which is great for your overall health and well-being. Keep up the good work by staying physically active and eating a balanced diet.",
            "Overweight": "Your BMI indicates that you are overweight, which may increase your risk of health problems such as heart disease and diabetes. You should consider making lifestyle changes such as increasing your physical activity and reducing your calorie intake.",
            "Obese":"Your BMI indicates that you are obese, which significantly increases your risk of health problems such as heart disease, stroke, and cancer. You should consult a dietitian to develop a weight loss plan that can help you achieve a healthy weight and reduce your risk of these health problems.",
            }

Finally, we check the user’s weight category based on their BMI and display a custom message to our DetailsLabel. Our final Results.py file looks like:

import os
from delphifmx import *

class ResultsForm(Form):

    def __init__(self, owner, BMI):
        self.BMIScore = None
        self.Label1 = None
        self.DetailsLabel = None
        self.CategoryLabel = None
        self.Title = None
        self.Reset = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Results.pyfmx"))
       
        # More initializations
        self.BMIScore.Text = str(BMI)
        self.BMI = BMI
        self.Detail = {
            "Underweight": "Your BMI indicates that you are underweight, which may increase your risk of health problems. You should consult a doctor or a dietitian to develop a healthy eating plan that can help you gain weight in a safe and sustainable way.",
            "Healthy": "Your BMI indicates that you are in a healthy weight range, which is great for your overall health and well-being. Keep up the good work by staying physically active and eating a balanced diet.",
            "Overweight": "Your BMI indicates that you are overweight, which may increase your risk of health problems such as heart disease and diabetes. You should consider making lifestyle changes such as increasing your physical activity and reducing your calorie intake.",
            "Obese":"Your BMI indicates that you are obese, which significantly increases your risk of health problems such as heart disease, stroke, and cancer. You should consult a dietitian to develop a weight loss plan that can help you achieve a healthy weight and reduce your risk of these health problems.",
            }

        # Categorization according to BMI
        if BMI < 18.5:
            self.CategoryLabel.Text = "Underweight"
        elif 18.5 < BMI < 24.9:
            self.CategoryLabel.Text = "Healthy"
        elif 25.0 < BMI < 29.9:
            self.CategoryLabel.Text = "Overweight"
        elif BMI > 30:
            self.CategoryLabel.Text = "Obese"

        self.DetailsLabel.Text = self.Detail[self.CategoryLabel.Text] # Display details and suggestions according to the category

Can this Code be Used to Create a Mobile Application?

Now that our app is ready, we can use FMXBuilder to convert this into an Android app.

But before we can create our app, we need to make important adjustments to our code to make it run on Android. Start by creating a new file named BMI_Calculator_App_Android.py and paste the content of BMI_Calculator_App.py. Now, open up this new file and start making the changes.
First, we need to remove the initialization. This is done because Delphi initializes Android applications automatically, so it is unnecessary to do it manually. In addition, we don’t need to launch or destroy our app form manually, as Delphi also does this. Here is what our BMI_Calculator_App_Android.py looks like:

from delphifmx import *
from Main import MainForm

def main():
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()

if __name__ == '__main__':
    main()

Now we can build our Android app. Start by opening up the FMXBuilder and create a new project by clicking on Project > New project on the toolbar. Next, enter the name of this new project:

How to Create a BMI App With Delphi Ecosystem And Python. Create a new project.

Add your Python and .pyfmx files by right-clicking on the App and selecting Add file. We won’t add BMI_Calculator_App.py but instead will be adding the BMI_Calculator_App_Android.py.

How to Create a BMI App With Delphi Ecosystem And Python. Add a file.

Now, right-click on the BMI_Calculator_App_Android.py file and set it to the main file.

How to Create a BMI App With Delphi Ecosystem And Python. Set the main screen.

Now that everything is ready, we must create the .apk file for the app using the Build Project button.

How to Create a BMI App With Delphi Ecosystem And Python. Build the project.

When the .apk is fully generated, you will be prompted with a “Build process done” message in the Messages box. You can then check out your generated file in the pathtoPythonFMXBuilderGUIexeFolderappsBMIbin folder.

How to Create a BMI App With Delphi Ecosystem And Python. The APK file.

Now, you must copy the .apk file into your phone’s storage. Next, install this file by accessing it on your Android device. Once your app is installed, you can use it like any other app on your phone.

Does the App Fulfill all Requirements?

Here is what our final app looks like:

How to Create a BMI App With Delphi Ecosystem And Python. App screen 12.

If you press Results without selecting any field, you get an error message:

How to Create a BMI App With Delphi Ecosystem And Python. App screen 13.

Similarly, if you leave any field empty, you also get an error message:

How to Create a BMI App With Delphi Ecosystem And Python. App screen 14.

Once you’ve filled in all the fields and press Results, you will be navigated to the ResultsForm.

How to Create a BMI App With Delphi Ecosystem And Python. App screen 15.

Here you will be presented with your BMI along with a custom message:

How to Create a BMI App With Delphi Ecosystem And Python. App screen 16.

You will also be given messages for being healthy, underweight, and overweight:

How to Create a BMI App With Delphi Ecosystem And Python. App screen 17.
How to Create a BMI App With Delphi Ecosystem And Python. App screen 18.
How to Create a BMI App With Delphi Ecosystem And Python. App screen 19.

Are You Ready to Create More Such Apps?

How to Create a BMI App With Delphi Ecosystem And Python. Are you ready?

Creating a BMI calculator app using Python and the Delphi ecosystem offers an excellent opportunity for Python developers to enhance their programming skills and produce useful tools that can benefit others. Furthermore, with the help of Delphi’s FireMonkey GUI framework, developers can easily create a user-friendly and aesthetically pleasing app that can be accessed on multiple platforms, including Android and iOS.

The Delphi ecosystem offers a wide range of development tools and libraries, making it an excellent choice for those who want to quickly build powerful and efficient apps. In addition, the cross-platform compatibility of DelphiFMX means that the app you create can be used by a wider audience, regardless of their device or operating system.

By utilizing the features and tools of the Delphi ecosystem, developers can significantly accelerate the app creation process, leading to quicker development and deployment times. 

So, don’t wait any longer – start building your next app with the Delphi ecosystem today!

What Are Some FAQs Regarding This Topic?

How to Create a BMI App With Delphi Ecosystem And Python. FAQ Screen.

What is the Delphi ecosystem?

The Delphi ecosystem is a collection of development tools, libraries, and frameworks used for building applications across multiple platforms, including Windows, Android, and iOS.

What is the FireMonkey GUI framework, and why is it useful for app development?

The FireMonkey GUI framework is a cross-platform UI toolkit for developing graphical user interfaces (GUIs) for applications. It’s useful for app development because it provides a rich set of UI controls, allows easy UI elements customization, and supports multiple platforms.

Can I use the BMI calculator app on my smartphone?

Yes, you can use the BMI calculator app on your smartphone. The app can be developed to support both Android and iOS platforms, making it accessible to a wider audience.

Can the BMI calculator app calculate BMI for children?

Yes, the BMI calculator app can calculate BMI for children and adults. However, the BMI calculation formula for children is different. Moreover, if you feel that your child may have certain health problems, it’s important to consult with a healthcare professional for a more accurate assessment of a child’s health.

The post How to Create a BMI App With Delphi Ecosystem And Python first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-bmi-app-with-delphi-ecosystem-and-python/feed/ 1 10455
How to Create a Stopwatch/Timer Android App With Delphi For Python? https://pythongui.org/how-to-create-a-stopwatch-timer-android-app-with-delphi-for-python/ https://pythongui.org/how-to-create-a-stopwatch-timer-android-app-with-delphi-for-python/#respond Tue, 16 May 2023 13:07:36 +0000 https://pythongui.org/?p=9990 Delphi is a popular development environment for building Windows and mobile applications. It has a rich set of libraries and tools that make it easy to create cross-platform apps. Delphi for Python is an extension...

The post How to Create a Stopwatch/Timer Android App With Delphi For Python? first appeared on Python GUI.

]]>
Delphi is a popular development environment for building Windows and mobile applications. It has a rich set of libraries and tools that make it easy to create cross-platform apps. Delphi for Python is an extension of Delphi that allows you to use supercharge Python to build attractive applications. This tutorial will show you how to create a stopwatch/timer Android app using Delphi for Python.

Why Use Delphi For Python?

How to Create a Stopwatch/Timer Android App With Delphi For Python? A person looking at the RAD Studio IDE

Delphi for Python is a set of powerful tools that can benefit Python developers who want to create Graphical User Interfaces (GUIs) quickly and easily. These tools provide cross-platform support, allowing GUIs to work on various devices without writing separate code for each platform. For instance, Delphi for Python offers access to the FireMonkey GUI framework, a powerful and flexible tool for creating GUIs, providing sophisticated and visually appealing user interfaces. 

Additionally, Python developers can use Delphi’s UI design tools to design their GUIs by utilizing the Delphi4PythonExporter tool, which can speed up the development process and ensure the resulting GUIs are functional and visually appealing. Finally, Delphi Community Edition and PythonFMXBuilder are open-source tools ideal for developers who prefer open-source tools whenever possible. Delphi for Python is a great solution for Python developers to streamline the development process and ensure that their applications work well on all platforms.

How to Create a Stopwatch/Timer App For Desktop?

How to Create a Stopwatch/Timer Android App With Delphi For Python? A screen showing a Python app in an IDE

Let’s create a basic timer and stopwatch application for desktop devices! A good approach would be to use the Delphi tools mentioned above. So let’s get started!

What Are the Requirements to Create this App?

To proceed with this tutorial, you will need the latest version of Python, PythonFMXBuilder, Delphi4PythonExporter, Delphi, and any text editor or IDE (PyScripter is recommended) that supports Python.

We’ve got you covered if you don’t have these installed on your device. We recommend checking out this article, “Powerful Python GUI Project Setup”, to help you get started.

You can grab the code for this tutorial from our GitHub repository using the following link: https://github.com/Embarcadero/PythonBlogExamples/tree/main/Time_Widget_App

How to Create its Forms in Delphi CE?

Open Delphi CE and create a blank application by navigating to File > New > Multi-Device Application > Blank Application > Ok. Here we have named our project StopwatchTimerApp.

How to Create a Stopwatch/Timer Android App With Delphi For Python? The RAD Studio IDE

To understand what each section of the above Delphi IDE means/represents, please go through the free eBook bundle, we have developed. This eBook explains the ideology around Delphi Python EcoSystem, all Python GUI offerings, and much more.

How to Create a Stopwatch/Timer Android App With Delphi For Python? The Python E-book explained

Let’s start by giving our form a name. Right-click on the form and click on QuickEdit. Here we will name our form MainForm with the caption MainMenu.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Creating the main form

Next, let’s resize our form. Head to the object inspector, and in the properties tab, search for ClientHeight and ClientWidth. We will set them as 500 and 360, respectively.

How to Create a Stopwatch/Timer Android App With Delphi For Python? The object inspector.

We will also rename the source file of our main form to MainMenu.pas to make it easy to keep track of.

How to Create a Stopwatch/Timer Android App With Delphi For Python? the project manager view

As you may have guessed, this is the main form of our app. It will serve as the main screen where users can select the option of a timer or stopwatch. To make it more user-friendly, let us add a label that will greet us with the title of our app. Head over to the standard palette and search for the TLabel component. Next, drag and drop the component into the form.

How to Create a Stopwatch/Timer Android App With Delphi For Python? The tool palette

Now, let’s change the text style to display the title. We will do this using TextSettings. Head over to the Object Inspector and search for TextSettings. Select Font under it and click on the ... to see options allowing you to change the label font, size, and style according to your needs.

How to Create a Stopwatch/Timer Android App With Delphi For Python? The object inspector

Now rename the text of each label by right-clicking on that label and selecting Quick Edit. It is important to follow an intuitive naming convention to name the labels so that it is easier to track them. Here, we named our TLabel component Title with the text “Time Widget App.”

How to Create a Stopwatch/Timer Android App With Delphi For Python? The first form designed with a label

We can change the form’s background color by navigating to the Object Inspector and selecting the form’s fill property.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Using the object inspector to change the brush's fill
How to Create a Stopwatch/Timer Android App With Delphi For Python? Selecting a fill color

Finally, we need a way to navigate to the next form, either a timer or a stopwatch. So, go to the Palette and add two buttons using the TButton component.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Finding a button in the palette
How to Create a Stopwatch/Timer Android App With Delphi For Python? Soem more design on the screen.

These buttons will help us navigate to our Stopwatch or Timer screen. So let’s name these buttons appropriately. Moreover, we have changed these button text’s font size and style (as we did for the TLabels above) to make them more prominent. Here we have to use the font style as Segoe UI. We have also aligned the text to the Center, the same as the Title label above, so the text appears symmetric.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Changing the alignment is easy.

After these changes, our form will look much more visually attractive:

How to Create a Stopwatch/Timer Android App With Delphi For Python? Showing the screen after the alignment changes

Double-click on each button to create an OnClick method in your .pas file corresponding to your .fmx for each button. This will allow you to add different functionality when a button is clicked.

How to Create a Stopwatch/Timer Android App With Delphi For Python? The code behind the screen.

Add at least one comment (//) after each button OnClick method to ensure that each procedure is preserved when we save the Python file. Since we don’t export the run-time implementation using the Delphi4PythonExporter, there is no need to write any run-time implementation code.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Empty button click procedures

Now that we are done with the MainForm of our app let’s create a new form that will display our timer. So right-click on TimerStopwatchApp.exe and select Add New > Multi-Device Form.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Creating a new multi device form

This will create a new form named TimerForm and the source file as Timer.pas.

Like our MainForm let’s add some buttons and labels to our TimerForm to make it more visually appealing.

How to Create a Stopwatch/Timer Android App With Delphi For Python? More design.

As you can see, we have added two extra labels, the Time label, and the Status label. The Time label will help countdown the time, whereas the Status label will help display different messages to the user.

In addition, we added a TEdit box that will help the user specify the time to set in the Timer app. We also added a Back button that will help us navigate back to the MainForm, and a combo box that will help us load predefined times that the user may have for certain tasks.

Next, we must add a system component called TTimer to the form. So head to the command palette, search for the TTimer component, and add it to your form. This component will enable us to either count up or count down from a selected time by simply enabling or disabling the module.

Here is what our TimerForm looks like:

How to Create a Stopwatch/Timer Android App With Delphi For Python? Selecting the edit box.

Lastly, we need to add procedures to our combo box and edit box, that will change the values of the timer when they are changed. To add these procedures, select the object and head to the Events tab in the Object Inspector. Here search for the OnChange event, and add the name of your relevant function. Delphi automatically creates a function you can manipulate to your choosing. Here we are adding a procedure called SetOtherTime for the TEdit Box:

How to Create a Stopwatch/Timer Android App With Delphi For Python? Creating the OnChange event

Like our MainForm, double-click on each button on the form to create an OnClick method for each button. Finally, add at least a single comment for each procedure to ensure that the method is preserved when we finally export the Python code.

Now that we have our TimerForm ready, we can create our StopwatchForm. So following the same process as before, we can create a new form and add relevant Labels and buttons to make it more appealing. Moreover, like before, we add a TTimer module that will help us run our stopwatch. Here is what our final form looks like:

How to Create a Stopwatch/Timer Android App With Delphi For Python? The final form's appearance

Now that our forms are ready, we can also see how our app appears on desktop and Android phones. Switch the Style from Windows to Android to verify this. This will alter how our form appears.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Changing to Android

How to Export this App as Python Code?

Now that our forms are ready, we can save our project as a Python script by selecting Tools > Export To Python > Export Current Entire Project.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Exporting the project to Python.

This will open up the Python Exporter. Here rename your project to StopwatchTimerApp, and select the main form as MainForm. Finally, select the directory of your choosing and click Export:

How to Create a Stopwatch/Timer Android App With Delphi For Python? Setting the exported project's properties

Delphi will generate a total of 7 files, 4 Python scripts named MainMenu.py, Stopwatch.py, Timer.py, and StopwatchTimerApp.py. The MainMenu, Stopwatch, and Timer python files contain the classes for the individual forms, and the StopwatchTimerApp is used to launch our Delphi app. 

Along with each Python file, Delphi also generates a .pyfmx script containing each form’s visual information.

Let’s take a look at the exported StopwatchTimerApp.py file.

from delphifmx import *
from MainMenu import MainForm

def main():
    Application.Initialize()
    Application.Title = 'StopwatchTimerApp'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Next, let’s take a look at the contents of MainMenu.py that contains information about our MainForm:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.StopwatchFormButton = None
        self.TimerFormButton = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainMenu.pyfmx"))

    def StopwatchFormButtonClick(self, Sender):
        pass

    def TimerFormButtonClick(self, Sender):
        pass

Here are the contents of Timer.py where we will be adding code to run our timer:

import os
from delphifmx import *

class TimerForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Time = None
        self.Start = None
        self.Pause = None
        self.Reset = None
        self.ComboBox1 = None
        self.Back = None
        self.TimeDuration = None
        self.Status = None
        self.Timer1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Timer.pyfmx"))

    def StartClick(self, Sender):
        pass

    def PauseClick(self, Sender):
        pass

    def ResetClick(self, Sender):
        pass

    def ComboSelected(self, Sender):
        pass

    def BackClick(self, Sender):
        pass

    def SetOtherTime(self, Sender):
        pass

    def Timer1Timer(self, Sender):
        pass

Finally, let’s take a look at Stopwatch.py, which we will use to run our stopwatch:

import os
from delphifmx import *

class StopwatchForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Time = None
        self.Play = None
        self.Pause = None
        self.Reset = None
        self.Back = None
        self.Timer1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Stopwatch.pyfmx"))

    def PlayClick(self, Sender):
        pass

    def PauseClick(self, Sender):
        pass

    def ResetClick(self, Sender):
        pass

    def BackClick(self, Sender):
        pass

    def Timer1Timer(self, Sender):
        pass

Can I Add Functionality to This App Using Delphi FMX?

Now that our forms are ready, let’s start adding functionality to our forms.

What Should I do in My MainForm?

Let’s start with the MainForm. Go to your Project folder and open up MainMenu.py.

For our MainForm the only thing we need to do is open up the StopwatchForm or the TimerForm using the relevant buttons. To do this, first import the StopwatchForm and TimerForm from the Python files:

from Stopwatch import StopwatchForm
from Timer import TimerForm

Next, navigate to the StopwatchFormButtonClick function and create a new instance of the StopwatchForm with a variable named self.StopwatchWindow. Next, display the new form using the show() method. We can repeat the same approach for the TimerFormButtonClick. Here what our final MainMenu.py looks like this:

import os
from delphifmx import *

# Extra Imports
from Stopwatch import StopwatchForm
from Timer import TimerForm

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.StopwatchFormButton = None
        self.TimerFormButton = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainMenu.pyfmx"))

    def StopwatchFormButtonClick(self, Sender):
        self.StopwatchWindow = StopwatchForm(self)
        self.StopwatchWindow.Show()

    def TimerFormButtonClick(self, Sender):
        self.TimerWindow = TimerForm(self)
        self.TimerWindow.Show()

How Can I Add Functionality to My StopwatchForm?

Now, let’s take a look at StopwatchForm.

Recall, that the Time label we created in the form was to display the time. So in the __init__ function, we need to initialize the Time label using the .Text property as follows:

# Initially setting time label to zero
        self.Time.Text = '00:00:00'

Now, let’s take a look start button. The start button should start the stopwatch. We can do this by navigating to the StartClick function and setting the Timer1 object as enabled. We also define the Timer1.Interval as 10 milliseconds. Our StartClick function looks like:

def StartClick(self, Sender):
        self.Timer1.Enabled = True
        self.Timer1.Interval = 10

Similarly our pause button should pause our timer. So navigate to the PauseClick function and simply set Timer1.Enabled as False:

def PauseClick(self, Sender):
        self.Timer1.Enabled = False

Finally, our reset button disables the timer and resets the Time label. We also update the timer tag to 0, which will help us keep track of the timer. Here is what our ResetClick function looks like:

def ResetClick(self, Sender):
        self.Time.Text = '00:00:00'  # Update the label
        self.Timer1.Tag = 0  # Update the timer tag
        self.Timer1.Enabled = False

Now, we need to define our Back button. Luckily, with Delphi, we must destroy the current form and simply show the Application.MainForm, which is defined as our MainForm. Our BackClick function looks like:

def BackClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

Finally, we must update our Timer at every interval. To do this, we will define our Timer1Timer function. Start by initializing a variable and adding the Timer1.Tag and the Timer1.Interval to the variable:

# Keep adding the time interval
        ElapsedTime = self.Timer1.Tag + self.Timer1.Interval

Next, we need to calculate the minutes, seconds, and milliseconds in the ElapsedTime variable. We do this using the following code:

# Calculate the number of minutes, seconds and milliseconds
        Minutes = ElapsedTime // (60 * 1000)
        Seconds = (ElapsedTime // 1000) % 60
        Milliseconds = ElapsedTime % 1000

Finally, we can display the time elapsed so far using the .Text property of our Time label. We also update the Timer1.Tag to the elapsed time so far. Here is what our Timer1Timer function looks like:

def Timer1Timer(self, Sender):
        # Keep adding the time interval
        ElapsedTime = self.Timer1.Tag + self.Timer1.Interval

        # Calculate the number of minutes, seconds and milliseconds
        Minutes = ElapsedTime // (60 * 1000)
        Seconds = (ElapsedTime // 1000) % 60
        Milliseconds = ElapsedTime % 1000

        # Update time label
        self.Time.Text = f"{Minutes:02d}:{Seconds:02d}.{Milliseconds:02d}"

        # Store the elapsed time in the timer tag
        self.Timer1.Tag = ElapsedTime

So our final Stopwatch.py file has the following code:

import os
from delphifmx import *

class StopwatchForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Time = None
        self.Start = None
        self.Pause = None
        self.Reset = None
        self.Back = None
        self.Timer1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Stopwatch.pyfmx"))

        # Initially setting time label to zero
        self.Time.Text = '00:00:00'

    def StartClick(self, Sender):
        self.Timer1.Enabled = True
        self.Timer1.Interval = 10

    def PauseClick(self, Sender):
        self.Timer1.Enabled = False

    def ResetClick(self, Sender):
        self.Time.Text = '00:00:00'  # Update the label
        self.Timer1.Tag = 0  # Update the timer tag
        self.Timer1.Enabled = False

    def BackClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

    def Timer1Timer(self, Sender):
        # Keep adding the time interval
        ElapsedTime = self.Timer1.Tag + self.Timer1.Interval

        # Calculate the number of minutes, seconds and milliseconds
        Minutes = ElapsedTime // (60 * 1000)
        Seconds = (ElapsedTime // 1000) % 60
        Milliseconds = ElapsedTime % 1000

        # Update time label
        self.Time.Text = f"{Minutes:02d}:{Seconds:02d}.{Milliseconds:02d}"

        # Store the elapsed time in the timer tag
        self.Timer1.Tag = ElapsedTime

What Should I Add to My Timer Form to Make it Function?

Now that our StopwatchForm is ready, let’s define our final form, i.e., TimerForm. Start by opening Time.py in your project directory and navigating to the __init__ function.

Similar to the StopwatchForm, let’s start by initializing our Time label as “00:00:00” and making our Status label empty:

# Initially setting time label to zero and status to blank
        self.Time.Text = '00:00:00'
        self.Status.Text = ''

Next, let’s add a few predefined items into our combo box. These items will define a preset timer for each task:

# Add items to the combo box
        self.ComboBox1.Items.Add('Brush Teeth')
        self.ComboBox1.Items.Add('Boil Eggs')
        self.ComboBox1.Items.Add('Other')

Now, disable all the buttons and edit boxes in our form. These will remain disabled until the user selects some element task from the combo box:

# You cannot type in the TEdit until Other from comboboc is selected
        self.TimeDuration.Enabled = False
        self.Start.Enabled = False
        self.Pause.Enabled = False
        self.Reset.Enabled = False

Finally, define a self.CountdownTime variable to store the time value for our timer. Here is what our final __init__ function looks like:

def __init__(self, owner):
        self.Title = None
        self.Time = None
        self.Start = None
        self.Pause = None
        self.Reset = None
        self.ComboBox1 = None
        self.Back = None
        self.TimeDuration = None
        self.Status = None
        self.Timer1 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Timer.pyfmx"))

        # Initially setting time label to zero and status to blank
        self.Time.Text = '00:00:00'
        self.Status.Text = ''

        # Add items to the combo box
        self.ComboBox1.Items.Add('Brush Teeth')
        self.ComboBox1.Items.Add('Boil Eggs')
        self.ComboBox1.Items.Add('Other')

        # You cannot type in the TEdit until Other from combo box is selected
        self.TimeDuration.Enabled = False
        self.Start.Enabled = False
        self.Pause.Enabled = False
        self.Reset.Enabled = False

        # Var to store start time value
        self.CountdownTime = 0

Next, we define our StartClick, PauseClick, ResetClick, and BackClick functions similar to what we did for the StopwatchForm:

def StartClick(self, Sender):
        self.Timer1.Enabled = True
        self.Timer1.Interval = 10
        self.Status.Text = ''

    def PauseClick(self, Sender):
        self.Timer1.Enabled = False

    def ResetClick(self, Sender):
        self.Time.Text = '00:00:00'  # Update the label
        self.Timer1.Tag = self.CountdownTime  # Update the timer tag
        self.Timer1.Enabled = False

    def BackClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

Now, we define our ComboSelected function. Our combo box allows the user to select one of three options, “Brush Teeth“, “Boil Eggs“, or “Other“. If the user selects “Brush Teeth“, a timer of 2 minutes is automatically set. Similarly, if the user selects “Boil Eggs“, a timer of 5 minutes is set. But if the user selects “Other“, we enable the TimeDuration edit box and allow the user to write down the time of his choosing. Here is what our final function looks like:

def ComboSelected(self, sender):
        if self.ComboBox1.ItemIndex == 0:
            self.TimeDuration.Text = '2:00:00'
        elif self.ComboBox1.ItemIndex == 1:
            self.TimeDuration.Text = '5:10:00'
        elif self.ComboBox1.ItemIndex == 2:
            self.TimeDuration.Text = ''
            self.TimeDuration.Enabled = True

Next, we define our TimeDuration edit box. If a user wants to define his time, we need to create a function that updates the time for our Timer. Luckily, we defined a function called SetOtherTime when we created our form that precisely does this. 

First, we need to check whether the time input has exactly two colons that give the time in a minute:second:millisecond format:

# Check for format of time given
        if self.TimeDuration.Text.count(':') == 2:

Next, we extract the total minutes, seconds, and milliseconds from the given time and convert them into milliseconds. We then store it in our Timer1.Tag variable and set all the buttons as enabled. If the user does not enter the correct time in the correct format, we display an error using the Status label. Here is what our final SetOtherTime function looks like:

def SetOtherTime(self, sender):
        # Check for format of time given
        if self.TimeDuration.Text.count(':') == 2:
            Time = self.TimeDuration.Text.split(':')
            Minutes, Seconds, Milliseconds = int(
                Time[0]), int(Time[1]), int(Time[2])
            TotalMilliseconds = (Minutes * 60 * 1000) + 
                (Seconds * 1000) + Milliseconds

            self.CountdownTime = int(TotalMilliseconds)
            self.Timer1.Tag = self.CountdownTime

            self.Start.Enabled = True
            self.Pause.Enabled = True
            self.Reset.Enabled = True

        else:
            self.Status.Text = 'Give the time duration in minutes:seconds:milliseconds'

Finally, we can define the Timer1Timer function exactly how we defined it for our StopwatchForm, with minor changes. Firstly, we need a way to stop our timer because we return in time. To do this, we use an if block that checks whether the ElapsedTime is still greater than 0. If it goes below 0, we display a “Timer Ended!” message in our Status label. We also update Time.Text and disable the Timer1 object. Our Timer1Timer function is as follows:

def Timer1Timer(self, Sender):
        ElapsedTime = self.Timer1.Tag - self.Timer1.Interval

        if ElapsedTime <= 0:
            self.Status.Text = 'Timer Ended!'
            self.Time.Text = '00:00:00'  # Update the label
            self.Timer1.Tag = self.CountdownTime  # Update the timer tag
            self.Timer1.Enabled = False

        # Calculate the number of minutes, seconds and milliseconds
        Minutes = ElapsedTime // (60 * 1000)
        Seconds = (ElapsedTime // 1000) % 60
        Milliseconds = ElapsedTime % 1000

        self.Time.Text = f"{Minutes:02d}:{Seconds:02d}.{Milliseconds:02d}"

        # Store the elapsed time in the Tag property of the timer
        self.Timer1.Tag = ElapsedTime

Here is what our final Timer.py file looks like:

import os
from delphifmx import *

class TimerForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Time = None
        self.Start = None
        self.Pause = None
        self.Reset = None
        self.ComboBox1 = None
        self.Back = None
        self.TimeDuration = None
        self.Status = None
        self.Timer1 = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Timer.pyfmx"))

        # Initially setting time label to zero and status to blank
        self.Time.Text = '00:00:00'
        self.Status.Text = ''

        # Add items to the combo box
        self.ComboBox1.Items.Add('Brush Teeth')
        self.ComboBox1.Items.Add('Boil Eggs')
        self.ComboBox1.Items.Add('Other')

        # You cannot type in the TEdit until Other from combo box is selected
        self.TimeDuration.Enabled = False
        self.Start.Enabled = False
        self.Pause.Enabled = False
        self.Reset.Enabled = False

        # Var to store start time value
        self.CountdownTime = 0

    def StartClick(self, Sender):
        self.Timer1.Enabled = True
        self.Timer1.Interval = 10
        self.Status.Text = ''

    def PauseClick(self, Sender):
        self.Timer1.Enabled = False

    def ResetClick(self, Sender):
        self.Time.Text = '00:00:00'  # Update the label
        self.Timer1.Tag = self.CountdownTime  # Update the timer tag
        self.Timer1.Enabled = False

    def SetOtherTime(self, sender):
        # Check for format of time given
        if self.TimeDuration.Text.count(':') == 2:
            Time = self.TimeDuration.Text.split(':')
            Minutes, Seconds, Milliseconds = int(
                Time[0]), int(Time[1]), int(Time[2])
            TotalMilliseconds = (Minutes * 60 * 1000) + 
                (Seconds * 1000) + Milliseconds

            self.CountdownTime = int(TotalMilliseconds)
            self.Timer1.Tag = self.CountdownTime

            self.Start.Enabled = True
            self.Pause.Enabled = True
            self.Reset.Enabled = True

        else:
            self.Status.Text = 'Give the time duration in minutes:seconds:milliseconds'

    def ComboSelected(self, sender):
        if self.ComboBox1.ItemIndex == 0:
            self.TimeDuration.Text = '2:00:00'
        elif self.ComboBox1.ItemIndex == 1:
            self.TimeDuration.Text = '5:10:00'
        elif self.ComboBox1.ItemIndex == 2:
            self.TimeDuration.Text = ''
            self.TimeDuration.Enabled = True

    def BackClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

    def Timer1Timer(self, Sender):
        ElapsedTime = self.Timer1.Tag - self.Timer1.Interval

        if ElapsedTime <= 0:
            self.Status.Text = 'Timer Ended!'
            self.Time.Text = '00:00:00'  # Update the label
            self.Timer1.Tag = self.CountdownTime  # Update the timer tag
            self.Timer1.Enabled = False

        # Calculate the number of minutes, seconds and milliseconds
        Minutes = ElapsedTime // (60 * 1000)
        Seconds = (ElapsedTime // 1000) % 60
        Milliseconds = ElapsedTime % 1000

        self.Time.Text = f"{Minutes:02d}:{Seconds:02d}.{Milliseconds:02d}"

        # Store the elapsed time in the Tag property of the timer
        self.Timer1.Tag = ElapsedTime

What Results Does Testing This Desktop App Give?

Now that code is ready; we can run our app by executing StopwatchTimerApp.py. Here is what our app looks like:

How to Create a Stopwatch/Timer Android App With Delphi For Python? The desktop app's appearance.

We can even navigate to the different forms by clicking on each button. Here is what our StopwatchForm looks like:

How to Create a Stopwatch/Timer Android App With Delphi For Python? The stopwatch form.

And here is what our TimerForm looks like:

How to Create a Stopwatch/Timer Android App With Delphi For Python? The timer form.

How to Create a Stopwatch/TimerApp For Android?

How to Create a Stopwatch/Timer Android App With Delphi For Python? A laptop showing the PythonFMXBuilder page.

Now that we have our time widget application ready, let’s convert this into an Android application.

The Delphi4Python Exporter exports TimerStopwatchApp with initialization logic for a desktop-based application. Therefore, we will use the PythonFMXBuilder to convert it to an Android app. 

So, open FMXBuilder and click Project > New project on the toolbar. Enter the name of the project that you want to build here. Here we define our project as StopwatchTimerApp.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Creating a new project.

Before we can add our Python files, we need to change some code that will allow us to run our project on Android. Let’s create a new file named StopwatchTimerApp_Android.py and paste the contents of StopwatchTimerApp.py.

Next, add your Python files and other supporting project files you used to build your application. Here we will not be adding StopwatchTimerApp.py as it will only be used to run our desktop application:

How to Create a Stopwatch/Timer Android App With Delphi For Python? The .py file contents

Now, right-click on TimerStopwatchApp_Android.py file and set it to the main file. But before we can build an .apk, let’s make important changes to our code. 

First off, Android applications are initialized automatically by Delphi applications. Because the program will be initialized automatically, we don’t need to initialize it or set a title manually. The Application.MainForm doesn’t need to be initialized either but just needs a variable. Lastly, like initialization, we don’t need to launch or destroy the program because Android handles both tasks.

Our StopwatchTimerApp_Android.py looks like:

from delphifmx import *
from MainMenu import MainForm


def main():
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()


if __name__ == '__main__':
    main()

Save the file with the code changes you’ve just made.

With PythonFMX Builder for Android, you can create an android application package file (.apk) or have it directly installed on your Android phone. To install the app directly on your mobile device, first, connect your android phone to your device and enable USB debugging on your phone. Next, click on the reload button on the top right corner. If your device is connected, you will see it appear on the drop-down menu.

How to Create a Stopwatch/Timer Android App With Delphi For Python? Choosing USB debugging.

Finally, select your device and click on Run Project:

31-6495829

This will install the app directly on your Android phone and run it.

What Results Does Testing This Android App Give?

Here is what our StopwatchTimerApp looks like on an Android device:

How to Create a Stopwatch/Timer Android App With Delphi For Python? The Android app running.

When we click on the Stopwatch or Timer button, we are taken to the next form:

How to Create a Stopwatch/Timer Android App With Delphi For Python? the time screen in the Python Android app.

Now we can select the options available in the combo box. Here we select the “Other” option:

How to Create a Stopwatch/Timer Android App With Delphi For Python? Choosing activities in the Android Python app.

Once we select the “Other” option, the Edit box allows us to set the time. We can then Start, Pause, or Reset the Timer.

The timer screen in the Python Android app. How to Create a Stopwatch/Timer Android App With Delphi For Python?

We can even navigate to the StopwatchForm and Start, Pause, or Reset our Stopwatch.

How to Create a Stopwatch/Timer Android App With Delphi For Python? The Python app running on Android.

Do You Want to Create More Apps Like This?

How to Create a Stopwatch/Timer Android App With Delphi For Python? A laptop showing the Delphi 11.3 landing page.

Congratulations on completing this tutorial! We hope you found it helpful to understand how to use Python GUI development tools to create desktop applications. With the help of DelphiFMX and other Delphi tools, you can easily create cross-platform applications that work on various devices, thanks to their user-friendly interface and powerful functionality. Whether you’re a seasoned programmer or just starting with Python, building a stopwatch or timer application is an excellent way to hone your skills and expand your knowledge. 

So, why not download Delphi and start creating your own Python-based Desktop and Android apps today?

What Are Some FAQs About Delphi For Python?

How to Create a Stopwatch/Timer Android App With Delphi For Python? A laptop showing the FAQ for Python for Android

What is Delphi for Python?

Delphi for Python is a tool that allows developers to create Python-based applications using the Delphi programming language. It provides a seamless integration between Delphi and Python, enabling developers to use the powerful features of both languages to create high-performance applications.

What is a time widget Android app?

It is an application that can be used to measure time intervals. It allows users to start and stop a timer and receive alerts when the time is up. These apps are commonly used in sports, cooking, and other activities that require accurate time measurement.

Why use Delphi for Python to create a Stopwatch/Timer Android app?

Delphi for Python provides a powerful and intuitive development environment for creating Android apps. It allows developers to leverage the strengths of both Delphi and Python to create high-performance and feature-rich applications quickly and easily.

What are the basic steps to create a Stopwatch/Timer Android app with Delphi for Python?

The basic steps to create a Stopwatch/Timer Android app with Delphi for Python include creating a new project in Delphi, adding the necessary components and controls, writing the code to implement the timer functionality, and deploying the app to an Android device.

Are there any limitations to creating a Stopwatch/Timer Android app with Delphi for Python?

There are no significant limitations to creating a Stopwatch/Timer Android app with Delphi for Python. However, developers may need to be familiar with Delphi and Python to create a fully functional and feature-rich app. Additionally, some advanced features may require additional third-party libraries or components.

The post How to Create a Stopwatch/Timer Android App With Delphi For Python? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-stopwatch-timer-android-app-with-delphi-for-python/feed/ 0 9990
How to Create a Unit Converter Android App Using Python GUI https://pythongui.org/how-to-create-a-unit-converter-android-app-using-python-gui/ https://pythongui.org/how-to-create-a-unit-converter-android-app-using-python-gui/#respond Thu, 11 May 2023 20:36:09 +0000 https://pythongui.org/?p=10058 Mobile applications have become increasingly popular today, where technology plays a significant role in our lives. One such application is a unit converter app, which allows users to convert different units of measurement quickly and...

The post How to Create a Unit Converter Android App Using Python GUI first appeared on Python GUI.

]]>
Mobile applications have become increasingly popular today, where technology plays a significant role in our lives. One such application is a unit converter app, which allows users to convert different units of measurement quickly and easily. If you’re interested in learning how to create a unit converter app for Android using Delphi For Python tools, then you’re in the right place. This tutorial will cover creating the UI, writing conversion logic, and packaging the app for Android devices. The result is a fully functional app that users can share. So let’s get started!

Why Create a Unit Conversion App?

How to Create a Unit Converter Android App Using Python GUI. Laptop with the VCL and FMX libraries for Python on the screen

A unit conversion app can be a helpful tool for a wide range of day-to-day tasks that require converting between different units of measurement. For example, when cooking, a recipe may call for certain ingredients in metric units, but the user may be more familiar with using imperial units. In this case, a unit conversion app can quickly convert the measurements to the preferred unit system, ensuring the recipe is prepared accurately.

So, unit conversion apps make it easy to convert between different units of measurement. Instead of manually calculating conversions, users can simply input a value and select the desired unit of measurement. Moreover, unit conversion apps help ensure accuracy by eliminating the potential for human error in manual calculations.

A dedicated app can save time and increase efficiency for tasks involving frequent unit conversions, such as engineering or scientific calculations. Also, by creating your own unit conversion app, you can tailor it to your specific needs and preferences, including which units to include, the user interface, and any additional features

Why Create Python GUI Using Delphi For Python?

How to Create a Unit Converter Android App Using Python GUI. An mage of a person editing a Python GUI app on their laptop

Delphi for Python is a package that allows Python developers to use Delphi components and libraries to create GUI applications. With Delphi for Python, Python developers can leverage the power of Delphi VCL and FMX frameworks to create native Windows applications or cross-platform applications, respectively. The package also includes Delphi4PythonExporter, which can export Python modules to Delphi DLLs.

PythonFMXBuilder is another tool that can be used to create cross-platform GUI applications using Python and Delphi FMX. It allows developers to build and deploy Python GUI applications to Windows, macOS, iOS, and Android platforms.

How to Create a Unit Converter Desktop App?

How to Create a Unit Converter Android App Using Python GUI. The RAD Studio IDE.

Before we start with the tutorial, let’s look at its prerequisites.

What Are the Requirements to Complete this Task?

The latest version of Python, PythonFMXBuilder, Delphi4PythonExporter, Delph CE, and any text editor or IDE (PyScripter is recommended) that supports Python are required for this tutorial.

We’ve got you covered if you don’t have these installed on your device. We recommend checking out this article, “Powerful Python GUI Project Setup” which will help you get started.

You can grab the code for this tutorial from our Git repository at: https://github.com/Embarcadero/PythonBlogExamples/tree/main/Unit_Conversion_App

How to Create a Form in Delphi?

Open Delphi CE and go create a blank application (File > New > Multi-Device Application > Blank Application > Ok). This will open a new project for you with a blank form. We have named our project UnitConversionApp.

How to Create a Unit Converter Android App Using Python GUI - a blank form in the RAD Studio IDE

To understand what each section of the above Delphi IDE means/represents, please go through the free eBook bundle we have developed. This eBook explains the ideology around Delphi Python EcoSystem, all Python GUI offerings, and much more.

How to Create a Unit Converter Android App Using Python GUI - the Python EBook download image

Let’s start by giving our form a name. Right-click on the form and click on QuickEdit. Here we will name our form Main and display the title as Unit Conversion App.

How to Create a Unit Converter Android App Using Python GUI . Naming the Python GUI app

Next, let’s resize our form. Head to the object inspector, and in the properties tab, search for ClientHeight and ClientWidth. We will set them as 480 and 306, respectively.

How to Create a Unit Converter Android App Using Python GUI . The Object Inspector

We will also rename the source file of our main form to MainForm.pas to make it easy to keep track of.

How to Create a Unit Converter Android App Using Python GUI  - the project manager

This form will be the primary interface for our Unit Converter application, where users will choose the units to convert. We’ll add a label that greets users with the app’s title to make it more like a main screen. To do this, navigate to the standard palette and locate the TLabel component. Afterward, simply drag and drop the component onto the form.

How to Create a Unit Converter Android App Using Python GUI . Searching the component palette for a TLabel.

Now, let’s change the text style to display the title. We can easily do this using TextSettings. So, select the Tlabel and head over to the Object Inspector on the bottom-left corner of your screen. Here in the search bar, search for TextSettings. Select Font under it and click on the ... to see options allowing you to change the label font, size, and style according to your needs.

How to Create a Unit Converter Android App Using Python GUI  - changing some of the control's properties in the object inspector.

Now rename the label’s text by right-clicking on that label and selecting Quick Edit. It is good practice to follow an intuitive naming convention to name your components to make them easier to track. Here, we named our label as Title with the text “Unit Conversion App.

How to Create a Unit Converter Android App Using Python GUI . The app's GUI

We can change the form’s background color by navigating to the Object Inspector and selecting the form’s fill property.

How to Create a Unit Converter Android App Using Python GUI . Chaning the fill style.
How to Create a Unit Converter Android App Using Python GUI  - the brush designer

Finally, we need to add a few buttons that will help us navigate to other forms where we will be converting our Units. So head on over to the Palette and add a few TButton components.

How to Create a Unit Converter Android App Using Python GUI  - searching the component palette for a TButton.
How to Create a Unit Converter Android App Using Python GUI  - the basic form.

As you can see, we have added four buttons to our form named Length, Temperature, Time, and Weight. These buttons will help us navigate to different forms that will help us convert the relevant units.

Next, let’s change the font size and style of this button text to make the button text more prominent. Here we have to use the font style as Segoe UI and increase the size to 16pt. We also increased the size of the buttons and aligned the text to the Center, the same as the Title label above, so that the text appears symmetric.

How to Create a Unit Converter Android App Using Python GUI  - the object inspector.

Here is what our final MainForm looks like:

How to Create a Unit Converter Android App Using Python GUI - a preview of the unit conversion app

Now that we’ve created our main screen, let’s add four new forms to help us with the unit conversions. To create our next form, right-click on UnitConversionApp.exe and select Add New > Multi-Device Form.

How to Create a Unit Converter Android App Using Python GUI - selecting to add a new multi-device form

This will create our new form. We will rename this form as Length and the source file as LengthForm.pas.

Next, resize the form to the same specifications as our MainForm to maintain consistency. Let’s also add a few labels and buttons to our form and make it more visually appealing.

Here is what our form looks like:

How to Create a Unit Converter Android App Using Python GUI - the GUI

As you can see, we have also added a small Status label indicated by the hyphen right above the Back and Convert buttons. We have also changed its color using TextSettings to help us display error messages based on wrong user inputs.

Now that our LengthForm has the basic visual components let’s add a few components that will allow us to convert our lengths based on user input. Start by navigating to the Palette and searching for the TComboBox component. We will add this to the form for the user to select the conversion unit. In addition to this, we will add a label under the Value label to indicate the result of the conversion.

How to Create a Unit Converter Android App Using Python GUI  - adding additional features to the GUI

Finally, let’s add a TEdit component that will help the user write the unit’s value to be converted. Here is what our final LengthForm looks like:

How to Create a Unit Converter Android App Using Python GUI - the final details

Now that we know how to create a unit form, we can create similar forms for Temperature, Time, and Weights. Here is what our final forms look like:

19-4566276
20-9007786
21-2680062

Now that our forms are ready, we need to add procedures to ensure our buttons work. So open up each form by double-clicking on the .fmx file of each form.

How to Create a Unit Converter Android App Using Python GUI

Next, double-click each button to construct the Click methods in the .pas files of our forms.

How to Create a Unit Converter Android App Using Python GUI

To ensure that the methods are not lost when we export our forms in Python, add at least a single comment (//)to each of the Click methods.

How to Create a Unit Converter Android App Using Python GUI

How to Export this Delphi Project as a Python Script?

Now that our forms are ready, we can export our project as a Python script. Navigate to Tools > Export To Python > Export Current Entire Project.

How to Create a Unit Converter Android App Using Python GUI

Next, give your application a title, select the Application Main Form as the MainForm, and, finally, select the directory of choice. Click on Export to generate your files.

How to Create a Unit Converter Android App Using Python GUI - exporting the UI

Because we have 5 forms for this project, Delphi will generate 6 Python scripts i.e., MainForm.py, LengthForm.py, TimeForm.py, TemperatureForm.py, WeightForm.py, and UnitConversionApp.py in your chosen directory. The form Python files contain the classes for the individual forms, and the UnitConversionApp is used to launch our Delphi app. 

Along with the Python files for each form, Delphi generates a .pyfmx file for each .py file in the same directory. These files contain all the form’s visual information.
Let’s take a look at the contents of UnitConversionApp.py, which will run our application:

from delphifmx import *
from MainForm import Main

def main():
    Application.Initialize()
    Application.Title = 'UnitConversionApp'
    Application.MainForm = Main(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Next, let’s take a look at MainForm.py that will show us our main screen:

import os
from delphifmx import *

class Main(Form):

    def __init__(self, owner):
        self.Title = None
        self.TemperatureFromButton = None
        self.LengthFormButton = None
        self.WeightFromButton = None
        self.TimeFormButton = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainForm.pyfmx"))

    def TemperatureFromButtonClick(self, Sender):
        pass

    def LengthFormButtonClick(self, Sender):
        pass

    def WeightFromButtonClick(self, Sender):
        pass

    def TimeFormButtonClick(self, Sender):
        pass

Here are the contents for the rest of the forms.

LengthForm.py:

import os
from delphifmx import *

class Length(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "LengthForm.pyfmx"))

    def ConvertClick(self, Sender):
        pass

    def BackButtonClick(self, Sender):
        pass

TemperatureForm.py:

import os
from delphifmx import *

class Temperature(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TemperatueForm.pyfmx"))

    def ConvertClick(self, Sender):
        pass

    def BackButtonClick(self, Sender):
        pass

TimeForm.py:

import os
from delphifmx import *

class Time(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TimeForm.pyfmx"))

    def ConvertClick(self, Sender):
        pass

    def BackButtonClick(self, Sender):
        pass

And finally WeightForm.py:

import os
from delphifmx import *

class Weight(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "WeightForm.pyfmx"))

    def ConvertClick(self, Sender):
        pass

    def BackButtonClick(self, Sender):
        pass

How to Add Functionality to the App?

Now that our forms are ready, we can add functionality to our App.

For our MainForm the only thing we need to do is link the relevant button to each of the forms. To do this, let’s import the conversion forms into our MainForm.py:

# Additional imports
from LengthForm import Length
from TemperatueForm import Temperature
from TimeForm import Time
from WeightForm import Weight

Next, navigate to the Click function for each form, create an instance of the form and assign it to a variable. We then display the new form using the show() method. For example, let’s navigate to TemperatureFromButtonClick, create an instance of TemperatureForm, and assign it to a new variable self.TempForm. We then use show() to display our form. Here is what our TemperatureFromButtonClick looks like:

def TemperatureFromButtonClick(self, Sender):
        self.TempForm = Temperature(self)
        self.TempForm.Show()

We can replicate this for the other buttons. Here is what our final MainForm.py file looks like:

import os
from delphifmx import *
# Additional imports
from LengthForm import Length
from TemperatueForm import Temperature
from TimeForm import Time
from WeightForm import Weight

class Main(Form):

    def __init__(self, owner):
        self.Title = None
        self.TemperatureFromButton = None
        self.LengthFormButton = None
        self.WeightFromButton = None
        self.TimeFormButton = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "MainForm.pyfmx"))

    def TemperatureFromButtonClick(self, Sender):
        self.TempForm = Temperature(self)
        self.TempForm.Show()

    def LengthFormButtonClick(self, Sender):
        self.LengthForm = Length(self)
        self.LengthForm.Show()

    def WeightFromButtonClick(self, Sender):
        self.WeightForm = Weight(self)
        self.WeightForm.Show()

    def TimeFormButtonClick(self, Sender):
        self.TimeForm = Time(self)
        self.TimeForm.Show()

Now, let’s move our LengthForm. First, let’s start by defining a dictionary in the __init__ function that stores the length conversions for each unit.

# Dictionary that gives us the relationship between units
        self.data = {
            "meter":{"meter":1, "kilometer":1/1000, "centimeter":100, "millimeter":1000, "yard":1.094, "foot":3.281, "inch":39.37, "mile":1/1609},
            "kilometer":{"meter":1000, "kilometer":1, "centimeter":100000, "millimeter":1000000, "yard":1094, "foot":3281, "inch":39370, "mile":1.609},
            "centimeter":{"meter":1/100, "kilometer":1/100000, "centimeter":1, "millimeter":10, "yard":1/91.44, "foot":1/30.48, "inch":1/2.54, "mile":1/160900},
            "millimeter":{"meter":1/1000, "kilometer":1/1000000, "centimeter":1/10, "millimeter":1, "yard":1/914.4, "foot":1/304.8, "inch":1/25.4, "mile":1/1609000},
            "yard":{"meter":1/1.094, "kilometer":1/1094, "centimeter":91.44, "millimeter":914.4, "yard":1, "foot":3, "inch":36, "mile":1/1760},
            "foot":{"meter":1/3.281, "kilometer":1/3281, "centimeter":30.48, "millimeter":304.8, "yard":1/3, "foot":1, "inch":12, "mile":1/5280},
            "inch":{"meter":1/39.37, "kilometer":1/39370, "centimeter":2.54, "millimeter":25.4, "yard":1/36, "foot":1/12, "inch":1, "mile":1/63360},
            "mile":{"meter":1609, "kilometer":1.609, "centimeter":160900, "millimeter":1609000, "yard":1760, "foot":5280, "inch":63360, "mile":1}
        }

Here we have defined the dictionary such that to convert from meter to kilometer, we use the meter key to get the nested dictionary and then access the kilometer conversion using that dictionary. Here we get the number 1/1000, so multiplying any user value with this number will yield our converted result. 

Next, let’s iterate over the dictionary and populate the combo boxes in our form.

# Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromUnit.Items.append(key)
            self.ToUnit.Items.append(key)

Finally, we initialize the Status label empty using the .Text property of the labels. Here is what our final __init__ function looks like:

def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "LengthForm.pyfmx"))


        # Addtional initializations
        # Dictionary that gives us the relationship between units
        self.data = {
            "meter":{"meter":1, "kilometer":1/1000, "centimeter":100, "millimeter":1000, "yard":1.094, "foot":3.281, "inch":39.37, "mile":1/1609},
            "kilometer":{"meter":1000, "kilometer":1, "centimeter":100000, "millimeter":1000000, "yard":1094, "foot":3281, "inch":39370, "mile":1.609},
            "centimeter":{"meter":1/100, "kilometer":1/100000, "centimeter":1, "millimeter":10, "yard":1/91.44, "foot":1/30.48, "inch":1/2.54, "mile":1/160900},
            "millimeter":{"meter":1/1000, "kilometer":1/1000000, "centimeter":1/10, "millimeter":1, "yard":1/914.4, "foot":1/304.8, "inch":1/25.4, "mile":1/1609000},
            "yard":{"meter":1/1.094, "kilometer":1/1094, "centimeter":91.44, "millimeter":914.4, "yard":1, "foot":3, "inch":36, "mile":1/1760},
            "foot":{"meter":1/3.281, "kilometer":1/3281, "centimeter":30.48, "millimeter":304.8, "yard":1/3, "foot":1, "inch":12, "mile":1/5280},
            "inch":{"meter":1/39.37, "kilometer":1/39370, "centimeter":2.54, "millimeter":25.4, "yard":1/36, "foot":1/12, "inch":1, "mile":1/63360},
            "mile":{"meter":1609, "kilometer":1.609, "centimeter":160900, "millimeter":1609000, "yard":1760, "foot":5280, "inch":63360, "mile":1}
        }

        # Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromUnit.Items.append(key)
            self.ToUnit.Items.append(key)

        self.Status.Text = ""

Next, let’s redefine the Back button to open up our new form. So in the BackButtonClick method,  use the show() method to open up the MainForm and then we will use the .Destroy() method to destroy the current form, then .

Here is what our BackButtonClick method looks like:

def BackButtonClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

Finally, lets define our ConvertClick function that will make our conversion happen. First, start by checking whether the user has selected values in both combo boxes and added a value to be converted. Next, use the .Text property to get the given and to units from the form. We also get the amountGiven by the user in the edit box, and finally calculate the amount by simply multiplying the amountGiven with the conversion rate from the dictionary:

if self.FromUnit.Selected!=None and self.ToUnit.Selected!=None and self.FromValue.Text!="": # Checking is all required fields filles
            given = self.FromUnit.Selected.Text
            to = self.ToUnit.Selected.Text
            amountGiven = int(self.FromValue.Text)
            amountCalculated  = self.data[given][to] * amountGiven

But before we can display our value, we add a check to ensure that the calculated value does not exceed 8 characters. If it does, we then convert it into scientific notation. We then reset the Status and display our converted value on the label.

if self.FromUnit.Selected!=None and self.ToUnit.Selected!=None and self.FromValue.Text!="": # Checking is all required fields filles
            given = self.FromUnit.Selected.Text
            to = self.ToUnit.Selected.Text
            amountGiven = int(self.FromValue.Text)
            amountCalculated  = self.data[given][to] * amountGiven
            if len(str(amountCalculated)) > 8: # If the value is longer than 8 digits then use scientific notation
                amountCalculated = '{:.3e}'.format(amountCalculated)
            self.ToValue.Text = amountCalculated
            self.Status.Text = "" # Reset status since conversion was successful (incase there was an alert earlier)

Finally, if the user fails to fill in any required details we will display an error in the Status label. Here is what our final ConvertClick function looks like:

def ConvertClick(self, Sender):
        if self.FromUnit.Selected!=None and self.ToUnit.Selected!=None and self.FromValue.Text!="": # Checking is all required fields filles
            given = self.FromUnit.Selected.Text
            to = self.ToUnit.Selected.Text
            amountGiven = int(self.FromValue.Text)
            amountCalculated  = self.data[given][to] * amountGiven
            if len(str(amountCalculated)) > 8: # If the value is longer than 8 digits then use scientific notation
                amountCalculated = '{:.3e}'.format(amountCalculated)
            self.ToValue.Text = amountCalculated
            self.Status.Text = "" # Reset status since conversion was successful (incase there was an alert earlier)
        else:
            self.Status.Text = "Please fill all relevant inputs!"

Following is the final LengthForm.py file code:

import os
from delphifmx import *

class Length(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "LengthForm.pyfmx"))


        # Addtional initializations
        # Dictionary that gives us the relationship between units
        self.data = {
            "meter":{"meter":1, "kilometer":1/1000, "centimeter":100, "millimeter":1000, "yard":1.094, "foot":3.281, "inch":39.37, "mile":1/1609},
            "kilometer":{"meter":1000, "kilometer":1, "centimeter":100000, "millimeter":1000000, "yard":1094, "foot":3281, "inch":39370, "mile":1.609},
            "centimeter":{"meter":1/100, "kilometer":1/100000, "centimeter":1, "millimeter":10, "yard":1/91.44, "foot":1/30.48, "inch":1/2.54, "mile":1/160900},
            "millimeter":{"meter":1/1000, "kilometer":1/1000000, "centimeter":1/10, "millimeter":1, "yard":1/914.4, "foot":1/304.8, "inch":1/25.4, "mile":1/1609000},
            "yard":{"meter":1/1.094, "kilometer":1/1094, "centimeter":91.44, "millimeter":914.4, "yard":1, "foot":3, "inch":36, "mile":1/1760},
            "foot":{"meter":1/3.281, "kilometer":1/3281, "centimeter":30.48, "millimeter":304.8, "yard":1/3, "foot":1, "inch":12, "mile":1/5280},
            "inch":{"meter":1/39.37, "kilometer":1/39370, "centimeter":2.54, "millimeter":25.4, "yard":1/36, "foot":1/12, "inch":1, "mile":1/63360},
            "mile":{"meter":1609, "kilometer":1.609, "centimeter":160900, "millimeter":1609000, "yard":1760, "foot":5280, "inch":63360, "mile":1}
        }

        # Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromUnit.Items.append(key)
            self.ToUnit.Items.append(key)

        self.Status.Text = ""

    def ConvertClick(self, Sender):
        if self.FromUnit.Selected!=None and self.ToUnit.Selected!=None and self.FromValue.Text!="": # Checking is all required fields filles
            given = self.FromUnit.Selected.Text
            to = self.ToUnit.Selected.Text
            amountGiven = int(self.FromValue.Text)
            amountCalculated  = self.data[given][to] * amountGiven
            if len(str(amountCalculated)) > 8: # If the value is longer than 8 digits then use scientific notation
                amountCalculated = '{:.3e}'.format(amountCalculated)
            self.ToValue.Text = amountCalculated
            self.Status.Text = "" # Reset status since conversion was successful (incase there was an alert earlier)
        else:
            self.Status.Text = "Please fill all relevant inputs!"
    def BackButtonClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

We can follow the same process to add functionalities to our WeightForm, and TimeForm. Here is that our final WeightForm.py looks like:

import os
from delphifmx import *

class Weight(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "WeightForm.pyfmx"))

        # Addtional initializations
        # Dictionary that gives us the relationship between units
        self.data = {
            "kilogram":{"kilogram":1, "gram":1000, "milligram":1000000, "metric ton":1/1000, "pound":2.205, "ounce":35.274},
            "gram":{"kilogram":1/1000, "gram":1, "milligram":1000, "metric ton":1/1000000, "pound":1/453.6, "ounce":1/28.35},
            "milligram":{"kilogram":1/1000000, "gram":1/1000, "milligram":1, "metric ton":1/1000000000, "pound":1/453600, "ounce":1/28350},
            "metric ton":{"kilogram":1000, "gram":1000000, "milligram":1000000000, "metric ton":1, "pound":2205, "ounce":35270},
            "pound":{"kilogram":1/2.205, "gram":453.6, "milligram":453600, "metric ton":2205, "pound":1, "ounce":16},
            "ounce":{"kilogram":1/35.274, "gram":28.35, "milligram":28350, "metric ton":1/35270, "pound":1/16, "ounce":1}
        }

        # Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromUnit.Items.append(key)
            self.ToUnit.Items.append(key)

        self.Status.Text = ""

    def ConvertClick(self, Sender):
        if self.FromUnit.Selected!=None and self.ToUnit.Selected!=None and self.FromValue.Text!="": # Checking is all required fields filles
            given = self.FromUnit.Selected.Text
            to = self.ToUnit.Selected.Text
            amountGiven = int(self.FromValue.Text)
            amountCalculated  = self.data[given][to] * amountGiven
            if len(str(amountCalculated)) > 8: # If the value is longer than 8 digits then use scientific notation
                amountCalculated = '{:.3e}'.format(amountCalculated)
            self.ToValue.Text = amountCalculated
            self.Status.Text = "" # Reset status since conversion was successful (incase there was an alert earlier)
        else:
            self.Status.Text = "Please fill all relevant inputs!"

    def BackButtonClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

And here is what our final TimeForm.py looks like:

import os
from delphifmx import *

class Time(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TimeForm.pyfmx"))

        # Addtional initializations
        # Dictionary that gives us the relationship between units
        self.data = {
            "second":{"second":1, "millisecond":1000, "minute":1/60, "hour":1/3600, "day":1/86400, "week":1/6084800, "month":1/2628000, "year":1/31540000},
            "millisecond":{"second":1/1000, "millisecond":1, "minute":1/60000, "hour":1/3600000, "day":1/86400000, "week":1/6084800000, "month":1/2628000000, "year":1/31540000000},
            "minute":{"second":60, "millisecond":60000, "minute":1, "hour":1/60, "day":1/1440, "week":1/10080, "month":1/43800, "year":1/525600},
            "hour":{"second":3600, "millisecond":3600000, "minute":60, "hour":1, "day":1/24, "week":1/168, "month":1/730, "year":1/8760},
            "day":{"second":86400, "millisecond":86400000, "minute":1440, "hour":24, "day":1, "week":1/7, "month":1/30.417, "year":1/365},
            "week":{"second":604800, "millisecond":604800000, "minute":10080, "hour":168, "day":7, "week":1, "month":1/4.345, "year":1/52.143},
            "month":{"second":2628000, "millisecond":2628000000, "minute":43800, "hour":730, "day":30.417, "week":4.345, "month":1, "year":1/12},
            "year":{"second":31540000, "millisecond":31540000000, "minute":525600, "hour":8760, "day":365, "week":52.143, "month":12, "year":1}
        }

        # Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromUnit.Items.append(key)
            self.ToUnit.Items.append(key)

        self.Status.Text = ""

    def ConvertClick(self, Sender):
        if self.FromUnit.Selected!=None and self.ToUnit.Selected!=None and self.FromValue.Text!="": # Checking is all required fields filles
            given = self.FromUnit.Selected.Text
            to = self.ToUnit.Selected.Text
            amountGiven = int(self.FromValue.Text)
            amountCalculated  = self.data[given][to] * amountGiven
            if len(str(amountCalculated)) > 8: # If the value is longer than 8 digits then use scientific notation
                amountCalculated = '{:.3e}'.format(amountCalculated)
            self.ToValue.Text = amountCalculated
            self.Status.Text = "" # Reset status since conversion was successful (incase there was an alert earlier)
        else:
            self.Status.Text = "Please fill all relevant inputs!"

    def BackButtonClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

However, it is important to note that unlike our other forms, the temperature conversions require us to use formulae that involve operations other than division and multiplication. So let’s make changes to our TemperatureForm.py.

What Changes Have to be Made in the Temperature Form? 

Start by opening TemperatureForm.py and define the __init__ functions and BackClick button like our other forms.

Next, we will need to redefine our dictionary to store our functions. So navigate to the __init__ function and create a lambda function for each unit conversion.

self.data = {
            "celsius":{"celsius":lambda a: a, "kelvin":lambda a: a+273.15, "fahrenheit":lambda a: a*(9/5)+32},
            "kelvin":{"celsius":lambda a: a-273.15, "kelvin":lambda a: a, "fahrenheit":lambda a: (a-273.15)*(9/5)+32},
            "fahrenheit":{"celsius":lambda a: (a-32)*(5/9), "kelvin":lambda a: (a-32)*(5/9)+273.15, "fahrenheit":lambda a: a}                
        }

Let’s take a look at an example, to convert from Celsius to Kelvin, we need to multiply our Celsius value by 9/5 then add 32 to it. We thus create a lambda function that takes in a single value and converts it into Celsius as lambda a: a * (9.5) + 32. We can replicate the same for other conversions. Therefore, to convert a value, we will use the dictionary to get the relevant function and then pass in the value to be converted. For example, self.data["celsius"]["fahrenheit"](5) will convert 5 degree Celsius to Fahrenheit.

Next, we will change the ConvertClick function to pass values to the lambda functions to calculate the relevant amounts. Here is what our final TemperatureForm.py looks like:

import os
from delphifmx import *

class Temperature(Form):

    def __init__(self, owner):
        self.FromValue = None
        self.UnitFromLabel = None
        self.ValueFromLabel = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromUnit = None
        self.ToUnit = None
        self.ToValue = None
        self.UnitToLabel = None
        self.ValueToLabel = None
        self.BackButton = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TemperatueForm.pyfmx"))

        # Addtional initializations
        # Dictionary that gives us the relationship between units using lamda functions
        self.data = {
            "celsius":{"celsius":lambda a: a, "kelvin":lambda a: a+273.15, "fahrenheit":lambda a: a*(9/5)+32},
            "kelvin":{"celsius":lambda a: a-273.15, "kelvin":lambda a: a, "fahrenheit":lambda a: (a-273.15)*(9/5)+32},
            "fahrenheit":{"celsius":lambda a: (a-32)*(5/9), "kelvin":lambda a: (a-32)*(5/9)+273.15, "fahrenheit":lambda a: a}                
        }

        # Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromUnit.Items.append(key)
            self.ToUnit.Items.append(key)

        self.Status.Text = ""

    def ConvertClick(self, Sender):
        if self.FromUnit.Selected!=None and self.ToUnit.Selected!=None and self.FromValue.Text!="":
            given = self.FromUnit.Selected.Text
            to = self.ToUnit.Selected.Text
            amountGiven = int(self.FromValue.Text)
            amountCalculated  = self.data[given][to](amountGiven) # using the lambda 
            if len(str(amountCalculated)) > 8: # if the value is longer than 8 digits then use scientific notation
                amountCalculated = '{:.3e}'.format(amountCalculated)
            self.ToValue.Text = amountCalculated
            self.Status.Text = "" # reset status since conversion was successful (incase there was an alert earlier) 
        else: 
            self.Status.Text = "Please fill all relevant inputs!"        
        
    def BackButtonClick(self, Sender):
        Application.MainForm.Show()
        self.Destroy()

What Results Does Testing This Desktop App Give?

Now that code is ready, we can run our app by executing UnitConversionApp.py. Here is what MainForm looks like:

How to Create a Unit Converter Android App Using Python GUI - the UI in action

We can even navigate to the different forms by clicking each button. Here is what our LengthForm looks like:

How to Create a Unit Converter Android App Using Python GUI - the length form

Here is what our TimeForm:

How to Create a Unit Converter Android App Using Python GUI - another form

Here is our TemperatureForm:

How to Create a Unit Converter Android App Using Python GUI - the temperature form

And finally here is what our WeightForm looks like:

How to Create a Unit Converter Android App Using Python GUI 0 the weight form

How To Turn This Into an Android App?

How to Create a Unit Converter Android App Using Python GUI - a laptop showing the PythonFMXBuilder download page

Now that our Unit Conversion App is running, let’s convert this into an Android application.

So, open up FMXBuilder and click on Project > New project on the toolbar. Enter the name of the project that you want to build here. Here we define our project as UnitConversionApp.

How to Create a Unit Converter Android App Using Python GUI - naming the project

Next, add your Python and .pyfmx files by right-clicking on the App and selecting Add file.

How to Create a Unit Converter Android App Using Python GUI - adding a file

Before we can add our UnitConversionApp.py file, we need to change some code to allow us to run our project in Android. Let’s create a new file named UnitConversionApp_Android.py and paste the contents of UnitConversionApp.py.

Next, open up the UnitConversionApp_Android.py file and start making some important changes. First off, Android applications are initialized automatically by Delphi applications. Because the program will be initialized automatically, we don’t need to initialize it or set a title manually. The Application.MainForm doesn’t need to be initialized either but just needs a variable. Lastly, like initialization, we don’t need to launch or destroy the program because Android handles both tasks.

Here is what our UnitConversionApp_Android.py file looks like:

from delphifmx import *
from MainForm import Main


def main():
    Application.MainForm = Main(Application)
    Application.MainForm.Show()


if __name__ == '__main__':
    main()

Save the file with the code changes you’ve just made. Now, right-click on UnitConversionApp_Android.py file and set it to the main file.

How to Create a Unit Converter Android App Using Python GUI - setting the main form

PythonFMX Builder for Android can generate an android application package file (.apk) or install the app directly onto your Android device. To directly install the app onto your mobile device, you’ll first need to connect your Android phone to your device and enable USB debugging on your phone. Afterward, simply click on the reload button located in the top right corner. If your device is properly connected, it will appear in the drop-down menu.

How to Create a Unit Converter Android App Using Python GUI - the APK details

Finally, select your device and click on Run Project:

36-9884589

This will install the app directly on your Android phone and run it.

Does the Android App Work As We Expect?

Upon opening the app on your Android device, you will see the main menu:

How to Create a Unit Converter Android App Using Python GUI - testing the Android app

Now, if we select the length option, we will be taken to the LengthForm where we can select our desired units and do successful conversions:

How to Create a Unit Converter Android App Using Python GUI - the length

We can even check whether the resultant conversion is given in scientific notation when required.

How to Create a Unit Converter Android App Using Python GUI - more on the length form

Let’s also check that if we had not filled in the required details and pressed the Convert button, do we get an error:

How to Create a Unit Converter Android App Using Python GUI - more details

We can even check that our TemperatureForm, TimeForm, and WeightForm work as expected:

How to Create a Unit Converter Android App Using Python GUI - temp form
How to Create a Unit Converter Android App Using Python GUI - the time form
How to Create a Unit Converter Android App Using Python GUI - the weight form

Are You Ready To Create Your Own Unit Converter App?

How to Create a Unit Converter Android App Using Python GUI - a laptop showing the Edge browser description page for RAD Studio 11

Congratulations on completing this tutorial on creating an Android unit converter app using Python GUI! We hope this tutorial has given you insights into how Python can be used to develop mobile apps and simplify the creation of graphical user interfaces. With the help of Delphi for Python Exporter and PythonFMXBuilder, you can easily deploy Python scripts on Android devices and create visually appealing UIs in Delphi. The Delphi Community Edition is a great tool with a streamlined IDE, code editor, integrated debugger, and hundreds of visual components.

Now that you have the necessary tools, you can create Python-based mobile apps using Delphi. So, why not get started and create your app today? The possibilities are endless!

What Are Some FAQs Related to this Tutorial?

How to Create a Unit Converter Android App Using Python GUI - the FAQs

What is Embarcadero?

Embarcadero technologies are created for the best-skilled programmers worldwide who build and support the most important applications. Because we are the developer champion and can help them create scalable, secure enterprise apps more quickly than with any other solution on the market, our clients select Embarcadero. Ninety of the Fortune 100 and a vibrant community of more than three million customers worldwide have relied on Embarcadero’s award-winning products for more than 30 years.

What GUI library is used to create the app’s user interface?

The app’s user interface is created using the delphifmx library and other tools such as Delphi CE, PythonFMXBuilder, and Delphi4PythonExporter.

Is it possible to create an Android app using Python?

Yes, it is possible to create an Android app using Python.

Do I need any prior programming experience to follow this tutorial?

While some programming experience would be helpful, this tutorial is designed to be beginner-friendly and walks you through the process step-by-step.

The post How to Create a Unit Converter Android App Using Python GUI first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-unit-converter-android-app-using-python-gui/feed/ 0 10058
How To Create A Python Quiz Application With DelphiFMX? https://pythongui.org/how-to-create-a-python-quiz-application-with-delphifmx/ https://pythongui.org/how-to-create-a-python-quiz-application-with-delphifmx/#respond Wed, 03 May 2023 19:16:03 +0000 https://pythongui.org/?p=9883 Python is one of the most popular programming languages today, with uses ranging from data analysis to web development. It’s understandable why many programmers prefer Python due to its simple syntax and robust libraries. While...

The post How To Create A Python Quiz Application With DelphiFMX? first appeared on Python GUI.

]]>
Python is one of the most popular programming languages today, with uses ranging from data analysis to web development. It’s understandable why many programmers prefer Python due to its simple syntax and robust libraries. While there are many resources for learning Python scripting, quizzes are occasionally the greatest way to evaluate your understanding. In this post, we’ll look at how to use DelphiFMX, a powerful cross-platform application development framework, to build a Python quiz application.

Why Should You Build a Python Quiz Android App?

Constructing a Python quiz enables you to combine your understanding of Python with mobile app development and is a terrific way to improve your programming abilities. To construct a quiz app installed on Android smartphones, you can utilize several tools, including DelphiFMX and PythonFMXBuilder. 

By creating a quiz app, you can give users a fun and instructive experience while simultaneously showcasing your programming skills to potential employers or clients. To keep users interested, you may personalize the app to include many categories and levels of difficulty. Developing an Android quiz app in Python can be a fulfilling undertaking that can advance your programming abilities and benefit users.

What Tools do Python Developers Prefer For Building Python GUIs?

How To Create A Python Quiz Application With DelphiFMX? A laptop with the Python Tools download page displayed on screen

Several tools support the ability to create GUIs in Python. PyScripter is a free and open-source IDE for Python on Windows and is one of the most popular options. It was first created as a straightforward IDE to offer a potent scripting option for Delphi applications. It has since developed into a powerful IDE for Python development, nevertheless.

Another well-liked tool for creating GUIs among Python developers is Delphi Community Edition. Because of its open-source nature, the DelphiFMX module gives Python programmers access to the FireMonkey GUI framework. The library makes it possible to create GUIs for various operating systems, including Windows, macOS, Linux, and Android.

A strong Python and Delphi ecosystem depends on the Delphi4PythonExporter. Python programmers can write design code more quickly by utilizing Delphi’s UI design capabilities. As they may design programs using their Delphi skills and subsequently give Python analogs of those apps, this tool can also be helpful for Delphi developers.

PythonFMXBuilder is a DelphiFMX-based Python application builder for Android applications. It enables programmers to install a specific Python script on their phone and incorporate it into an Android application.

How Can You Create A Python Quiz App For Windows Desktop?

How To Create A Python Quiz Application With DelphiFMX? A laptop showing the PyScripter Python IDE

Let’s create a basic quiz application for desktop devices! A good approach would be to use the Delphi tools mentioned above. So let’s get started!

What Are the Requirements to Create this App?

Python, PythonFMXBuilder, Delphi4PythonExporter, Delphi, and any text editor or IDE (PyScripter is recommended) that supports Python are required for this tutorial.

We’ve got you covered if you don’t have these installed on your device. We recommend checking out this article, “Powerful Python GUI Project Setup” which will help you get started.

You can grab the code for this tutorial from our Git repository at: https://github.com/Embarcadero/PythonBlogExamples/tree/main/Python_Quiz_App

How to Start a Basic Form For the App in Delphi?

Open Delphi CE and create a blank application by navigating to File > New > Multi-Device Application > Blank Application > Ok. Here we have named our project PythonQuizApp.

How To Create A Python Quiz Application With DelphiFMX? The RAD Studio IDE with an example form on display

To understand what each section of the above Delphi IDE means/represents, please go through the free eBook bundle we have developed. This eBook explains the ideology around Delphi Python EcoSystem, all Python GUI offerings, and much more.

How To Create A Python Quiz Application With DelphiFMX? The Python GUI ebook bundle.

Let’s start by giving our form a name. Right-click on the form and click on QuickEdit. Here we will name our form MainForm and display the title as PythonQuizApp.

How To Create A Python Quiz Application With DelphiFMX? Using QuickEdit.

Next, let’s resize our form. Head to the object inspector, and in the properties tab, search for ClientHeight and ClientWidth. We will set them as 550 and 350, respectively.

How To Create A Python Quiz Application With DelphiFMX? TYhe Object Inspector.

We will also rename the source file of our main form to Main.pas to make it easy to keep track of.

How To Create A Python Quiz Application With DelphiFMX? The project manager.

As you may have guessed, this is the main form of our quiz app. It will serve as the main screen where users will start their Python quiz. To make it more like a quiz app, let us add a label that will greet us with the title of our app. Head over to the standard palette and search for the TLabel component. Next, drag and drop the component into the form.

How To Create A Python Quiz Application With DelphiFMX? Searching the component palette

Now, let’s change the text style to display the title. We will do this using TextSettings. Head over to the Object Inspector and search for TextSettings. Select Font under it and click on the ... to see options allowing you to change the label font, size, and style according to your needs.

How To Create A Python Quiz Application With DelphiFMX? The object inspector.

Now rename the text of each label by right-clicking on that label and selecting Quick Edit. It is important to follow an intuitive naming convention to name the labels so that it is easier to track them. Here, we named our TLabel component as Title with the text “Ultimate Python Quiz.”

How To Create A Python Quiz Application With DelphiFMX? The main form.

We can change the form’s background color by navigating to the Object Inspector and selecting the form’s fill property.

How To Create A Python Quiz Application With DelphiFMX? The object inspector.
How To Create A Python Quiz Application With DelphiFMX? Choosing the right color.

Finally, we need a way to navigate to the next form, where we will start our quiz questions. So, go to the Palette and add a button using the TButton component.

How To Create A Python Quiz Application With DelphiFMX? Searching the component palette for a button.
How To Create A Python Quiz Application With DelphiFMX? Adding the start button to our app's form

As you can see, we have named our button Start. You should even change the font size and style of this button text (as we did for the TLabels above) to make the “START” text on the button more prominent. Here we have to use the font style as Segoe UI. We have also aligned the text to the Center, the same as the Title label above, so that the text appears symmetric.

How To Create A Python Quiz Application With DelphiFMX? Selecting the alignment properties

After these changes, our form will look much more visually attractive:

How To Create A Python Quiz Application With DelphiFMX? The project in the style editor.

Now that we are done with the Main form of our app, let’s create a new form that will display our questions. So right-click on PythonQuizApp.exe and select Add New > Multi-Device Form.

How To Create A Python Quiz Application With DelphiFMX? Choosing a multi-device form type.

This will create a new form that we have named as QuizForm and the source file as Quiz.pas.

Next, we will populate our form with labels, text boxes, and buttons to help users log in to our application. We will give them intuitive names as we add elements to the form. Here is what our final QuizForm looks like:

How To Create A Python Quiz Application With DelphiFMX? The options screen of our app.

As you can see, we have added 3 labels. The label on the top named QuestionNumberLabel will display the number of attempted questions, whereas the Question label will display the question. Finally, the AnswerStatus label will help us displays a Correct or Incorrect message if the user chooses the answer to the question. If the user does not answer a question, the AnswerStatus will show an error.

We have also added 4 option buttons that will display the choices for each question, and the Next button will help display the next questions only when the user has attempted the current question. After the user has attempted all questions, the button will open the final form that will display the score for the quiz.

We may also see how our app appears on desktop and Android phones. Switch the Style from Windows to Android to verify this. This will alter how our form appears.

How To Create A Python Quiz Application With DelphiFMX? The Android version of the form display.

Finally, we can make our final form that will help display the user’s level and the quiz’s score. We named our form ResultsForm and the source file Results.pas. Here is what our ResultsForm looks like:

How To Create A Python Quiz Application With DelphiFMX? Teh results.

Now that we have our forms ready, we must add procedures to each button. Open up each form and double-click on each button. The form’s buttons can be clicked twice to construct Click methods in the .pas file corresponding to our .fmx for each button. This makes it easier to add an on-click function to each button.

How To Create A Python Quiz Application With DelphiFMX? How the code looks in the IDE.

To ensure that the method is preserved when we save the Python file, add at least one comment (//) after each button Click method. Since we don’t export the run-time implementation using the Delphi4PythonExporter, there is no need to write any run-time implementation code.

How To Create A Python Quiz Application With DelphiFMX? No implementation code.

How to Export this Form as a Python Script?

You can save your project as a Python script by selecting Tools > Export To Python > Export Current Entire Project.

How To Create A Python Quiz Application With DelphiFMX? Exporting the form as a Python script.

Now give your application a title, select the Application Main Form as the MainForm, and, finally, select the directory of choice. Click on Export to generate your files.

How To Create A Python Quiz Application With DelphiFMX? Using the Python exporter

Delphi will generate four Python scripts, Main.py, Quiz.py, Results.py, and PythonQuizApp.py, in your chosen directory. The Main, Quiz, and Results python files contain the classes for the individual forms, and the PythonQuizApp is used to launch our Delphi app. 

Along with the Python files, .pyfmx files are saved in that directory containing all the form’s visual information.

Let’s take a look at the exported PythonQuizApp.py file.

from delphifmx import *
from Main import MainForm

def main():
    Application.Initialize()
    Application.Title = 'PythonQuizApp'
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Next, let’s take a look at the contents of Main.py that will show our start screen:

import os
from delphifmx import *

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Start = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def StartClick(self, Sender):
        pass

Here are the contents of Quiz.py where we will be adding code to show and change questions:

import os
from delphifmx import *

class QuizForm(Form):

    def __init__(self, owner):
        self.QuestionNumberLabel = None
        self.Question = None
        self.OptionA = None
        self.OptionB = None
        self.OptionC = None
        self.OptionD = None
        self.NextQuestion = None
        self.AnswerStatus = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Quiz.pyfmx"))

    def OptionAClick(self, Sender):
        pass

    def OptionBClick(self, Sender):
        pass

    def OptionCClick(self, Sender):
        pass

    def OptionDClick(self, Sender):
        pass

    def NextQuestionClick(self, Sender):
        pass

Notice that the QuizForm constructor does not take in any values. We will get to that later in the tutorial.

Finally, let’s take a look at Results.py, which we will use to display our results:

import os
from delphifmx import *

class ResultsForm(Form):

    def __init__(self, owner):
        self.Score = None
        self.Level = None
        self.ResultLabel = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Results.pyfmx"))

How to Add Functionality To the Quiz App?

Now that our app is ready, we can add logic to our game. 

What Initializations and Imports Have to be Made?

Go to your project folder and open up Main.py.

For our MainForm the only thing we need to do is open up the QuizForm that will display our questions. To do this, first, import the QuizForm class from Quiz.py.

from Quiz import QuizForm

Next, navigate to the StartClick function and create a new variable named self.QuestionWindow will create a new instance of the QuizForm. We then display the new form using the show() method. Our final Main.py looks like this:

import os
from delphifmx import *
from Quiz import QuizForm

class MainForm(Form):

    def __init__(self, owner):
        self.Title = None
        self.Start = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx"))

    def StartClick(self, Sender):
        self.QuestionWindow = QuizForm(self) # Create question 1 window
        self.QuestionWindow.show()

How to Add Main Functionality to All the Buttons in Main Question Form?

Now let’s take a look at our QuizForm that will display our questions. Let’s start by initializing two variables self.Score and self.QuestionNumber that initializes the score and question number of our quiz.

Let’s store these values inside two instance variables in the class constructor:

self.QuestionNumber = 1
        self.Score = 0

Next, let’s define a nested dictionary that contains our questions:

# Dictionary with all of the quiz data
        self.QuizQuestions = {
                                1:{"Question":"Which operator has higher precedence:","Answer":"** (Exponent)", "Options":["> (Comparison)", "** (Exponent)", "& (BitWise AND)", "% (Modulus)"]},
                                2:{"Question":"What is a correct syntax to output 'Hello World' in Python?","Answer":"print('Hello World')", "Options":["print('Hello World')", "print 'Hellow World'", "p('Hello World')", "echo 'Hello World'"]},
                                3:{"Question":"How do you insert comments in Python code?","Answer":"#Comment", "Options":["#Comment", "//Comment", "!Comment", "/*Comment*/"]},
                                4:{"Question":"Which of the following is not a legal variable name","Answer":"python-GUI", "Options":["_pythonGUI", "python_GUI", "pythonGUI", "python-GUI"]},
                                5:{"Question":"What is the correct syntax to output the type of a variable or object in Python?","Answer":"print(type(x))", "Options":["print(type x)", "print(typeOf(x))", "print(type(x))", "print(typeof(x))"]},
                                6:{"Question":"What is the correct way to create a function in Python?","Answer":"def myfunc():", "Options":["create myfunc():", "function myfunc():", "def myfunc():", "func myfunc():"]},
                                7:{"Question":"What is a correct syntax to return the first character in a string?","Answer":"'PythonGUI'[0]", "Options":["'PythonGUI'[0]", "'PythonGUI'[1]", "'PythonGUI'.sub(0,1)", "sub('PythonGUI',0,1)"]},
                                8:{"Question":"Which method can be used to remove any whitespace from both the beginning and the end of a string?","Answer":"strip()", "Options":["len()", "strip()", "split()", "ptrim()"]},
                                9:{"Question":"Which collection is ordered, changeable, and allows duplicate members?","Answer":"List", "Options":["List", "Dictionary", "Set", "Tuple"]},
                                10:{"Question":"Which statement is used to stop a loop?","Answer":"break", "Options":["break", "exit", "return", "stop"]}
                            }

The dictionary contains the QuestionNumber as its key and another dictionary with the question, answer options as a list, and correct answer. We will finally call an __UpdateLabels() function that populates the labels in our form based on the question number. Here is what our __init__ function looks like:

def __init__(self, owner):
        self.QuestionNumberLabel = None
        self.Question = None
        self.OptionA = None
        self.OptionB = None
        self.OptionC = None
        self.OptionD = None
        self.NextQuestion = None
        self.AnswerStatus = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Quiz.pyfmx"))

        self.Score = 0 # Initialize quiz score
        self.QuestionNumber = 1 # Initialize question number

        # Dictionary with all of the quiz data
        self.QuizQuestions = {
            1: {"Question": "Which operator has higher precedence:", "Answer": "** (Exponent)", "Options": ["> (Comparison)", "** (Exponent)", "& (BitWise AND)", "% (Modulus)"]},
            2: {"Question": "What is a correct syntax to output 'Hello World' in Python?", "Answer": "print('Hello World')", "Options": ["print('Hello World')", "print 'Hellow World'", "p('Hello World')", "echo 'Hello World'"]},
            3: {"Question": "How do you insert comments in Python code?", "Answer": "#Comment", "Options": ["#Comment", "//Comment", "!Comment", "/*Comment*/"]},
            4: {"Question": "Which of the following is not a legal variable name", "Answer": "python-GUI", "Options": ["_pythonGUI", "python_GUI", "pythonGUI", "python-GUI"]},
            5: {"Question": "What is the correct syntax to output the type of a variable or object in Python?", "Answer": "print(type(x))", "Options": ["print(type x)", "print(typeOf(x))", "print(type(x))", "print(typeof(x))"]},
            6: {"Question": "What is the correct way to create a function in Python?", "Answer": "def myfunc():", "Options": ["create myfunc():", "function myfunc():", "def myfunc():", "func myfunc():"]},
            7: {"Question": "What is a correct syntax to return the first character in a string?", "Answer": "'PythonGUI'[0]", "Options": ["'PythonGUI'[0]", "'PythonGUI'[1]", "'PythonGUI'.sub(0,1)", "sub('PythonGUI',0,1)"]},
            8: {"Question": "Which method can be used to remove any whitespace from both the beginning and the end of a string?", "Answer": "strip()", "Options": ["len()", "strip()", "split()", "ptrim()"]},
            9: {"Question": "Which collection is ordered, changeable, and allows duplicate members?", "Answer": "List", "Options": ["List", "Dictionary", "Set", "Tuple"]},
            10: {"Question": "Which statement is used to stop a loop?", "Answer": "break", "Options": ["break", "exit", "return", "stop"]}
        }

        self.__UpdateLabels()

Next, we need to create a __UpdateLabels() function that will help us display our question in the Question label and its corresponding answers in the buttons. We access each value of the dictionary using the self.QuestionNumber variable. We then display each value using the .Text property of each object. In addition, we also update the QuestionNumberLabel to display the current question number.

Here is what our final __UpdateLabels() function looks like:

def __UpdateLabels(self):
        # Display options of the current question
        self.OptionA.Text = self.QuizQuestions[self.QuestionNumber]["Options"][0]
        self.OptionB.Text = self.QuizQuestions[self.QuestionNumber]["Options"][1]
        self.OptionC.Text = self.QuizQuestions[self.QuestionNumber]["Options"][2]
        self.OptionD.Text = self.QuizQuestions[self.QuestionNumber]["Options"][3]

        # Display question number
        self.QuestionNumberLabel.Text = str(self.QuestionNumber) + " of 10"

        # Display question text
        self.Question.Text = self.QuizQuestions[self.QuestionNumber]["Question"]

        # Resetting Status
        self.AnswerStatus.Text = ""

Now that we have displayed our questions, we need to check whether the option a user selects is correct. To do this, we can use the click functions. Let’s implement this functionality for OptionA.

Navigate to OptionAClick, and start by checking if a button has already been selected. We will use the AnswerStatus label to check whether there is an option that has already been selected. If an option has already been selected, we will allow no changes:

# Ensure some button not already clicked
        if self.AnswerStatus.Text == "Correct" or self.AnswerStatus.Text == "Incorrect":
            pass

Next, we can check whether the text in the button corresponds to the correct answer to the question. If the correct answer has been selected, we will increment the score and update the AnswerStatus. Otherwise, we will display an Incorrect error message.

# If correct answer chosen then increase score and print correct
        elif self.OptionA.Text == self.QuizQuestions[self.QuestionNumber]["Answer"]:
            self.Score += 1
            self.AnswerStatus.Text = "Correct"
        # If incorrect answer chosen then print incorrect
        else:
            self.AnswerStatus.Text = "Incorrect"

Here is what our final OptionAClick function looks like:

def OptionAClick(self, Sender):
        # Ensure some button not already clicked
        if self.AnswerStatus.Text == "Correct" or self.AnswerStatus.Text == "Incorrect":
            pass
        # If correct answer chosen then increase score and print correct
        elif self.OptionA.Text == self.QuizQuestions[self.QuestionNumber]["Answer"]:
            self.Score += 1
            self.AnswerStatus.Text = "Correct"
        # If incorrect answer chosen then print incorrect
        else:
            self.AnswerStatus.Text = "Incorrect"

We can replicate this step for the other option click functions.

Finally, we need a way to display the next question or to open up the ResultsForm. To do this, we start by importing the ResultsForm from Results.py.

from Results import ResultsForm # import result form to create window

Next, navigate to the NextQuestionClick function. For our app, we will only allow the next question to appear only if the user has answered the current question. To do this, we check the AnswerStatus to see if it has been updated. If the AnswerStatus is empty or shows an error message, we display an error:

# Checking if user has answered a question.
        # User can only proceed to next question if an answer has been selected
        if self.AnswerStatus.Text == "" or self.AnswerStatus.Text == "Select an answer before proceeding!":
            self.AnswerStatus.Text = "Select an answer before proceeding!"

If the user has answered the current question, we increment the self.QuestionNumber by 1. Next, we check whether all ten questions have been answered. If the user has answered all ten questions, we will display the ResultsForm, we will update the questions by calling the __UpdateLabels function.. Here is what our final NextQuestionClick function looks like:

def NextQuestionClick(self, Sender):
        # Checking if user has answered a question.
        # User can only proceed to next question if an answer has been selected
        if self.AnswerStatus.Text == "" or self.AnswerStatus.Text == "Select an answer before proceeding!":
            self.AnswerStatus.Text = "Select an answer before proceeding!"

        else:
            self.QuestionNumber += 1  # Update question number to display the next one
            if self.QuestionNumber <= 10:  # If the ten questions have not been asked
                self.__UpdateLabels()
            else:  # It the ten questions have been asked, show the result form
                self.ResultsWindow = ResultsForm(self, Score=self.Score)
                self.ResultsWindow.show()

Here are the final contents of Quiz.py.

import os
from delphifmx import *
from Results import ResultsForm  # import result form to create window


class QuizForm(Form):

    def __init__(self, owner):
        self.QuestionNumberLabel = None
        self.Question = None
        self.OptionA = None
        self.OptionB = None
        self.OptionC = None
        self.OptionD = None
        self.NextQuestion = None
        self.AnswerStatus = None
        self.LoadProps(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "Quiz.pyfmx"))

        self.Score = 0 # Initialize quiz score
        self.QuestionNumber = 1 # Initialize question number

        # Dictionary with all of the quiz data
        self.QuizQuestions = {
            1: {"Question": "Which operator has higher precedence:", "Answer": "** (Exponent)", "Options": ["> (Comparison)", "** (Exponent)", "& (BitWise AND)", "% (Modulus)"]},
            2: {"Question": "What is a correct syntax to output 'Hello World' in Python?", "Answer": "print('Hello World')", "Options": ["print('Hello World')", "print 'Hellow World'", "p('Hello World')", "echo 'Hello World'"]},
            3: {"Question": "How do you insert comments in Python code?", "Answer": "#Comment", "Options": ["#Comment", "//Comment", "!Comment", "/*Comment*/"]},
            4: {"Question": "Which of the following is not a legal variable name", "Answer": "python-GUI", "Options": ["_pythonGUI", "python_GUI", "pythonGUI", "python-GUI"]},
            5: {"Question": "What is the correct syntax to output the type of a variable or object in Python?", "Answer": "print(type(x))", "Options": ["print(type x)", "print(typeOf(x))", "print(type(x))", "print(typeof(x))"]},
            6: {"Question": "What is the correct way to create a function in Python?", "Answer": "def myfunc():", "Options": ["create myfunc():", "function myfunc():", "def myfunc():", "func myfunc():"]},
            7: {"Question": "What is a correct syntax to return the first character in a string?", "Answer": "'PythonGUI'[0]", "Options": ["'PythonGUI'[0]", "'PythonGUI'[1]", "'PythonGUI'.sub(0,1)", "sub('PythonGUI',0,1)"]},
            8: {"Question": "Which method can be used to remove any whitespace from both the beginning and the end of a string?", "Answer": "strip()", "Options": ["len()", "strip()", "split()", "ptrim()"]},
            9: {"Question": "Which collection is ordered, changeable, and allows duplicate members?", "Answer": "List", "Options": ["List", "Dictionary", "Set", "Tuple"]},
            10: {"Question": "Which statement is used to stop a loop?", "Answer": "break", "Options": ["break", "exit", "return", "stop"]}
        }

        self.__UpdateLabels()

    def OptionAClick(self, Sender):
        # Ensure some button not already clicked
        if self.AnswerStatus.Text == "Correct" or self.AnswerStatus.Text == "Incorrect":
            pass
        # If correct answer chosen then increase score and print correct
        elif self.OptionA.Text == self.QuizQuestions[self.QuestionNumber]["Answer"]:
            self.Score += 1
            self.AnswerStatus.Text = "Correct"
        # If incorrect answer chosen then print incorrect
        else:
            self.AnswerStatus.Text = "Incorrect"

    def OptionBClick(self, Sender):
        # Ensure some button not already clicked
        if self.AnswerStatus.Text == "Correct" or self.AnswerStatus.Text == "Incorrect":
            pass
        # If correct answer chosen then increase score and print correct
        elif self.OptionB.Text == self.QuizQuestions[self.QuestionNumber]["Answer"]:
            self.Score += 1
            self.AnswerStatus.Text = "Correct"
        # If incorrect answer chosen then print incorrect
        else:
            self.AnswerStatus.Text = "Incorrect"

    def OptionCClick(self, Sender):
        # Ensure some button not already clicked
        if self.AnswerStatus.Text == "Correct" or self.AnswerStatus.Text == "Incorrect":
            pass
        # If correct answer chosen then increase score and print correct
        elif self.OptionC.Text == self.QuizQuestions[self.QuestionNumber]["Answer"]:
            self.Score += 1
            self.AnswerStatus.Text = "Correct"
        # If incorrect answer chosen then print incorrect
        else:
            self.AnswerStatus.Text = "Incorrect"

    def OptionDClick(self, Sender):
        # Ensure some button not already clicked
        if self.AnswerStatus.Text == "Correct" or self.AnswerStatus.Text == "Incorrect":
            pass
        # If correct answer chosen then increase score and print correct
        elif self.OptionD.Text == self.QuizQuestions[self.QuestionNumber]["Answer"]:
            self.Score += 1
            self.AnswerStatus.Text = "Correct"
        # If incorrect answer chosen then print incorrect
        else:
            self.AnswerStatus.Text = "Incorrect"

    def NextQuestionClick(self, Sender):
        # Checking if user has answered a question.
        # User can only proceed to next question if an answer has been selected
        if self.AnswerStatus.Text == "" or self.AnswerStatus.Text == "Select an answer before proceeding!":
            self.AnswerStatus.Text = "Select an answer before proceeding!"

        else:
            self.QuestionNumber += 1  # Update question number to display the next one
            if self.QuestionNumber <= 10:  # If the ten questions have not been asked
                self.__UpdateLabels()
            else:  # It the ten questions have been asked, show the result form
                self.ResultsWindow = ResultsForm(self, Score=self.Score)
                self.ResultsWindow.show()

    def __UpdateLabels(self):
        # Display options of the current question
        self.OptionA.Text = self.QuizQuestions[self.QuestionNumber]["Options"][0]
        self.OptionB.Text = self.QuizQuestions[self.QuestionNumber]["Options"][1]
        self.OptionC.Text = self.QuizQuestions[self.QuestionNumber]["Options"][2]
        self.OptionD.Text = self.QuizQuestions[self.QuestionNumber]["Options"][3]

        # Display question number
        self.QuestionNumberLabel.Text = str(self.QuestionNumber) + " of 10"

        # Display question text
        self.Question.Text = self.QuizQuestions[self.QuestionNumber]["Question"]

        # Resetting Status
        self.AnswerStatus.Text = ""

How to Display all Relevant Information on the Results Form?

Now let’s display our final quiz results in the ResultsForm.

Similarly to the QuizForm, our ResultsForm does not take in any additional parameters. Therefore, we will update the __init__ function to take in the final Score:

def __init__(self, owner, Score):

Next, we can display the score by simply using the .Text property of the self.Score label. We also display the level of the user based on their score on the quiz. Here is what our final Results.py looks like:

import os
from delphifmx import *

class ResultsForm(Form):

    def __init__(self, owner, Score):
        self.Score = None
        self.Level = None      
        self.ResultLabel = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Results.pyfmx"))
       
        self.Score.Text = "Score: " + str(Score) # Display score out of ten

        # Display level, based on score
        if Score < 6:
            self.Level.Text += " Novice"
        elif Score < 9:
            self.Level.Text += " Intermediate"
        else:
            self.Level.Text += " Expert"

Now that code is ready, we can run our app by running PythonQuizApp.py. Here is what our app looks like:

How To Create A Python Quiz Application With DelphiFMX? Our example app running as a Python script

How to Build this Quiz App As An Android Application Using Delphi?

Now that we have our PythonQuizApp ready let’s convert this into an Android application.

The Delphi4Python Exporter exports PythonQuizApp with initialization logic for a desktop-based application. Therefore, we will use the PythonFMXBuilder to convert it to an Android app. 

So, open up FMXBuilder and click on Project > New project on the toolbar. Enter the name of the project that you want to build here. Here we define our project as PythonQuizApp.

How To Create A Python Quiz Application With DelphiFMX? Defining the project name.

Before we can add our Python files we need to change some code that will allow us to run our project in Android. Let’s create a new file named PythonQuizApp_Android.py and paste the contents of PythonQuizApp.py.

Next, add your Python files as well as any other supporting project files you used to build your application. Here we will not be adding PythonQuizApp.py as it will only be used to run our desktop application:

How To Create A Python Quiz Application With DelphiFMX? The files.

Now, right-click on PythonQuizApp_Android.py file and set it to the main file. But before we can build an .apk, let’s make some important changes to our code. 

First off, Android applications are initialized automatically by Delphi applications. Because the program will be initialized automatically, we don’t need to initialize it or set a title manually. The Application.MainForm doesn’t need to be initialized either but just needs a variable. Lastly, like initialization, we don’t need to launch or destroy the program because Android handles both tasks.

Here is what our PythonQuizApp_Android.py looks like:

from delphifmx import *
from Main import MainForm

def main():
    Application.MainForm = MainForm(Application)
    Application.MainForm.Show()

if __name__ == '__main__':
    main()

Save the file with the code changes you’ve just made.

You can easily install the app on your mobile device thanks to PythonFMXBuilder by clicking on the Run Project button. We can alternatively also create an .apk file to create an Android application. Click the Build Project button on the toolbar to create your file.

How To Create A Python Quiz Application With DelphiFMX? Building the project.

You will be prompted with a “Build process done” notification in the Messages box once the .apk has been entirely generated.

How To Create A Python Quiz Application With DelphiFMX? The messages window

Your generated file will be in the pathtoPythonFMXBuilderGUIexeFolderappsPythonQuizAppbin folder.

How To Create A Python Quiz Application With DelphiFMX? Where to find the exported APK.

Just copy and paste this .apk file into your phone’s storage. If you access this file from your phone and click on it, you will be prompted with an installation message, which you should proceed with. Then, your PythonQuizApp will be ready for use.

Does the App Work on Your Android Device?

Here is what our Python quiz app looks like on an Android device:

How To Create A Python Quiz Application With DelphiFMX? Our example app running on an Android device.

When we press the start button, we are taken to the next form or the first question.

How To Create A Python Quiz Application With DelphiFMX? Screen 2.

Now, if we select the Next button without selecting any answer, we will not proceed and will get an error prompt.

How To Create A Python Quiz Application With DelphiFMX? Screen 3.

As soon as we select a question, we get to know whether our answer is correct or not.

How To Create A Python Quiz Application With DelphiFMX? Screen 5

Then we can even click Next to move forward.

How To Create A Python Quiz Application With DelphiFMX? Screen 6 the results screen

After attempting the entire quiz, we get an updated score and a level based on the score.

What Are the Key Takeaways From this Tutorial?

How To Create A Python Quiz Application With DelphiFMX? A laptop on a chair with the PyScripter free download page on display

Congratulations on completing this tutorial. We hope it has helped you realize how easy Python GUI development is when using the correct tools.

Developing a Python quiz application with DelphiFMX is a fantastic method to demonstrate your programming prowess and evaluate your language proficiency. DelphiFMX makes it simple to construct cross-platform programs that can operate on various devices thanks to its user-friendly interface and robust functionality. This project is a fun approach to developing your abilities and broadening your knowledge, regardless of whether you are an experienced programmer or just getting started with Python.

After seeing how to use the appropriate Python GUI tools to create Android apps, you’re ready to create apps of your own. So, click here to download Delphi and start making Python-based apps immediately!

What Are the FAQs Regarding This Topic?

How To Create A Python Quiz Application With DelphiFMX? The FAQ page opened on a laptop

What is DelphiFMX?

Using the Delphi programming language, developers can construct cross-platform apps utilizing the DelphiFMX software development environment. In addition to a library of pre-built components for typical programming tasks, it offers a visual designer for developing user interfaces. You can use it to create several applications such as ToDo Apps, TicTacToe Apps, or Currency Converters.

Which programming language was employed in developing the quiz application in this article?

Python was used to develop the article’s quiz application. The popular high-level programming language Python is praised for being straightforward and readable. It is employed in various applications, including artificial intelligence, data analysis, and web building.

What is the purpose of creating a quiz application with DelphiFMX?

The goal of using DelphiFMX to construct a quiz application is to produce a cross-platform quiz application that can be used on both Windows and Android. DelphiFMX is the perfect option for building cross-platform apps since it offers a straightforward method for creating user interfaces that function across several platforms.

What are the features of the quiz application created in this article?

The quiz application created in this article allows users to take quizzes, view their scores, and review their answers. They can reset the quiz if they want to retake it.

Why is PyScripter a popular IDE?

When PyScripter was launched, it was a simple IDE that provided a reliable scripting solution for Delphi programs. It evolved into a complete standalone Python IDE over time. Delphi was used to develop it. Python4Delphi, however, enables the addition of Python programs (P4D). It is lighter than other IDEs because it was created in a compiled language. You can use PyScripter’s project management, file explorer, Python interpreter, and debugger, among other things.

The post How To Create A Python Quiz Application With DelphiFMX? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-python-quiz-application-with-delphifmx/feed/ 0 9883
Understanding The Basics of DelphiFMX and DelphiVCL https://pythongui.org/understanding-the-basics-of-delphifmx-and-delphivcl/ https://pythongui.org/understanding-the-basics-of-delphifmx-and-delphivcl/#respond Wed, 26 Apr 2023 13:16:08 +0000 https://pythongui.org/?p=9957 RAD Studio with Delphi is a powerful Integrated Development Environment (IDE) for creating applications in the Object Pascal programming language. It enables developers to create cross-platform applications with UIs using two libraries: Visual Component Library...

The post Understanding The Basics of DelphiFMX and DelphiVCL first appeared on Python GUI.

]]>
RAD Studio with Delphi is a powerful Integrated Development Environment (IDE) for creating applications in the Object Pascal programming language. It enables developers to create cross-platform applications with UIs using two libraries: Visual Component Library (VCL) and FireMonkey (FMX). This article will go over the fundamentals of DelphiVCL and DelphiFMX and how to install and test these Delphi libraries and use them in your Python apps to create rich user interfaces and add the additional power they bring to your own projects.

What is Delphi For Python?

what-is-delphi-for-python-8577600

DelphiVCL for Python is a Python wrapper around Delphi’s native Windows GUI framework, VCL. VCL is designed for Windows and makes use of native Windows controls. This means that developers can use Python to create Windows desktop applications while still reaping the benefits of the powerful Delphi IDE. DelphiVCL for Python includes many components and controls for creating feature-rich and visually appealing user interfaces for Windows applications.

DelphiFMX for Python, on the other hand, is a binding of the FireMonkey cross-platform GUI framework (FMX). The FMX framework is compatible with the most popular operating systems, including Windows, macOS, iOS, and Android. This means developers can use Python to create cross-platform applications while utilizing the powerful Delphi IDE. In addition, DelphiFMX for Python includes components and controls for creating user interfaces that look and behave consistently across platforms.
While developers can create GUI applications without knowing or installing Delphi, they must install the delphifmx and delphivcl Python packages to use DelphiFMX and DelphiVCL. Much of what developers learn with Delphi for Python will transfer to the other package. Still, there may be some cases where developers prefer the lighter-weight VCL framework when creating Windows applications because it is specifically designed for the Windows platform.

Understanding The Basics of DelphiFMX and DelphiVCL - free ebook

How to install DelphiFMX and DelphiVCL libraries for Python?

Understanding The Basics of DelphiFMX and DelphiVCL - a laptop showing an IDE with our code in it

There are two ways to install the Delphi libraries: using PyPi or downloading the source from GitHub. DelphiFMX and DelphiVCL are available on PyPi and support Python 3.6 through 3.10, including Conda. In addition, DelphiFMX works with various operating systems, including Android32, Android64, Linux64, OSX64, OSXARM64, Win32, and Win64, whereas DelphiVCL is only available for Windows.

The simplest way to install these libraries is through PIP. For DelphiFMX, use this command:

pip install delphifmx
Understanding The Basics of DelphiFMX and DelphiVCL - a screenshot of the Windows terminal window with a person installing the DelphiFMX libraries using Python's Pip

For DelphiVCL, use the command:

pip install delphivcl

Alternatively, download or clone the repository from GitHub and manually install the package. Once the repository has been downloaded or cloned, navigate to the DelphiFMX4Python or DelphiVCL4Python root directory and open the command or Conda prompt with that path. Finally, to install the package, run the following command:

python setup.py install

How can I test if the Installation of DelphiFMX and DelphiVCL in Python was successful?

To see if the delphivcl and delphifmx modules were successfully installed, use the Python REPL and enter the dir() function to look for available names in the local scope. Then, import the installed modules and see if they appear in the dir() function output. To validate the installation, use the dot (.) operator to look for available classes, functions, and objects in the installed modules. An object Application instance is a ready-to-use singleton instance that can be accessed via the dot (.) operator.

Let’s look at this in action using the terminal:

# Enter the Python REPL
$ python
# Check available names in the local scope
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', 
'__package__', '__spec__']
# Import the installed modules
>>> import delphifmx
>>> import delphivcl
# Check available names in the local scope again
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', 
'__package__', '__spec__', 'delphifmx', 'delphivcl']
# Check for available classes, functions, and objects in the modules using the dot operator
>>> delphifmx.Button
<class 'Button'>
>>> delphivcl.Button
<class 'Button'>

In this example, we first entered the Python REPL and used the dir() function to search the local scope for available names. Next, we checked for available names in the local scope again after importing the installed delphifmx and delphivcl modules to confirm that the modules were successfully installed. 

Finally, we used the dot operator to search the modules for available classes, functions, and objects, such as Button. If the modules were not properly installed, the code would throw an ImportError when attempting to import them or an AttributeError when attempting to access non-existent classes, functions, or objects.

How to create a simple app with the DelphiVCL Python libraries?

Understanding The Basics of DelphiFMX and DelphiVCL. A laptop showing someone editing some code.

Let’s now create a simple GUI application. The code for it is:

# Import the delphivcl library
from delphivcl import *

# Initialize the application
Application.Initialize()

# Set the title of the application to "Hello DelphiVCL"
Application.Title = "Hello DelphiVCL"

# Create a new form window
app = Form(Application)

# Set the caption of the form window to "Welcome"
app.SetProps(Caption = "Welcome")

# Show the form window
app.Show()

# Free the console
FreeConsole()

# Run the application
Application.Run()

# Destroy the form window
app.Destroy()
Understanding The Basics of DelphiFMX and DelphiVCL. A plain "welcome" screen.

How to create a simple app with the DelphiFMX Python libraries?

Understanding The Basics of DelphiFMX and DelphiVCL. A laptop with some basic Python initialization code on the screen

We’ve seen an example for DelphiVCL. Now, let’s get you started with the DelphiFMX 

Python package to build GUI applications. For this, let’s create an FMX version of the above-created simplest VCL application using the following code:

# Import the delphifmx library
from delphifmx import *

# Initialize the application
Application.Initialize()

# Set the title of the application to "Hello DelphiFMX"
Application.Title = "Hello DelphiFMX"

# Create a new form window
app = Form(Application)

# Set the caption of the form window to "Welcome"
app.SetProps(Caption = "Welcome")

# Set the main form of the application to the new form window
Application.MainForm = app

# Show the form window
app.Show()

# Run the application
Application.Run()

# Destroy the form window
app.Destroy()

Some differences exist between the DelphiVCL version of the simplest app and this DelphiFMX code. For example, in the DelphiVCL code, the MainForm property is automatically set to the first form created in the application. We need to explicitly call the FreeConsole() function to release the console window’s resources. 

On the other hand, in the DelphiFMX code, we need to set the Application.MainForm to explicitly specify which form should be the main form, and the FreeConsole() function is called automatically in DelphiFMX. These differences in the two frameworks’ handling of creating and managing the user interface and other application resources may influence the choice of framework developers to use based on their requirements and familiarity with the respective frameworks.

Are you ready to make your own GUIs with Delphi and Python?

Understanding The Basics of DelphiFMX and DelphiVCL. A desktop screen with the "Getting started with Python GUI" web page open on it.

DelphiVCL and DelphiFMX are powerful libraries for creating cross-platform applications with rich UIs. DelphiVCL is a standard library containing many pre-built user interface controls for creating desktop applications. DelphiFMX, on the other hand, is a more modern library that enables developers to create user interfaces for mobile and desktop applications from a single codebase. Python developers can easily install Delphi libraries and create simple applications using DelphiVCL and DelphiFMX for Python with the help of this article. It is now up to you to investigate more of Delphi’s capabilities and create user interfaces with Delphi.

Check out our comprehensive ebook, “Getting Started with Python GUI,” to learn more about creating GUIs with Python. This ebook will walk you through the fundamentals of creating user interfaces with Python and Delphi, laying the groundwork for you to build more complex applications. 

Click the link to get your copy today and take your Python programming skills to the next level.

What are some FAQs about DelphiVCL and DelphiFMX?

Understanding The Basics of DelphiFMX and DelphiVCL. A screen showing the FAQ page

What is the difference between DelphiVCL and DelphiFMX?

The VCL library closely encapsulates the Microsoft Windows GUI controls to make it very east to develop powerful Windows desktop applications. In contrast, FMX allows developers to create cross-platform user interfaces for mobile and desktop applications from a single codebase. FMX creates controls using its own graphics technology and custom drawing whereas VCL partially relies on the Windows APIs to render the controls. Both are very powerful. DelphiVCL and DelphiFMX are the Python versions of the VCL and FMX frameworks found in the RAD Studio with Delphi ecosystem.

Can I use DelphiVCL and DelphiFMX together?

Yes, DelphiVCL and DelphiFMX can be used by developers to create hybrid applications that run on both desktop and mobile platforms.

How do I install DelphiVCL and DelphiFMX?

DelphiVCL and DelphiFMX are pre-installed in the Delphi IDE, so developers can use them immediately.

What platforms are supported by DelphiVCL and DelphiFMX?

DelphiVCL is compatible with desktop platforms such as Windows, whereas DelphiFMX is compatible with desktop and mobile platforms such as Android, iOS, and macOS.

What kind of applications can I build with DelphiVCL and DelphiFMX?

Python developers can use DelphiVCL and DelphiFMX to create various applications such as currency converter, employee management systems, to-do apps, guessing games, tic-tac-toe, TUIs, and much more.

Are any resources available to help me learn more about DelphiVCL and DelphiFMX?

Numerous online resources, such as documentation, tutorials, and forums, help developers learn more about DelphiVCL and DelphiFMX and how to use them effectively. The ebook also contains detailed instructions and step-by-step tutorials for DelphiVCL and DelphiFMX.

The post Understanding The Basics of DelphiFMX and DelphiVCL first appeared on Python GUI.

]]>
https://pythongui.org/understanding-the-basics-of-delphifmx-and-delphivcl/feed/ 0 9957
How To Build An Attractive Login And Registration App With PythonGUI? https://pythongui.org/how-to-build-an-attractive-login-and-registration-app-with-pythongui/ https://pythongui.org/how-to-build-an-attractive-login-and-registration-app-with-pythongui/#respond Wed, 12 Apr 2023 13:50:30 +0000 https://pythongui.org/?p=9631 Users can easily use an app they have never seen before if the GUI is well-designed. GUIs provide an attractive design and simple way for users to access technology. They can easily chat with pals,...

The post How To Build An Attractive Login And Registration App With PythonGUI? first appeared on Python GUI.

]]>
Users can easily use an app they have never seen before if the GUI is well-designed. GUIs provide an attractive design and simple way for users to access technology. They can easily chat with pals, make online purchases, and watch popular shows. In this tutorial, we will learn how to use Python and Delphi to create a simple but visually appealing app that allows users to register and log in to a system. So, let’s dive right in!

What is the importance of the GUI in a Login Registration App?

How To Build An Attractive Login And Registration App With PythonGUI? A laptop with the Delphi VCL and FMX libraries for Python download page showing.

Login and registration are required in many apps, just as they are in any website or software. The purpose is to authenticate its users to protect their private content and provide them with a personalized experience.

Regarding human-computer interaction, the GUI is an important component of software application programming, replacing text-based commands with user-friendly actions. Its goal is to provide the user with simple decision points to locate, understand, and apply.

Moreover, the GUI experience for the login and registration screens contributes to whether a user will stick around to use the app or move on. Therefore, it is important that GUI’s are intuitive and interactive, providing users with an appealing interface, promoting a positive experience and impression, that in turn may lead to them continuing to use the app.

How to create a Python GUI for your app with PythonGUI Tools?

How To Build An Attractive Login And Registration App With PythonGUI?  The Edge browser support page.

Let’s create a simple Login and Registration App that will allow our users to Login or Register to the app. The app would serve two basic functions: a login form that checks a user’s credentials against stored credentials in a database and a register form that allows new users to register to our app.

What are the requirements to create the Python GUI for an app?

For this tutorial, you will need:

  • Python
  • PythonFMXBuilder
  • Delphi4PythonExporter
  • Delphi CE
  • PyScripter or any other IDE.

We’ve got you covered if you don’t have these tools installed on your laptop or PC. You can check out this article on Powerful Python GUI Project Setup to get started.

In addition, you will also need a basic understanding of Python and the Python sqlalchemy library to host our database.

You can grab the code for this tutorial from our GitHub repository using the following link: https://github.com/Embarcadero/PythonBlogExamples/tree/main/Login_Registration_App

Now that we have our requirements installed and ready, let’s begin this tutorial by creating our forms.

How to make basic screen forms and layouts in Delphi?

Open up Delphi CE, and under the develop tab, select create a new project. Next, select the Multi-Device application and create a blank application.

How To Build An Attractive Login And Registration App With PythonGUI? Choosing a multi-device application from the new items menu.

If you are not familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.

How To Build An Attractive Login And Registration App With PythonGUI? An image asking you to click to download the PythonGUI ebook.

This will create a new project for you with a blank form. We have named our project as Login_Registration_App. By default, Delphi launches a project with a blank form. We will begin by creating a sign-in form, so we have renamed our form as SignIn.

How To Build An Attractive Login And Registration App With PythonGUI? The UI being designed in the RAD Studio IDE.

Let’s begin by renaming our form, so right click on the form and select QuickEdit. Here we will name our form as SignInForm with the caption SignIn.

How To Build An Attractive Login And Registration App With PythonGUI? The signin form.

Now, let’s add labels to our form. Head to the standard palette and select TLabel.

How To Build An Attractive Login And Registration App With PythonGUI? The project manager screen.

Next, rename the text of each label by right-clicking on that label and selecting Quick Edit.

How To Build An Attractive Login And Registration App With PythonGUI? Using the quick edit function to change the control's properties.

For example, we have named our password label as Password, as this label will only contain the text "Password:".

How To Build An Attractive Login And Registration App With PythonGUI? The plain form.

To log into the app, we will need our users to add their email and password which we will check against entries in our database. So head on over to the standard palette and add some TEdit boxes. These will allow our user to input their details and login credentials to our app. Rename these TEdit labels and give them intuitive names which will help us in our program later. Here we have named our email and password input boxes as EmailText and PasswordText respectively.

How To Build An Attractive Login And Registration App With PythonGUI? The form with added edit boxes.

Moreover, we need to add some buttons to our form. So head to the palette and add some TButtons. We have named our buttons Signin and Signup. The Signin button will allow our user to log in to our application, whereas the Signup button will redirect us to the registration form. In addition to this, we add a small text label named Status right above the Signin button that displays an error if the user uses incorrect login credentials.

Here is what our form looks like:

How To Build An Attractive Login And Registration App With PythonGUI? The form with more work done to it.

Next, we need to create another registration form that will allow a new user to register for our application. So right-click on Login_Registration_App.exe and select Add New > Multi-Device Form.

How To Build An Attractive Login And Registration App With PythonGUI? Choose add new from the context menu.

This will create a new blank form, which we have renamed as SignUp.

Next, we will populate our form with labels, text boxes, and buttons that will help our users log in to our application. We will give them intuitive names as we add elements to the form. Here is what our final registration form looks like:

How To Build An Attractive Login And Registration App With PythonGUI? More work on the UI.

Finally, we need to add some function that will help us add some code to each button. To do this, we need to double-click each button on both of our forms. For example, double-clicking on the Signin button on the SignIn form creates a SigninClick event in the SignIn.pas file that is associated with our SignIn.pas form. The event is triggered each time the button is clicked.

How To Build An Attractive Login And Registration App With PythonGUI? The code behind the UI form.

By default, Delphi cleans up your code to remove redundant or unused functions and procedures. Therefore, in the event method, we must add at least a single comment // in each button click event so that the Delphi IDE will not automatically remove it. This will ensure the method remains when we save the file.

How to export our Python GUI screen as Python Code?

Now that we have our forms ready, it is time that we export our project as Python scripts using Delphi4PythonExporter. To do this, select Tools > Export To Python > Export Current Entire Project on the top menu bar.

How To Build An Attractive Login And Registration App With PythonGUI? Choose export entire project.

In the Project Export menu, select your desired project directory. Next, select the Application Main Form as the SignIn form. Finally, click on Export.

How To Build An Attractive Login And Registration App With PythonGUI? The project export dialog.

This action will generate 3 Python scripts Login_Registration_App.py, SignIn.py, and SignUp.py that contain each function and the functionality of each form in our chosen directory. With this, there are 2 .pyfmx files that contain all the visual information of the forms.

The code in the Login_Registration_App.py is as follows:

from delphifmx import *
from SignIn import SignInForm

def main():
    Application.Initialize()
    Application.Title = 'Login_Registration_App'
    Application.MainForm = SignInForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Next, let’s take a look at the content of the SignIn.py form that will allow our user to sign in:

import os
from delphifmx import *

class SignInForm(Form):

    def __init__(self, owner):
        self.Login = None
        self.Email = None
        self.PasswordText = None
        self.Password = None
        self.Signin = None
        self.EmailText = None
        self.Status = None
        self.Signup = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "SignIn.pyfmx"))

    def SigninClick(self, Sender):
        pass

    def SignupClick(self, Sender):
        pass

Here is are the contents of SignUp.py where we will be adding logic for signing up to our app:

import os
from delphifmx import *

class SignUpForm(Form):

    def __init__(self, owner):
        self.Register = None
        self.FnameText = None
        self.Fname = None
        self.LNameText = None
        self.LName = None
        self.EmailText = None
        self.Email = None
        self.PasswordText = None
        self.Password = None
        self.CPasswordText = None
        self.CPassword = None
        self.Signup = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "SignUp.pyfmx"))

    def SignupClick(self, Sender):
        pass

How to create a database with Python to store user information?

Before we can start creating our functions for our forms, we first need to create a database to store our user information. To do this, we will create a Python script named database.py in the projects folder. Open up the file and import create_engine, MetaData, Table, Column, and VARCHAR from SQLAlchemy:

from sqlalchemy import create_engine, MetaData, Table, Column, VARCHAR

Next, establish a connection or create a database using the create_engine function and specify the name. Here we have named our database users.db.

engine = create_engine(
    'sqlite:///users.db')

In addition, we need to define the format of data in our database. To do this, first, create a MetaData object instance and bind it to the engine:

# initialize the Metadata Object
meta = MetaData(bind=engine)

Next, create a table called users with attributes of different types using the Table function and assign it to a variable:

users = Table(
    'users', meta,
    Column('email', VARCHAR, primary_key=True),
    Column('fname', VARCHAR),
    Column('lname', VARCHAR),
    Column('password', VARCHAR)
)

Finally, execute the query using the create_all method of MetaData:

meta.create_all(engine)

Here is what our final database.py looks like:

# import necessary packages
from sqlalchemy import create_engine, MetaData, Table, Column, VARCHAR

# establish connections - create new file db and connect of connect if it already exists
engine = create_engine(
    'sqlite:///users.db')

# initialize the Metadata Object
meta = MetaData(bind=engine)

# create a table schema
users = Table(
    'users', meta,
    Column('email', VARCHAR, primary_key=True),
    Column('fname', VARCHAR),
    Column('lname', VARCHAR),
    Column('password', VARCHAR)
)

meta.create_all(engine)

Running the script will create a database in our projects directory that we can use to store all the user information.

How To Build An Attractive Login And Registration App With PythonGUI? An Explorer window showing the location of the users database.

How to add the Login and Registration GUI function to our Python App?

Now that we have our forms up and running let’s start adding logic to our code. Let’s begin by modifying our SignIn form and finishing our SigninClick function.

The first thing we will need to do is establish a connection to our database. Open up SignIn.py and import the create_engine and text function from the sqlalchemy library. Next, establish a connection to our users.db by using the create_engine function:

from sqlalchemy import create_engine, text

# establish connections - create new file db and connect of connect if it already exists
engine = create_engine(
    'sqlite:///users.db')

Next, we check is whether the email or password entries are empty. Navigate to the SigninClick function and check the EmailText and PasswordText boxes using the .Text property. We can then display the error on our Status label if either text box is empty:

if self.EmailText.Text == "" or self.PasswordText.Text == "":
            self.Status.Text = "Incomplete details"

Now, if the user enters some email or password, we need to check it against all of the entries in our database. To do this, we write an SQL query using the text function, run the query, commit the changes, fetch all instances using engine.execute(sql).fetch_all(), and finally check the results to see if there was a matching found in the database. We write a message to the Status label, whether the details were found in the database.

else:
            # write the SQL query inside the text() block
            sql = text("SELECT * FROM users WHERE users.email='{}' AND users.password='{}'".format(self.EmailText.Text, self.PasswordText.Text))
            result = engine.execute(sql).fetchall()
            print(result)
            if len(result) == 0:
                self.Status.Text = "Incorrect or invalid login details"
            else:
                Fname = result[0][1]
                self.Status.Text = "Successful login. Welcome {}".format(Fname)

Here is what our function SigninClick function looks like:

def SigninClick(self, Sender):
        if self.EmailText.Text == "" or self.PasswordText.Text == "":
            self.Status.Text = "Incomplete details"
        else:
            # write the SQL query inside the text() block
            sql = text("SELECT * FROM users WHERE users.email='{}' AND users.password='{}'".format(self.EmailText.Text, self.PasswordText.Text))
            result = engine.execute(sql).fetchall()
            print(result)
            if len(result) == 0:
                self.Status.Text = "Incorrect or invalid login details"
            else:
                Fname = result[0][1]
                self.Status.Text = "Successful login. Welcome {}".format(Fname)

To finish our SignIn form, we need to write the logic for our SignupClick function. The function should open the SignUp form whenever the Signup button is clicked. To do this, we first import the form SignUp form from SignUp.py:

from SignUp import SignUpForm

Next, we create a new instance of the SignUpForm and assign it to a new variable named signup_form. We then use the Show() method to display the new form.. Here is our final SignupClick function:

def SignupClick(self, Sender):
        signup_form = SignUpForm(self)
        signup_form.Show()
        #self.Show()

Let’s finish up our SignUp form. First, open up SignUp.py, import create_engine from sql_alchemy, and create a database engine using the create_engine function. If a database is already created create_engine creates a new database with the supplied name. Otherwise, it establishes a connection to an existing database. In this case, we have named our database as users.db.

from sqlalchemy import create_engine

# establish connections - create new file db and connect of connect if it already exists
engine = create_engine(
    'sqlite:///users.db')

Before completing our SignUpClick function, we need to create an owner for our form that will allow us to navigate back to our main form. To do this navigate to the __init__ function and create a new variable named self.owner. Now simply assign the owner parameter to this new variable. Here is what our new __init__ function looks like:

def __init__(self, owner):
        self.Register = None
        self.FnameText = None
        self.Fname = None
        self.LNameText = None
        self.LName = None
        self.EmailText = None
        self.Email = None
        self.PasswordText = None
        self.Password = None
        self.CPasswordText = None
        self.CPassword = None
        self.Signup = None
        self.Status = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "SignUp.pyfmx"))
        self.owner = owner

Next, we check whether any of the text boxes are empty. We do this by checking the .Text property of the TEdit boxes. If a text box is empty, we display an error:

if self.FnameText.Text == "" or self.LNameText.Text == "" or self.EmailText.Text == "" or self.PasswordText.Text == "" or self.CPasswordText.Text == "":
            self.Status.Text = "Incomplete details!"

The next thing to check is if the password and the confirm password fields match:

elif self.CPasswordText.Text != self.PasswordText.Text:
            self.Status.Text = "Passwords do not match!"

Finally, if all text fields are filled, we can simply remove the text from each label and use an INSERT query to add the user to the existing database. We then display a “Successful SignUp” message in the SignInForm using the Status label, and destroy the current form:

else:            
            query = "INSERT INTO users VALUES ('{}', '{}','{}', '{}')".format(self.EmailText.Text, self.FnameText.Text, self.LNameText.Text, self.PasswordText.Text)

            # execute the insert record statement
            engine.execute(query)

            self.owner.Status.Text = "Successful SignUp. Login Now!!"
            self.Destroy()
            #self.owner.Show()

Here is our final SignupClick function:

def SignupClick(self, Sender):
        if self.FnameText.Text == "" or self.LNameText.Text == "" or self.EmailText.Text == "" or self.PasswordText.Text == "" or self.CPasswordText.Text == "":
            self.Status.Text = "Incomplete details!"
        elif self.CPasswordText.Text != self.PasswordText.Text:
            self.Status.Text = "Passwords do not match!"
        else:
            query = "INSERT INTO users VALUES ('{}', '{}','{}', '{}')".format(self.EmailText.Text, self.FnameText.Text, self.LNameText.Text, self.PasswordText.Text)

            # execute the insert record statement
            engine.execute(query)

            self.owner.Status.Text = "Successful SignUp. Login Now!!"
            self.Destroy()
            #self.owner.Show()

How to make a Python app GUI look more appealing?

Now that everything is ready, let’s make our app more appealing by making changes to the FMX code in the .pyfmx files. Let’s start by improving our SignIn form. Let us begin by fixing the caption to our form. Open up SignIn.pyfmx, and navigate to the Caption property. Here you can see that our Caption has been defined as 'Form3'. We can change this by simply renaming our form to SignIn.

How To Build An Attractive Login And Registration App With PythonGUI? Changing the caption field.

Next, let’s add some background color to our form. You can do this by defining a color Fill.Color property inside the form. In addition, you will also have to specify the type of color that you are adding in HEX as ARGB where A defines the opacity of your color. Moreover, we need to define the type of color we want, which can be a gradient or solid color. Here we are defining it to be a solid color using the Fill.Kind property:

How To Build An Attractive Login And Registration App With PythonGUI? Changing the fill properties.

Let’s now change the "LogIn" label of our form. To do this, navigate to the Login object.

How To Build An Attractive Login And Registration App With PythonGUI? The label control's properties in text form.

Add a property named TextSettings.Font.Family and set it to “Rockwell“. Next, check out the TextSettings.Font.Size property and size it accordingly. We have defined it to be 26pt. Finally, align the label to the center by changing the TextSettings.HorzAlign to Center. This will help us center our label. Here is what the final object label looks like:

How To Build An Attractive Login And Registration App With PythonGUI? Selecting the font family.

If your Login label still isn’t centered, chances are that your label isn’t wide enough to align itself to the center of your form automatically. You can easily overcome this by setting the Size.Width property of the Login label to the width of your form (306pt in our case).

Now, let’s change the font of all our other objects and labels; we can do this by first adding style settings to our objects. For example, let’s take a look at the Email label.

How To Build An Attractive Login And Registration App With PythonGUI? The email label.

As you can see, there is no style defined for our label. Therefore, to add any format to the label or any other object, we add StyledSettings property and define it as Size, Style, and FontColor. We then proceed to change the font by adding TextSettings.Font.Family = 'Rockwell' to the objects in our form. Here is what our object looks like:

How To Build An Attractive Login And Registration App With PythonGUI? Updating the styled settings and font family.

Note that we have added two additional style settings, namely FontColor, and Size, which we have not defined. These settings will allow you to use TextSettings.FontColor property and TextSettings.Font.Size to define the color and size of your text. We can similarly define the same settings for different labels and buttons in our app. This helps us style our app according to our needs. Running the Login_Registation_App.py we can see what our final form looks like:

How To Build An Attractive Login And Registration App With PythonGUI? A preview of the running login screen.

Similarly, we can define different properties of the SignUp form. Here is what our final registration form looks like:

How To Build An Attractive Login And Registration App With PythonGUI? The register screen.

How to test our SignIn-SignUp Python App?

So now that we have completed working on the functionality and visuals of the app, let’s go ahead and test everything out. As expected, when we run the file Login_Registration_App.py, the SignIn form appears. Now if we try to sign in without adding the required details, we get a warning:

How To Build An Attractive Login And Registration App With PythonGUI? Showing an error.

If we fill out the details but are incorrect, meaning the user is not stored in the users.db database, then we get another message:

How To Build An Attractive Login And Registration App With PythonGUI? Showing invalid credentials.

So let’s sign up by clicking on the signup button and filling out the SignUp form details:

How To Build An Attractive Login And Registration App With PythonGUI? The login screen in a non error state.

Submitting the form will open up the SignIn form with the success message:

How To Build An Attractive Login And Registration App With PythonGUI? Showing success feedback.

Note that if we had not filled all the required fields, then we would have gotten an error message as we did in the SignIn form.

After a successful signup, when we add the user credentials just registered, we are successfully signed in, and the user gets a greeting with her first name acquired from the database:

How To Build An Attractive Login And Registration App With PythonGUI? Logn screen showing a welcome message.

So the app works just as expected and looks impressive too!

Are you ready to create beautiful Python GUI apps with Delphi?

How To Build An Attractive Login And Registration App With PythonGUI?  A tiny tiny tiny laptop or someone with huge hands editing code in the IDE.

Today, you have learned a lot about Python GUIs. A graphical user interface significantly boosts usability for the typical individual. GUI apps are self-descriptive, provide rapid feedback, and use visual cues to stimulate and direct discoverability. A combination of tools, such as DelphiFMX, DelphiCE, PyScripter, and Delphi4PythonExporter, allows users to create simple, attractive, and powerful apps in just a few steps. 

DelphiFMX from Embarcadero is the ideal feature set for creating visually appealing user interfaces. It is relatively simple and supports several systems, including Windows, macOS, and Linux. The bulk of Python GUIs is considered difficult to use by rookie developers due to a lack of suitable functionality. DelphiFMX addresses these issues by enabling the creation of visually attractive GUIs.

Now that you’ve seen how the correct set of Python GUI tools can be used to create the most stunning applications, go ahead and install Delphi to get started right away!

What are the FAQs regarding building an attractive GUI for a Python app?

How To Build An Attractive Login And Registration App With PythonGUI? A laptop showing the PythonGUI Frequently Asked Questions FAQ screen.

What is P4D?

Python for Delphi (P4D) is a free set of components that integrates the Python DLL into Delphi. They simplify the execution of Python programs and the creation of new Python modules and types. Python extensions, among other things, can be created as DLLs.

What is Delphi CE?

Embarcadero Delphi Community Edition is an excellent starting point for creating visually appealing, high-performance native Delphi apps for Windows, macOS, iOS, and Android. Delphi Community Edition includes a streamlined IDE, code editor, integrated debugger, award-winning visual designers to speed development, powerful data access components, and data binding technologies, hundreds of visual components, and a commercial use licence with a limited commercial use license.

What is DelphiFMX?

DelphiFMX from Embarcadero is the ideal feature set for creating visually appealing user interfaces. It is relatively simple to use and supports several systems, including Windows, macOS, and Linux. The bulk of Python GUIs is considered difficult to use by inexperienced developers due to a lack of suitable functionality. DelphiFMX addresses these issues by enabling the creation of visually attractive GUIs. DelphiFMX eliminates compatibility concerns by including Stencils for FireMonkey, which enable the development of multi-build device apps. DelphiFMX is an excellent choice for creating visually appealing GUIs.

What is Delphi4PythonExporter?

Delphi4PythonExporter is an essential component of a healthy Python and Delphi environment. By exploiting Delphi’s flagship UI design tools, Python developers can save time writing design code in Python. They may use a WYSIWYG preview, including styles, as you design.

Furthermore, users can use the features throughout the design phase to connect event methods to various events on the GUI application. Finally, Pythoneers can use these techniques to scale their large-scale Python GUI applications.

What is a multi-device application?

A multi-device application can run on any platform that RAD Studio supports; multi-device apps are not limited to desktop or mobile platforms. FireMonkey and RTL, two of RAD Studio’s three main libraries, are used in multi-device applications.

The post How To Build An Attractive Login And Registration App With PythonGUI? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-build-an-attractive-login-and-registration-app-with-pythongui/feed/ 0 9631
Unlock the Power of Python for Deep Learning with Convolutional Neural Networks https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-convolutional-neural-networks/ https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-convolutional-neural-networks/#respond Wed, 05 Apr 2023 15:36:55 +0000 https://pythongui.org/?p=10141 Deep learning algorithms work with almost any kind of data and require large amounts of computing power and information to solve complicated issues. Now, let us, deep-dive, into one of the most famous deep learning...

The post Unlock the Power of Python for Deep Learning with Convolutional Neural Networks first appeared on Python GUI.

]]>
Deep learning algorithms work with almost any kind of data and require large amounts of computing power and information to solve complicated issues. Now, let us, deep-dive, into one of the most famous deep learning algorithms: Convolutional Neural Network (CNN).

If you are looking for unsupervised learning algorithms, read our article about it here:

What is Deep Learning?

Deep learning is a subfield of machine learning in which artificial neural networks are used to analyze and solve complex problems. Deep learning neural networks are built with multiple layers of interconnected nodes that can learn and extract features from input data. Deep learning models are trained on large datasets, allowing them to detect patterns and correlations in data that a human would find difficult or impossible to detect.

Deep learning has brought about a significant transformation in the area of artificial intelligence, paving the way for the creation of intelligent systems capable of independent learning, adaptation, and decision-making. Various applications such as image and speech recognition, natural language processing, and autonomous driving have witnessed remarkable achievements through the use of these models.

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Multiple layers of abstraction in deep learning
Representing images on multiple layers of abstraction in deep learning. Image source: Reference [3].

Why Python for Deep Learning?

Python has gained widespread popularity as a programming language due to its versatility and ease of use in diverse domains of computer science, especially in the field of deep learning. Thanks to its extensive range of libraries and frameworks specially tailored for deep learning, Python has emerged as a top choice among many machine learning professionals.

Python has emerged as the language of choice for deep learning, and here are some of the reasons why:

1. Simple to learn and use: 

Python is a high-level programming language that is easy to learn and use, even for those who are new to programming. Its concise and uncomplicated syntax makes it easy to write and understand. This allows developers to concentrate on solving problems without worrying about the details of the language.

2. Abundant libraries and frameworks: 

Python has a vast ecosystem of libraries and frameworks that cater specifically to deep learning. Some of these libraries include TensorFlow, PyTorch, Keras, and Theano. These libraries provide pre-built functions and modules that simplify the development process, reducing the need to write complex code from scratch.

3. Strong community support: 

Python has a large and active community of developers contributing to its development, maintenance, and improvement. This community offers support and guidance to beginners, making it easier to learn and use Python for deep learning.

4. Platform independence: 

Python is platform-independent, which means that code written on one platform can be easily executed on another platform without any modification. This makes it easier to deploy deep learning models on different platforms and devices.

5. Easy integration with other languages: 

Python can be easily integrated with other programming languages, such as Delphi, C++, and Java, making it ideal for building complex systems that require integrating different technologies.

Overall, Python’s ease of use, an abundance of libraries and frameworks, strong community support, platform independence, and ease of integration with other languages make it an indispensable tool for machine learning practitioners. Its popularity continues to soar as a result.

What is Convolutional Neural Network (CNN)?

Convolutional Neural Networks (CNNs – not to be confused with the US news channel of the same name) are specialized artificial neural networks designed for processing and analyzing images and other multidimensional data. CNNs consist of multiple layers of interconnected nodes, each performing a specific task, such as feature extraction, classification, or prediction. Yann LeCun developed the first CNN in 1988 when it was called LeNet. It was used for recognizing characters like ZIP codes and digits.

One of the key features of CNNs is the use of convolutional layers, which employ a mathematical operation known as convolution to filter and extract features from the input data. This allows CNNs to learn and recognize patterns and features in images with greater accuracy and efficiency than traditional machine learning algorithms.

Below is an example of an image processed via CNN:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning convolutional neural network example
Convolutional Neural Network to identify the image of a bird. Source: Reference [1].

CNNs have shown remarkable success in a wide range of applications, including image classification, object recognition, face detection, and natural language processing. The ability of CNNs to learn and extract complex features from images has led to breakthroughs in many fields, such as medical imaging, autonomous driving, and robotics. Moreover, CNNs have proven to be highly effective in solving many real-world problems, such as identifying fraudulent transactions in finance or detecting defects in manufacturing processes.

The architecture and design of CNNs are still evolving, and researchers continue to explore new ways to optimize their performance and improve their capabilities. Recent advancements in CNNs include techniques such as transfer learning, which allows pre-trained CNN models to be adapted to new tasks, and ensemble methods, which combine multiple CNN models to achieve even greater accuracy and robustness. As deep learning continues to advance, CNNs are likely to remain a critical tool for processing and analyzing complex data, particularly in image and signal processing.

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning lenet vs alexnet
Comparison of the LeNet and AlexNet convolution, pooling and dense layers. Source: Reference [2].

Prerequisites for performing CNNs with Python

To perform CNNs with Python, you need to have some prerequisites in terms of programming knowledge, tools, and libraries. The following are some of the prerequisites for performing CNNs with Python:

1. Python programming

You should understand Python programming concepts well, including data types, control structures, functions, and object-oriented programming (OOP) concepts. You should also be comfortable with using Python libraries and packages.

2. NumPy

NumPy is a Python library for numerical computing, which is essential for performing mathematical operations involved in deep learning. It supports multi-dimensional arrays, linear algebra, and other mathematical functions used in machine learning.

Our past article about Python GUI for NumPy

3. matplotlib

Matplotlib is a Python library for data visualization, which is useful for visualizing the data used in training and evaluating CNNs. It provides a wide range of visualization tools, including line plots, scatter plots, histograms, and heatmaps.

Our past article about Python GUI for matplotlib

4. Keras

Keras provides a user-friendly interface for building and training deep learning models, including CNNs.

Our past article about Python GUI for Keras:

Demo video:

5. TensorFlow

TensorFlow is a more flexible and scalable framework that can be used to build and deploy more complex deep learning models.

Our past article about Python GUI for TensorFlow:

Demo video:

6. Image data

To train and test CNNs, you will need a dataset of images in the required format. The images should be labeled or annotated for classification, object detection, or segmentation tasks.

7. GPU hardware (optional, depend on your tasks)

Deep learning models require a lot of computing power, and training CNNs on large datasets can take a long time on a CPU. To speed up the training process, you can use a GPU (Graphics Processing Unit) to accelerate the computations.

In summary, to perform CNNs with Python, you should understand Python programming, NumPy, and Matplotlib. You should also be familiar with deep learning frameworks such as Keras or TensorFlow, have access to image data, and have access to GPU hardware to accelerate the training process.

How do I build and train a Convolutional Neural Network from scratch?

Finally, what we are already waiting for, is the hands-on section to build and train your own CNN from scratch. 

The following is the code example for CNN:

# Load the data: Fashion MNIST dataset
from keras.datasets import fashion_mnist
(train_X,train_Y), (test_X,test_Y) = fashion_mnist.load_data()

# Analyze the data
import numpy as np
from keras.utils import to_categorical
import matplotlib.pyplot as plt
print('Training data shape : ', train_X.shape, train_Y.shape)
print('Testing data shape : ', test_X.shape, test_Y.shape)
## Find the unique numbers from the train labels
classes = np.unique(train_Y)
nClasses = len(classes)
print('Total number of outputs : ', nClasses)
print('Output classes : ', classes)
## Take a look at what the images in your dataset
plt.figure(figsize=[5,5])
## Display the first image in training data
plt.subplot(121)
plt.imshow(train_X[0,:,:], cmap='gray')
plt.title("Ground Truth : {}".format(train_Y[0]))
## Display the first image in testing data
plt.subplot(122)
plt.imshow(test_X[0,:,:], cmap='gray')
plt.title("Ground Truth : {}".format(test_Y[0]))
plt.show()

# Data preprocessing
## Convert each 28 x 28 image of the train and test set into a matrix of size 28 x 28 x 1 which is fed into the network
train_X = train_X.reshape(-1, 28,28, 1)
test_X = test_X.reshape(-1, 28,28, 1)
print((train_X.shape), (test_X.shape))
## Convert data from int8 to float32 format, and rescale pixel values in range 0-1
train_X = train_X.astype('float32')
test_X = test_X.astype('float32')
train_X = train_X / 255.
test_X = test_X / 255.
## Convert the class labels from categorical into a one-hot encoding vector
train_Y_one_hot = to_categorical(train_Y)
test_Y_one_hot = to_categorical(test_Y)
### Display the change for category label using one-hot encoding
print('Original label:', train_Y[0])
print('After conversion to one-hot:', train_Y_one_hot[0])
## Split train (80%) & test data (20%)
from sklearn.model_selection import train_test_split
train_X,valid_X,train_label,valid_label = train_test_split(train_X, train_Y_one_hot, test_size=0.2, random_state=13)
print((train_X.shape), (valid_X.shape), (train_label.shape), (valid_label.shape))

# Model the data
import keras
from keras.models import Sequential,Input,Model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import LeakyReLU
## Set 64 batch size for minimum memory power
batch_size = 64
epochs = 20
num_classes = 10

# NN architecture
fashion_model = Sequential()
fashion_model.add(Conv2D(32, kernel_size=(3, 3),activation='linear',input_shape=(28,28,1),padding='same'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D((2, 2),padding='same'))
fashion_model.add(Conv2D(64, (3, 3), activation='linear',padding='same'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
fashion_model.add(Conv2D(128, (3, 3), activation='linear',padding='same'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
fashion_model.add(Flatten())
fashion_model.add(Dense(128, activation='linear'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(Dense(num_classes, activation='softmax'))

# Compile the model
fashion_model.compile(loss=keras.losses.categorical_crossentropy,
                      optimizer=keras.optimizers.Adam(),
                      metrics=['accuracy'])
print(fashion_model.summary())

# Train the model
fashion_train = fashion_model.fit(train_X, train_label, batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(valid_X, valid_label))

# Evaluate model on the test set
test_eval = fashion_model.evaluate(test_X, test_Y_one_hot, verbose=0)
print('Test loss:', test_eval[0])
print('Test accuracy:', test_eval[1])
## Plot the accuracy and loss plots between training and validation data
accuracy = fashion_train.history['accuracy']
val_accuracy = fashion_train.history['val_accuracy']
loss = fashion_train.history['loss']
val_loss = fashion_train.history['val_loss']
epochs = range(len(accuracy))
plt.plot(epochs, accuracy, 'bo', label='Training accuracy')
plt.plot(epochs, val_accuracy, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()

# Add a dropout layer to overcome the problem of overfitting
batch_size = 64
epochs = 20
num_classes = 10
## NN architecture
fashion_model = Sequential()
fashion_model.add(Conv2D(32, kernel_size=(3, 3),activation='linear',padding='same',input_shape=(28,28,1)))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D((2, 2),padding='same'))
fashion_model.add(Dropout(0.25))
fashion_model.add(Conv2D(64, (3, 3), activation='linear',padding='same'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
fashion_model.add(Dropout(0.25))
fashion_model.add(Conv2D(128, (3, 3), activation='linear',padding='same'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
fashion_model.add(Dropout(0.4))
fashion_model.add(Flatten())
fashion_model.add(Dense(128, activation='linear'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(Dropout(0.3))
fashion_model.add(Dense(num_classes, activation='softmax'))
## Model summary
fashion_model.summary()
## Compile model
fashion_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(),metrics=['accuracy'])
## Train drop out
fashion_train_dropout = fashion_model.fit(train_X, train_label, batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(valid_X, valid_label))
## Save model
fashion_model.save("fashion_model_dropout.h5py")

# Evaluate your model on the test set
test_eval = fashion_model.evaluate(test_X, test_Y_one_hot, verbose=1)
print('Test loss:', test_eval[0])
print('Test accuracy:', test_eval[1])
## Plot the accuracy and loss plots between training and validation data for the one last time
accuracy = fashion_train_dropout.history['accuracy']
val_accuracy = fashion_train_dropout.history['val_accuracy']
loss = fashion_train_dropout.history['loss']
val_loss = fashion_train_dropout.history['val_loss']
epochs = range(len(accuracy))
plt.plot(epochs, accuracy, 'bo', label='Training accuracy')
plt.plot(epochs, val_accuracy, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()

# Predict Labels
predicted_classes = fashion_model.predict(test_X)
predicted_classes = np.argmax(np.round(predicted_classes),axis=1)
predicted_classes.shape, test_Y.shape
## Show examples of correct labels
correct = np.where(predicted_classes==test_Y)[0]
print("Found %d correct labels" % len(correct))
for i, correct in enumerate(correct[:9]):
    plt.subplot(3,3,i+1)
    plt.imshow(test_X[correct].reshape(28,28), cmap='gray', interpolation='none')
    plt.title("Predicted {}, Class {}".format(predicted_classes[correct], test_Y[correct]))
    plt.tight_layout()
plt.show()
## Show examples of incorrect labels
incorrect = np.where(predicted_classes!=test_Y)[0]
print("Found %d incorrect labels" % len(incorrect))
for i, incorrect in enumerate(incorrect[:9]):
    plt.subplot(3,3,i+1)
    plt.imshow(test_X[incorrect].reshape(28,28), cmap='gray', interpolation='none')
    plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], test_Y[incorrect]))
plt.tight_layout()
plt.show()

# Classification report
from sklearn.metrics import classification_report
target_names = ["Class {}".format(i) for i in range(num_classes)]
print(classification_report(test_Y, predicted_classes, target_names=target_names))

The code above does the following operations (for more details, read the comments inside the code snippet):

1. Introduce you to convolutional neural networks with Keras.

2. Load, explore, and analyze the data.

3. Preprocess your data

You’ll resize, rescale, and convert your labels into one-hot encoding vectors and split up your data in training and validation sets.

4. Construct the neural network model

You’ll model the data and form the network. You’ll compile, train and evaluate the model, visualizing the accuracy and loss plots.

5. Learn about the concept of overfitting and how you can overcome it by adding a dropout layer.

6. Revisit your original model and re-train the model. You’ll also re-evaluate your new model and compare the results of both models.

7. Make predictions on the test data, convert the probabilities into class labels, and plot a few test samples that your model correctly classified and incorrectly classified.

8. Finally, visualize the classification report, which will give you more in-depth intuition about which class was (in)correctly classified by your model.

Let’s run the above code using PyScripter IDE. And the following are some selected outputs:

1. Take a look at the images in your dataset:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 01

2. Model summary:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 02

3. Train the model:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 03

4. Plot the accuracy and loss plots between training and validation data:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 04

5. Plot the accuracy and loss plots between training and validation data after adding the Dropout layer to our model:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 05

6. Show correct labels:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 06

7. Show incorrect labels:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 07

8. Classification report:

Unlock the Power of Python for Deep Learning with Convolutional Neural Networks. Deep learning on pyscripter 08

Congratulations, now you have learned how to build and train a Convolutional Neural Network (CNN) from scratch and successfully run it inside PyScripter IDE with high speed & performance.

Visit our other AI-related articles here:


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL, which makes creating Windows GUIs with Python simple.


References & further readings

[1] Biswal, A. (2023).

Top 10 Deep Learning Algorithms You Should Know in 2023. Simplilearn. simplilearn.com/tutorials/deep-learning-tutorial/deep-learning-algorithm

[2] Cmglee. (2021).

Comparison of the LeNet and AlexNet convolution, pooling and dense layers. Wikimedia. en.wikipedia.org/wiki/Convolutional_neural_network #/media/File:Comparison_image_neural_networks .svg

[3] Schulz, H., & Behnke, S. (2012).

Deep learning: Layer-wise learning of feature hierarchies. KI-Künstliche Intelligenz, 26, 357-363.

[4] Sharma, A. (2017).

Convolutional Neural Networks in Python with Keras. DataCamp Blog. datacamp.com/tutorial/convolutional-neural-networks-python

[5] Zhang, A., Lipton, Z. C., Li, M., & Smola, A. J. (2021).

Dive into deep learning. arXiv preprint arXiv:2106.11342.

The post Unlock the Power of Python for Deep Learning with Convolutional Neural Networks first appeared on Python GUI.

]]>
https://pythongui.org/unlock-the-power-of-python-for-deep-learning-with-convolutional-neural-networks/feed/ 0 10141
How To Start Python GUI Development With Delphi? https://pythongui.org/how-to-start-python-gui-development-with-delphi/ https://pythongui.org/how-to-start-python-gui-development-with-delphi/#respond Wed, 29 Mar 2023 20:14:30 +0000 https://pythongui.org/?p=9935 Python is a popular and versatile programming language, and GUI development in Python is in high demand. However, developing GUI applications, particularly cross-platform ones, can be difficult. Delphi is a powerful programming language used for...

The post How To Start Python GUI Development With Delphi? first appeared on Python GUI.

]]>
Python is a popular and versatile programming language, and GUI development in Python is in high demand. However, developing GUI applications, particularly cross-platform ones, can be difficult. Delphi is a powerful programming language used for GUI development since the 1990s. In this article, we will look at how to get started with Python GUI development with Delphi and how to use the powerful features of both languages to create powerful and intuitive GUI applications.

How can we compare Delphi’s DNA to the Zen of Python?

How To Start Python GUI Development With Delphi? Python vs Delphi DNA.

Python and Delphi share several design principles that guide the evolution of their respective programming languages. The Zen of Python, a collection of guiding principles for the Python programming language, also emphasizes simplicity, readability, and explicitness. Delphi places a premium on developer productivity, providing a suite of tools and components that make it simple to build powerful applications.

Both languages prioritize developer accessibility through simple visual designers or clear and concise code. In this article, we’ll look at the similarities and differences between Delphi and Python design philosophies and how they affect application development in both languages.

3-9131178

What are the differences between Delphi and Python?

The first distinction is that while Delphi has a free community edition, Python is open-source. The second distinction is that Python employs garbage collection with reference counting and cycle detection. In contrast, Delphi employs manual memory management with an ownership model that simplifies it in most cases. 
Third, regarding how the languages work, Delphi is primarily a compiled language, whereas Python is an interpreted language with some compiling options. Finally, while Delphi is commonly used to develop business-to-business software or internal IT development, Python has become a general-purpose language. Still, it is used for machine learning research and prototyping.

Which levels of development are home to Delphi and Python?

How To Start Python GUI Development With Delphi? Unleash the power of your dreams.
How To Start Python GUI Development With Delphi? A low code comparison graphic.

Delphi or Python development can be classified into low code, standard and third-party libraries, and raw memory access. 

At low level, Delphi provides many visual low-code tools that allow developers to focus on productivity rather than writing code, but there are limitations to what can be accomplished. The second level involves using common libraries and creating programs, which allows for greater customization. Finally, the third level is the most versatile, powerful, and least productive because it requires dealing with raw memory and pointers via assembly language code.

Delphi effectively combines all three levels of development. Conversely, Python falls primarily into the middle level, with numerous built-in and third-party libraries. Python has garbage collectors that collect garbage automatically, whereas Delphi handles garbage manually. Python also supports the creation of extension modules in C, which provides raw memory management and broadens its reach to include low-level platform access.

Python’s ability to import extension modules as libraries make it extremely productive at the middle level of development, and include Python extension modules written in Delphi.

Which libraries does Delphi offer?

How To Start Python GUI Development With Delphi? A laptop showing the Delphi FMX and VCL Python library downloads,
How To Start Python GUI Development With Delphi? The Delphi and Python ecosystem explained.

Python for Delphi bridge has capability to offer two rich and mature GUI frameworks for graphical user interface (GUI) application development to Python as extension modules:

What is VCL’s technology stack? 

The VCL (Visual Component Library) is a technology stack based on Windows components, including message interception handles. VCL simplifies the use of Windows components by adding a layer of abstraction, removing the need for developers to think about handles, messages, and other details. VCL is designed for Windows-based development and is built with the component model for component reuse.

What is the FMX’s technology stack?

FireMonkey is a cross-platform graphical user interface framework that was released in 2011. It was built from the ground up to be hardware accelerated, utilizing GPUs via DirectX on Windows and OpenGL on other platforms. FireMonkey includes platform services that aid in abstraction when transferring between platforms. It is compatible with Windows, Mac, iOS, Android, and Linux. It adapts automatically to the platform you’re using, with the UI’s behaviors, looks, and feels changing accordingly.

What are the final thoughts on how to Start Python GUI development with Delphi?

How To Start Python GUI Development With Delphi? A woman looking at  computer screen which is dislaying the "Getting started with Python GUI" web page.

In conclusion, Delphi for Python offers a stable and efficient solution for GUI development with Python. It combines Python’s ease of use and versatility with the power of Delphi’s GUI development capabilities to create intuitive and user-friendly cross-platform applications. Because Delphi has a long history in GUI development, developers can use its powerful tools and features to create functional and visually appealing applications. 

Furthermore, by incorporating Delphi into Python GUI development, developers can leverage the strengths of both languages to create powerful applications that meet their requirements. If you’re interested in learning more about how to use Delphi for Python GUI development, there’s a great resource available in the form of an eBook. This comprehensive guide walks you through using Delphi to create Python GUI applications. It goes over creating forms, using components, handling events, and other topics. This eBook can help you unlock the full potential of Delphi for creating beautiful and powerful GUI applications, whether you’re a seasoned developer or just getting started with Python GUI development.

So, to take your Python GUI development to the next level, check out the “Getting Started with Python GUI” ebook today and start creating amazing applications!

What are some FAQs related to PythonGUI?

How To Start Python GUI Development With Delphi? A laptop with a person looking at the FAQ page.

What is Delphi?

Delphi is a software development kit and programming language that has been around since the 1990s. It is well-known for its GUI development capabilities and is widely used in developing applications for Windows and other platforms.

Why should you use Delphi for Python GUI development?

Delphi’s powerful GUI development tools and features make it an ideal solution for visually appealing and intuitive applications. When Delphi’s capabilities are combined with Python’s versatility and ease of use, the result is a powerful solution for developing cross-platform GUI applications.

What is the “Getting Started with Python GUI” eBook?

The Python GUI Programming with Delphi eBook is a comprehensive guide to developing Python GUIs with Delphi. It provides a step-by-step tutorial on creating forms, using components, handling events, and more, making it an excellent resource for Python GUI developers looking to improve their skills.

Is the Delphi for Python combination suitable for beginners?

While Delphi and Python can be a little daunting for beginners, developers of all skill levels can use the two together. The eBook “Python GUI Programming with Delphi” provides a comprehensive guide that can assist beginners in learning the fundamentals of Delphi and Python GUI development.

Can Delphi be used for other programming languages?

Delphi is primarily used for developing applications using its programming language, but it can also be used with other programming languages such as C++ and C#. Its GUI development capabilities, however, are best utilized with its language.

The post How To Start Python GUI Development With Delphi? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-start-python-gui-development-with-delphi/feed/ 0 9935
How To Create A Calculator App Using Python GUI? https://pythongui.org/how-to-create-a-calculator-app-using-python-gui/ https://pythongui.org/how-to-create-a-calculator-app-using-python-gui/#respond Wed, 22 Mar 2023 15:33:11 +0000 https://pythongui.org/?p=9374 Python is a fantastic programming language for developing a wide range of useful scripts and programs, including graphical user interfaces (GUIs). A graphical user interface (GUI) allows users to perform operations on a program, platform,...

The post How To Create A Calculator App Using Python GUI? first appeared on Python GUI.

]]>
Python is a fantastic programming language for developing a wide range of useful scripts and programs, including graphical user interfaces (GUIs). A graphical user interface (GUI) allows users to perform operations on a program, platform, device, or application without typing commands or understanding its code. So, if you want to learn to make stunning GUIs with Python, this article is for you.

In this tutorial, we will take a look at the basics of Python GUI. We will learn how to create a simple calculator app for Windows and Android devices and take a look at some of the best Python GUI tools on the market.

What are useful tools for creating a Python GUI?

How To Create A Calculator App Using Python GUI? - a laptop with "unleash the power of your dreams" page on it

There are several tools for Python GUI that Embarcadero offers, including Delphi Community Edition, DelphiFMX, DelphiVCL, PythonFMXBuilder, Delphi4PythonExporter, and PyScripter.

What is DelphiFMX?

DelphiFMX is a natively compiled Python package using the Python4Delphi library. It’s open source and gives Python developers access to Delphi’s FireMonkey (FMX) GUI framework. GUI development with DelphiFMX is possible for many platforms, including Windows, macOS, Linux, and Android.

Embarcadero Delphi’s FireMonkey is a graphical user interface framework for developing native cross-platform applications. It makes use of the GPU via DirectX or OpenGL for hardware-accelerated rendering. It includes a robust styling system and is easily customizable by the user. DelphiFMX for Python requires no prior knowledge of Delphi or Object Pascal.

What is Delphi4PythonExporter?

Delphi4PythonExporter is a critical offering for a thriving Python and Delphi ecosystem. Python developers can save time writing design code in Python by leveraging Delphi’s flagship UI design features. As you design, they can use a WYSIWYG preview, including styles.

Furthermore, users can leverage the features during the design process to tie event methods to various events on the GUI application (for example, OnClick). Finally, Pythoneers can employ this method to scale their large-scale Python GUI application.

Delphi developers can also profit from the Exporter. They can leverage their Delphi expertise to design fantastic apps and then give Python implementations of those applications, providing you with new possibilities and an entirely new dimension.

What is PythonFMXBuilder?

The PythonFMXBuilder is a Python application builder that targets Android applications using DelphiFMX for Python. This enables you to embed a custom Python script in an Android app, deploy it to your phone, and submit it to the app market.

How can I create a simple calculator app using Python and DelphiFMX?

How To Create A Calculator App Using Python GUI? A close up of a laptop with the Get RAD Studio Now webpage showing on it

Let’s create a basic calculator application for both Android and desktop devices!

What are the requirements to create a calculator app with Python?

Python, PythonFMXBuilder, Delphi4PythonExporter, Delphi, and any text editor or IDE (PyScripter is recommended) that supports Python are required for this tutorial. If you don’t have these tools installed, check out this article on Python GUI Project Setup to get started.

You can grab the code for this tutorial from our Git repository at: github.com/Embarcadero/PythonBlogExamples/tree/main/Calculator_GUI

How To Create A Calculator App Using Python GUI? The main Python GUI setup hero image

How to start a basic form screen for a Python App in Delphi?

Open Delphi CE and create a blank application by navigating to File > New > Multi-Device Application > Blank Application > Ok. Here we have named our project Calculator.

How To Create A Calculator App Using Python GUI? A screenshot of the IDE in action

To get a detailed understanding of what each section of the above Delphi IDE means/represents, please go through the free eBook bundle that we developed. This eBook explains the ideology around Delphi-Python EcoSystem, all Python GUI offerings, and much more.

How To Create A Calculator App Using Python GUI? Get the free Python GUI book.

Next, let’s rename our app by right clicking on the form and selecting QuickEdit. Here we will name our form as CalculatorGUI with the caption Calculator Application.

How To Create A Calculator App Using Python GUI? Naming the Python GUI
How To Create A Calculator App Using Python GUI? Choosing a TLabel from the control pallette
How To Create A Calculator App Using Python GUI? A screen with two labels on it

It is important even to name the labels so that it is easier to track them. We even need to add buttons, TButton, that, when clicked, will give appropriate results to the calculation.

How To Create A Calculator App Using Python GUI? The object hierarchy
13-9835266

Next, rename the text of each label by right-clicking on that label and selecting Quick Edit.

How To Create A Calculator App Using Python GUI? Selecting quick edit
How To Create A Calculator App Using Python GUI? Changing the results label

Next, add some color to the form’s background. We can do this by navigating to the Object Inspector and selecting the form’s fill property. After these changes, our form will look much more visually attractive:

How To Create A Calculator App Using Python GUI? Picking some colors.


We can also check out how our app looks on both Desktop and Android apps. To check this, we can change the Style from Windows to Android. This will change the appearance of our form.

How To Create A Calculator App Using Python GUI? Select Android as the target
How To Create A Calculator App Using Python GUI? The calculator GUI

Now double-click on all the buttons on the form. Double-clicking helps to create click methods for each button in the .pas that corresponds to our .fmx form. This helps add a click functionality to each of these buttons later. Next, to each of the button Click methods add at least a single comment (//) which will ensure the method remains as we save the file in Python. There is no need to write any run-time implementation code because we don’t export the run-time implementation using the Delphi4PythonExporter.

How To Create A Calculator App Using Python GUI? The empty events in code

How to export a form screen as a Python Script?

You can save your project as a Python script by selecting Tools > Export To Python > Export Current Entire Project.

How To Create A Calculator App Using Python GUI? Exporting the project to Python

Delphi will generate two Python scripts, which you can rename to Calculator.py and CalculatorMain.py, in your chosen directory. Along with the Python file is a .pyfmx form that contains all the form’s visual information.

The code in CalculatorMain.py is as follows:

from delphifmx import *
from Calculator import CalculatorGUI

def main():
    Application.Initialize()
    Application.Title = 'CalculatorGUI'
    Application.MainForm = CalculatorGUI(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

Now, let’s look at Calculator.py, where we will be writing the logic of our application:

import os
from delphifmx import *

class CalculatorGUI(Form):
    def __init__(self, owner):
        self.Del = None
        self.C = None
        self.Percent = None
        self.Plus = None
        self.Seven = None
        self.Eight = None
        self.Nine = None
        self.Minus = None
        self.Four = None
        self.Five = None
        self.Six = None
        self.Multiply = None
        self.One = None
        self.Two = None
        self.Three = None
        self.Zero = None
        self.Dot = None
        self.Divide = None
        self.Equals = None
        self.Calc = None
        self.Results = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Calculator.pyfmx"))

    def DelClick(self, Sender):
        pass

    def CClick(self, Sender):
        pass

    def PercentClick(self, Sender):
        pass

    def PlusClick(self, Sender):
        pass

    def SevenClick(self, Sender):
        pass

    def EightClick(self, Sender):
        pass

    def NineClick(self, Sender):
        pass

    def MinusClick(self, Sender):
        pass

    def FourClick(self, Sender):
        pass

    def FiveClick(self, Sender):
        pass

    def SixClick(self, Sender):
        pass

    def MultiplyClick(self, Sender):
        pass

    def OneClick(self, Sender):
        pass

    def TwoClick(self, Sender):
        pass

    def ThreeClick(self, Sender):
        pass

    def ZeroClick(self, Sender):
        pass

    def DotClick(self, Sender):
        pass

    def DivideClick(self, Sender):
        pass

    def EqualsClick(self, Sender):
        pass

How to run the calculator as a desktop App using the exported Python script?

As you remember, in the code above, all the Click methods like DelClick were left empty. Therefore, we first need to add functionality to all these buttons. So let’s start coding.

First, navigate to your project folder and open up Calculator.py:

How To Create A Calculator App Using Python GUI? Calculator app in the Python IDE

Here, you will see all the objects you’ve created and the click methods for each button. For this calculator, we will use the Python eval() function that evaluates any strings that are passed onto it. So create an empty string self.Calculation in the __init__ method of the form. In addition, since the labels in our calculator contain some text, we will also initialize them as empty:

def __init__(self, owner):
        self.Del = None
        self.C = None
        self.Percent = None
        self.Plus = None
        self.Seven = None
        self.Eight = None
        self.Nine = None
        self.Minus = None
        self.Four = None
        self.Five = None
        self.Six = None
        self.Multiply = None
        self.One = None
        self.Two = None
        self.Three = None
        self.Zero = None
        self.Dot = None
        self.Divide = None
        self.Equals = None
        self.Calc = None
        self.Results = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Calculator.pyfmx"))
        self.Calculation = ""
        self.Results.Text = ""
        self.Calc.Text = ""
How To Create A Calculator App Using Python GUI? The events

Now, we can start coding our click methods. Navigate to each click method and add the relevant character to the self.Calculation string. In addition to this, since we have created a Calc label to display the calculation, add the character to Self.Calc.Text:

def DelClick(self, Sender):
        self.Calculation = self.Calculation[:-1]
        self.Calc.Text = self.Calculation

    def CClick(self, Sender):
        self.Calculation = ""
        self.Calc.Text = self.Calculation
        self.Results.Text = ""

    def PercentClick(self, Sender):
        self.Calculation += "%"
        self.Calc.Text = self.Calculation

    def PlusClick(self, Sender):
        self.Calculation += "+"
        self.Calc.Text = self.Calculation

    def SevenClick(self, Sender):
        self.Calculation += "7"
        self.Calc.Text = self.Calculation

    def EightClick(self, Sender):
        self.Calculation += "8"
        self.Calc.Text = self.Calculation

    def NineClick(self, Sender):
        self.Calculation += "9"
        self.Calc.Text = self.Calculation

    def MinusClick(self, Sender):
        self.Calculation += "-"
        self.Calc.Text = self.Calculation

    def FourClick(self, Sender):
        self.Calculation += "4"
        self.Calc.Text = self.Calculation

    def FiveClick(self, Sender):
        self.Calculation += "5"
        self.Calc.Text = self.Calculation

    def SixClick(self, Sender):
        self.Calculation += "6"
        self.Calc.Text = self.Calculation

    def MultiplyClick(self, Sender):
        self.Calculation += "*"
        self.Calc.Text = self.Calculation

    def OneClick(self, Sender):
        self.Calculation += "1"
        self.Calc.Text = self.Calculation

    def TwoClick(self, Sender):
        self.Calculation += "2"
        self.Calc.Text = self.Calculation

    def ThreeClick(self, Sender):
        self.Calculation += "3"
        self.Calc.Text = self.Calculation

    def ZeroClick(self, Sender):
        self.Calculation += "0"
        self.Calc.Text = self.Calculation

    def DotClick(self, Sender):
        self.Calculation += "."
        self.Calc.Text = self.Calculation

    def DivideClick(self, Sender):
        self.Calculation += "/"
        self.Calc.Text = self.Calculation
How To Create A Calculator App Using Python GUI? Click events

Like the C and Del functions in most calculators, our calculator does the same. If the Del key is pressed our calculator deletes the last character added, and if the C button is pressed our calculator clears all the calculations. Now, we can code the equals button method. The method uses a try and except block to try and calculate the given expression, using eval, if it is possible. If the added string is correct it shows the result in the self.Results Label, otherwise it shows an "Error" message.

def EqualsClick(self, Sender):
        try:
            self.Results.Text = str(eval(self.Calculation))
        except:
            self.Results.Text = "Error"
How To Create A Calculator App Using Python GUI? Filling out the click events.

Here is what our final Calculator.py file looks like:

import os
from delphifmx import *

class CalculatorGUI(Form):
    def __init__(self, owner):
        self.Del = None
        self.C = None
        self.Percent = None
        self.Plus = None
        self.Seven = None
        self.Eight = None
        self.Nine = None
        self.Minus = None
        self.Four = None
        self.Five = None
        self.Six = None
        self.Multiply = None
        self.One = None
        self.Two = None
        self.Three = None
        self.Zero = None
        self.Dot = None
        self.Divide = None
        self.Equals = None
        self.Calc = None
        self.Results = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Calculator.pyfmx"))
        self.Calculation = ""
        self.Results.Text = ""
        self.Calc.Text = ""

    def DelClick(self, Sender):
        self.Calculation = self.Calculation[:-1]
        self.Calc.Text = self.Calculation

    def CClick(self, Sender):
        self.Calculation = ""
        self.Calc.Text = self.Calculation
        self.Results.Text = ""

    def PercentClick(self, Sender):
        self.Calculation += "%"
        self.Calc.Text = self.Calculation

    def PlusClick(self, Sender):
        self.Calculation += "+"
        self.Calc.Text = self.Calculation

    def SevenClick(self, Sender):
        self.Calculation += "7"
        self.Calc.Text = self.Calculation

    def EightClick(self, Sender):
        self.Calculation += "8"
        self.Calc.Text = self.Calculation

    def NineClick(self, Sender):
        self.Calculation += "9"
        self.Calc.Text = self.Calculation

    def MinusClick(self, Sender):
        self.Calculation += "-"
        self.Calc.Text = self.Calculation

    def FourClick(self, Sender):
        self.Calculation += "4"
        self.Calc.Text = self.Calculation

    def FiveClick(self, Sender):
        self.Calculation += "5"
        self.Calc.Text = self.Calculation

    def SixClick(self, Sender):
        self.Calculation += "6"
        self.Calc.Text = self.Calculation

    def MultiplyClick(self, Sender):
        self.Calculation += "*"
        self.Calc.Text = self.Calculation

    def OneClick(self, Sender):
        self.Calculation += "1"
        self.Calc.Text = self.Calculation

    def TwoClick(self, Sender):
        self.Calculation += "2"
        self.Calc.Text = self.Calculation

    def ThreeClick(self, Sender):
        self.Calculation += "3"
        self.Calc.Text = self.Calculation

    def ZeroClick(self, Sender):
        self.Calculation += "0"
        self.Calc.Text = self.Calculation

    def DotClick(self, Sender):
        self.Calculation += "."
        self.Calc.Text = self.Calculation

    def DivideClick(self, Sender):
        self.Calculation += "/"
        self.Calc.Text = self.Calculation

    def EqualsClick(self, Sender):
        try:
            self.Results.Text = str(eval(self.Calculation))
        except:
            self.Results.Text = "Error"

Finally, open up CalculatorMain.py file and run your application:

How To Create A Calculator App Using Python GUI? The calculator GUI

Let’s go ahead and test this app. If everything works perfectly then you will be able to run any kind of equation on your application. For example, you can add two numbers easily, and pressing the = sign yields a result:

How To Create A Calculator App Using Python GUI? The equals button on the GUI

However, if your mathematical expression to be calculated is invalid you are prompted with an error message:

How To Create A Calculator App Using Python GUI? An error message on display

How to build the calculator as an Android Application using Python and PythonFMXBuilder?

The Delphi4Python Exporter exports the calculator application with initialization logic for a desktop-based application. Therefore, we will be using the PythonFMXBuilder to convert our calculator to an Android app. But before we export our calculator, we need to make some important changes to our code. 

Firstly, Android applications are Delphi applications that are initialized automatically. Therefore we don’t need to initialize the application explicitly or to set a title because it will be initialized automatically. So first lets create a new Python file named CalculatorMain_Android.py and paste the contents of CalculatorMain.py in this new file. Next, we don’t need to set the Application.MainForm, but need a variable for the Form. Lastly, just like initialization, we don’t need to run nor destroy the application as it is done automatically by Android. 

Here is what our CalculatorMain_Android.py looks like:

from delphifmx import *
from Calculator import CalculatorGUI

def main():
    Application.MainForm = CalculatorGUI(Application)
    Application.MainForm.Show()

if __name__ == '__main__':
    main()
How To Create A Calculator App Using Python GUI? The script.

Save the file with the changes you’ve made. Next, Open up FMXBuilder and click on Project > New project on the toolbar. Enter the name of the project that you want to build here.

How To Create A Calculator App Using Python GUI? Create a new project

Add your Python files as well as any other supporting project files you used to build your application. We will not import CalculatorMain.py as its only purpose is to run our desktop application:

How To Create A Calculator App Using Python GUI? The Android project

Next, right-click on CalculatorMain_Andriod.py file and set it to the main file.

We are now ready to convert our app to Android. PythonFMXBuilder gives developers three options for building applications: build, deploy, and run. You can learn more about these options by reading PythonGUI’s e-book.

How To Create A Calculator App Using Python GUI? The Android project in the editor

PythonFMXBuilder allows you to directly install the application on your mobile device. For now, we will build an Android application using a .apk file. To build your file Build project button on the toolbar.

32-5710816

When the .apk is fully generated you will be prompted with a "Build process done" message in the Messages box. You can then check out your generated file in the pathtoPythonFMXBuilderGUIexeFolderappsCalculatorbin folder.

How To Create A Calculator App Using Python GUI? Folder listing showing the APK location

Simply copy and paste this .apk file into your phone’s storage. You will be prompted to install this file if you access it from your phone and click on it. Once completed, your app calculator will be available for use in the same way that any other Android app is.

Here is what our calculator app looks like:

How To Create A Calculator App Using Python GUI? The calculator app running on a mobile device.

Similar to our desktop app, you can make all kinds of calculations expected from a simple calculator:

How To Create A Calculator App Using Python GUI? The actual calculator app

Also, similar to our desktop app, trying to evaluate an invalid calculation yields an error:

How To Create A Calculator App Using Python GUI? The running calculator app

Are you prepared to create more Apps using Python and DelphiFMX?

How To Create A Calculator App Using Python GUI? A laptop showing the the download PyScripter page

Congratulations on making it to the end of this tutorial! Hopefully, it has made you realize how simple it is to build Python GUIs with the right toolkit.

In this tutorial, we saw how building applications is efficient with Delphi. We learned that DelphiFMX is an extremely capable application with numerous capabilities and customization options. It is highly recommended for Windows, Linux, and Mac application developers due to its inherent support for hardware acceleration. DelphiFMX is perfect for building not just calculators, but also other useful applications such as currency converters.

If you want to learn more about Python GUI’s features, you can download the Python GUI getting started e-book. The best part about this package is that you can create multi-device applications. In addition, we also saw how using DelphiFMX library in PyScripter makes Python programming even more fun and easy.

Now that you have seen how the right set of Python GUI tools can be used to create Android and desktop applications, click here and install Delphi to start creating Python-based apps right away!

What are the FAQs regarding creating a Python GUI app?

How To Create A Calculator App Using Python GUI? A person looking at a laptop screen which is on the FAQ page

What is Embarcadero?

Embarcadero is the parent company of numerous B2B productivity software companies that enable technical users to complete more tasks in less time.

Embarcadero products are designed for the most skilled programmers in the world who build and support the most important applications. Embarcadero is the developer champion for many clients, supporting them in creating corporate applications that are more secure and scalable faster than with any other solution available. Ninety percent of the Fortune 100 and a global user base of more than three million have trusted Embarcadero’s award-winning products for more than 30 years.

Why is PyScripter a user-favorite IDE?

PyScripter is a free, open-source Python IDE for Windows. Delphi’s Object Pascal and Python were used to create it.

It started as a simple IDE to provide a powerful scripting solution for Delphi applications, which gradually evolved into a full-featured stand-alone Python IDE. PyScripter is written in Delphi and can be extended with Python scripts using Python4Delphi (P4D). It is relatively light compared to other IDEs because it is written in a compiled language.

PyScripter can be used as a syntax highlighting editor, a Python interpreter and debugger, a file explorer, a project manager, and more. In addition, it can be used for creating simple programs as well as more sophisticated APIs and TUIs.

What is Delphi?

Delphi is a high-level programming language that supports an object-oriented paradigm. It is a Rapid Application Development (RAD) paradigm used to create applications ranging from database solutions to mobile applications. Delphi is now widely regarded as the quickest way to develop, compile, package, and deploy cross-platform native applications for Windows, macOS, iOS, Android, and Linux.

Can you build GUIs in Python?

Creating a simple graphical user interface (GUI) that works across multiple platforms can be difficult. But this does not have to be the case. Python and Embarcadero’s DelphiFMX and DelphiVCL packages can be used to create visually appealing user interfaces for you and your users!

What is a multi-device application?

A multi-device application can operate on any platform supported by RAD Studio; multi-device apps are not restricted to desktop or mobile platforms. Multi-device applications use two of RAD Studio’s three core libraries: FireMonkey and RTL.

The post How To Create A Calculator App Using Python GUI? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-calculator-app-using-python-gui/feed/ 0 9374
Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages https://pythongui.org/introducing-python-3-11-and-documentation-support-to-the-delphifmx-and-delphivcl-gui-python-packages/ https://pythongui.org/introducing-python-3-11-and-documentation-support-to-the-delphifmx-and-delphivcl-gui-python-packages/#respond Tue, 14 Mar 2023 12:56:03 +0000 https://pythongui.org/?p=9859 Python 3.11 is the newest release of the Python programming language, and it contains many new features and optimizations compared to its prior 3.10 version. So many third-party Python packages are upgrading to support the...

The post Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages first appeared on Python GUI.

]]>
Python 3.11 is the newest release of the Python programming language, and it contains many new features and optimizations compared to its prior 3.10 version. So many third-party Python packages are upgrading to support the latest Python 3.11 version to take advantage of its latest features. To understand all the enhancements of Python 3.11, check out our blog post here. Also, any Python package must be able to help look up what a type/class and its attributes and methods do in terms of documentation. So we’re happy to announce that we now support Python 3.11 and documentation in our latest major releases of DelphiFMX and DelphiVCL Python GUI packages.

Are DelphiFMX and DelphiVCL compatible with Python 3.11?

Python 3.11 has been the most awaited release for the Python community, majorly because of its claims of Faster Python. The latest releases of our DelphiFMX and DelphiVCL Python GUI packages are fully compatible with Python 3.11. You can install them the same way you installed them earlier using PIP, as mentioned here.

Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages - the 3.11 ecosystem
Source: https://www.python.org/downloads/release/python-3110/

Our GUI packages work under any of the following:

  • System-wide Python installation from python.org
  • CPython environment created using conda environment manager – miniconda or anaconda
  • CPython environment created using venv virtual environment manager for managing multiple Python installations

Check out the images below to showcase that DelphiFMX and DelphiVCL are working on Python 3.11 environment created using the conda environment manager.

Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages - installing Python 3.11
Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages - a basic Python GUI form running

Bringing documentation support to DelphiFMX and DelphiVCL packages

Python provides a feature called “Docstrings“, which can be used to explain to any package/library/module users what a type/class and any method/attribute does. So the docstrings can be embedded into any symbol of any given package. Even though we have great Python packages (DelphiFMX and DelphiVCL) to develop GUI applications, we didn’t have docs available until the previous version. In the latest releases of the packages, we’re providing all the docs embedded into any symbol available as part of the importing process. Let’s look at the available docstrings and docs for a Form type using various ways to access them.

Accessing the Docs through help(object)

Default Python installation provides a Python REPL to run short scripts and check your logic before implementing it in the Production level code. Let’s use the REPL to get the help of Form type:

Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages - explanation of prompts

Accessing DocString using __doc__ attribute

Python internally implements a double underscore (dunder) method for each top-level core functionality. So, the Docstrings of any object are embedded into the __doc__ attribute, and we can access it using object.__doc__:

Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages -- accessing the DocString

Accessing Docs using ? feature of IPython

IPython project takes the REPL capabilities of Python to the next level. Out of all the amazing things that you can do with IPython, we can display the docs of any object in an elegant way using the ? symbol say, object? :

Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages - using the ? feature of IPython

Future updates – what’s next?

  • Utilizing the Docstrings to generate a Static site for Docs using the Sphinx Documentation generator.
  • Deploying the Static Docs site to any favorable and automated open-source hosting.

Are you ready to build GUI applications using the DelphiFMX or DelphiVCL Python packages?

With the updates mentioned in this article, you can now build your favorite GUI applications on Python 3.11 version. We have an eBook to get you started with the GUI development journey using either the DelphiFMX or DelphiVCL. The eBook bundle contains the Getting Started with Python GUI development eBook, 15 DelphiFMX for Python Styles, and 13 DelphiVCL for Python styles. All styles support High DPI to help your applications look fantastic, and the DelphiFMX styles work seamlessly on all Windows, macOS, Linux, and Android platforms. The eBook covers the basics of programming Python with these libraries. So unlock your potential for excellent Python GUI development by downloading the eBook bundle at: embt.co/PythonGUIBundle

Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages - getting started with Python GUI book image

NOTE: The Python 3.11 graphic can be found at https://www.python.org/downloads/release/python-3110/ and is used for illustrative purposes only. No endorsement by Python Software Foundation is implied. The cover graphic of this article is a composite image created by the PythonGUI.org editorial team.

The post Introducing Python 3.11 And Documentation Support To The DelphiFMX And DelphiVCL GUI Python Packages first appeared on Python GUI.

]]>
https://pythongui.org/introducing-python-3-11-and-documentation-support-to-the-delphifmx-and-delphivcl-gui-python-packages/feed/ 0 9859
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem https://pythongui.org/how-to-create-a-tic-tac-toe-game-using-delphi-python-ecosystem/ https://pythongui.org/how-to-create-a-tic-tac-toe-game-using-delphi-python-ecosystem/#respond Tue, 07 Mar 2023 19:03:28 +0000 https://pythongui.org/?p=9497 Python is a popular programming language due to its readability, flexibility, and beginner-friendliness. It is fantastic for creating graphical user interfaces (GUI), and today, it offers a lot of frameworks that anyone may utilize to...

The post How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem first appeared on Python GUI.

]]>
Python is a popular programming language due to its readability, flexibility, and beginner-friendliness. It is fantastic for creating graphical user interfaces (GUI), and today, it offers a lot of frameworks that anyone may utilize to begin designing a GUI quickly.

GUIs are one of the essential components of any Android application. So, if you’re learning Python and want to improve your GUI development skills, this post is for you. This article will provide a simple method for creating a tic-tac-toe game for Android.

Why should you build a Tic Tac Toe Android app?

Playing games is a natural approach to improving fine motor skills and promoting social connection. Tic-tac-toe can be used to develop various cognitive abilities, such as counting, spatial awareness, and the ability to recognize colors and shapes.

Players must focus or concentrate for brief periods to win a tic-tac-toe game. Focus and concentration can be improved with practice in these areas. An incredible skill to have in every aspect of life is this one. Consequently, many individuals are creating mobile apps for this kind of game.

What tools do Python developers prefer for building Python GUIs?

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - an image of a laptop showing the download page for the VCL and FMX libraries

Embarcadero provides several tools for creating Python GUIs, including PyScripter, Delphi Community Edition, DelphiFMX, PythonFMXBuilder, and Delphi4PythonExporter.

DelphiFMX is a natively generated Python package created using the Python4Delphi library/bridge. Thanks to its open-source nature, Python programmers can access the Delphi programming language’s rich and mature FireMonkey (FMX) GUI framework. DelphiFMX Python package enables GUI creation for various operating systems, including Windows, macOS, Linux, and Android.

The Delphi4PythonExporter is a crucial tool/addon for a robust Python and Delphi ecosystem. Python developers can use Delphi’s premier UI design tools to speed up the authoring of design code in Python. The Exporter can be helpful to Delphi developers as well. They can use their Delphi experience to create amazing programs and then provide Python equivalents of those applications, giving you additional options and a different perspective.

PythonFMXBuilder is a Python application builder for Android applications that uses DelphiFMX. This allows you to deploy an individual Python script to your phone and integrate it within an Android app.

PySripter is another helpful tool, an Integrated Development Environment (IDE) for Python on Windows, which is free and open-source. It is built using Python and Delphi using the same Python4Delphi that powers DelphiFMX. Initially created as a simple IDE to offer a powerful scripting solution for Delphi applications.

Now that we know our needed tools let’s start making our app.

How can you create a Tic-Tac-Toe game for Android?

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - a laptop running the Python editor

Let’s create a basic calculator application for both Android and desktop devices! Using the Python and Delphi tools mentioned above is a good approach. So let’s get started!

What are the requirements to create this game?

Python, PythonFMXBuilder, Delphi4PythonExporter, Delphi, and any text editor or IDE (PyScripter is recommended) that supports Python are required for this tutorial.

If you don’t have these installed, we recommend checking out this Delphi Python GUI Project Setup article to learn more about installing all the recommended tools.

You can grab the code for this tutorial from our Git repository at: https://github.com/Embarcadero/PythonBlogExamples/tree/main/TicTacToe_GUI

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - composite image of various laptops and logos

How to start a basic form for the app in Delphi?

Open Delphi CE and create a blank application by navigating to File > New > Multi-Device Application > Blank Application > Ok. Here we have named our project TicTacToeProject.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - a screenshot showing the beginning of a Python4Delphi project

To get a detailed understanding of what each section of the above Delphi IDE mean/represent, please go through the free eBook bundle that we developed. This eBook explains the ideology around Delphi-Python EcoSystem, all Python GUI offerings, and much more.

image-1412714-2407127

Let’s start by giving our form a name. Right click on the form and click on QuickEdit. Here we will name our form as TicTacToeGUI and display the title as Tic Tac Toe Game.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - editing the quickedit settings

Because we want to make a fully functional multiplayer tic tac-toe game, we should include some labels that will allow the user to be updated with the game’s status and so on. We will be using the TLabel component from the standard palette for this.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the object inspector, searching for a TLabel

Let’s go ahead and even change the label text style to make the app more attractive. We will do this using TextSettings. Head on over to the Object Inspector and search for TextSettings. Select Font under it and click on the ... to see options allowing you to change the label font, size and style according to your needs.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the font settings in the object inspector

Next, rename the text of each label by right-clicking on that label and selecting Quick Edit. It is important to follow an intuitive naming convention to name the labels so that it is easier to track them.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - adding the title

Next, we need to create some lines to create a tic-tac-toe grid. So go to the Palette and search for TLine. Insert the four lines, as appropriate, to create a 3×3 grid.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the command palette

Now, let’s change the form’s background color to make it more appealing. We can do this by navigating to the Object Inspector and selecting the form’s fill property.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - editing the fill
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the Tic Tac Toe game

We need to add functionality to the grid boxes so we can play our game. So let’s add buttons to each box in the grid. These buttons will add an X or O to that box when clicked. Go to the Palette and add the buttons using the TButton component.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - looking for the button component on the palette
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - selecting quick edit from the context menu
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem doing more selection

You should even change the font size and style of this button text (as we did for the TLabels above) so that the “X” and “O”s are more prominent. We can even align the text to the Center so that the markers appear symmetric in each box (button).

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - editing the text settings

After these changes, our form will look much more visually attractive:

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the screen of the game

Finally, we added a reset button to help us reset our game to initial conditions. We may also see how our app appears on desktop and Android phones. Switch the Style from Windows to Android to verify this. This will alter how our form appears.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem showing the player moves

Now, double-click on each button on the form. The form’s buttons can be clicked twice to construct Click methods in the .pas file that corresponds to our .fmx for each button. This makes it easier to add click functionality to each button.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - adding the resetclick methods

To ensure that the method is preserved when we save the .pas file, add at least one comment (//) after each button Click method. Since we don’t export the run-time implementation using the Delphi4PythonExporter, there is no need to write any run-time implementation code.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - adding more methods

How to export this form as a Python script?

You can save your project as a Python script by selecting Tools > Export To Python > Export Current Entire Project.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - exporting the form to a Python script

Delphi will generate two Python scripts, which you can rename to TicTacToe.py and TicTacToeMain.py, in your chosen directory. Along with the Python file, a .pyfmx file containing all the form’s visual information is saved in that directory. The exported TicTacToeMain.py will have the following code:

from delphifmx import *
from TicTacToe import TicTacToeGUI

def main():
    Application.Initialize()
    Application.Title = 'TicTacToe'
    Application.MainForm = TicTacToeGUI(Application)
    Application.MainForm.Show()
    Application.Run()

if __name__ == '__main__':
    main()
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - showing the script

How to add functionality to the game?

Now that our app is ready, we can add logic to our game. So go to your project folder and open up TicTacToe.py.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - adding game play to the code

First, we need to create a 3×3 grid that will help us program our grid logic. So in the __init__ function, add a nested 2D list that contains the text of each button corresponding to their position in the grid using the .Text attribute:

self.board = [[self.Pos1.Text, self.Pos2.Text, self.Pos3.Text], 
                    [self.Pos4.Text, self.Pos5.Text, self.Pos6.Text], 
                    [self.Pos7.Text, self.Pos8.Text, self.Pos9.Text]]

Next, we create our players as self.p1 and self.p2 and create an integer variable self.player_status that will help us know each player’s turn. Player 1 moves if player_status is 1, and Player 2 moves if player_status is 2.

Here is what our __init__ function looks like:

def __init__(self, owner):
        self.Title = None
        self.Status = None
        self.Line1 = None
        self.Line2 = None
        self.Line3 = None
        self.Line4 = None
        self.Pos1 = None
        self.Pos2 = None
        self.Pos3 = None
        self.Pos4 = None
        self.Pos6 = None
        self.Pos5 = None
        self.Pos7 = None
        self.Pos8 = None
        self.Pos9 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TicTacToe.pyfmx"))

        self.board = [[self.Pos1.Text, self.Pos2.Text, self.Pos3.Text], 
                    [self.Pos4.Text, self.Pos5.Text, self.Pos6.Text], 
                    [self.Pos7.Text, self.Pos8.Text, self.Pos9.Text]]
        self.p1 = "X"
        self.p2 = "O"
        self.player_status = 1

What will happen when any of the buttons in the grid are clicked?

We need to add some functionality to the tic-tac-toe app that will help us display our moves on the app, but only in empty slots of the grid to not overwrite the moves made by the other player.

First, let’s create a class method named make_move that takes in four parameters, the player who moved, the row and column positions, and the button to be updated. We first check if the move is valid. If there is already a move made in a slot, meaning if the Text of a button is X or O, we shall display a try again message:

def make_move(self, player, row, col, Pos):
        if Pos.Text != "":
            self.Status.Text = "Please try again!"

If there is no X or O in a slot, meaning the button’s Text is empty, we have to add an X for player 1’s move or an O otherwise. Once the move is made, we toggle the player_status to indicate the other player’s turn:

else:
            self.board[row][col] = player
            Pos.Text = player
            if player == "X":
                self.player_status = 2
            else:
                self.player_status = 1

Finally, we check whether the move has resulted in a winner, which we will check using a has_winner() method (we will define it later), or check if all the buttons are full, indicating a tie.

A tie would occur if all the boxes of the tic-tac-toe grid that were initially empty, now contain a X or O. So we can check this by creating a string of all the elements in the board. If its length is nine and there was no winner, there would have been a draw. If it is neither a win nor a tie, then the game continues, and we display whose turn it is. Here is what our function looks like:

if self.has_winner()==True:
                pass
            elif len("".join([self.board[i][j] for i in range(3) for j in range(3)])) == 9:
                self.Status.Text = "Tie! Game Over!"
            else:
                self.Status.Text = "Player "+ str(self.player_status) + " Move"

Here is what the final method looks like:

def make_move(self, player, row, col, Pos):
        if Pos.Text != "":
            self.Status.Text = "Please try again!"
        else:
            self.board[row][col] = player
            Pos.Text = player
            if player == "X":
                self.player_status = 2
            else:
                self.player_status = 1

            if self.has_winner()==True:
                pass
            elif len("".join([self.board[i][j] for i in range(3) for j in range(3)])) == 9:
                self.Status.Text = "Tie! Game Over!"
            else:
                self.Status.Text = "Player "+ str(self.player_status) + " Move"

Now head to the Button Click functions and call the make_move function with the relevant parameters. If player_status is one then player 1 moves, so we call the make_move method with X as the display string, the position of the Button on the 3×3 grid, and finally, the button itself so that it can be updated. We repeat this function call for all the other buttons. Here is what our Click functions look like:

def Pos1Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 0, 0, self.Pos1)
        else:
            self.make_move(self.p2, 0, 0, self.Pos1)

    def Pos2Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 0, 1, self.Pos2)
        else:
            self.make_move(self.p2, 0, 1, self.Pos2)

    def Pos3Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 0, 2, self.Pos3)
        else:
            self.make_move(self.p2, 0, 2, self.Pos3)

    def Pos4Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 1, 0, self.Pos4)
        else:
            self.make_move(self.p2, 1, 0, self.Pos4)

    def Pos5Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 1, 1, self.Pos5)
        else:
            self.make_move(self.p2, 1, 1, self.Pos5)

    def Pos6Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 1, 2, self.Pos6)
        else:
            self.make_move(self.p2, 1, 2, self.Pos6)

    def Pos7Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 2, 0, self.Pos7)
        else:
            self.make_move(self.p2, 2, 0, self.Pos7)

    def Pos8Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 2, 1, self.Pos8)
        else:
            self.make_move(self.p2, 2, 1, self.Pos8)

    def Pos9Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 2, 2, self.Pos9)
        else:
            self.make_move(self.p2, 2, 2, self.Pos9)

Note: The column and row positions are the positions of the Buttons relative to the tic-tac-toe grid.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - more work on the code

How to check when the game has ended?

Now that we have defined how we will make our moves, we need a mechanism to check whether the player wins. As mentioned previously, we will do this using the has_winner() method. For this method, we will check our tic-tac-toe grid for a winning pattern, which would be the same marker in one row, column, or diagonal. To do this, we run a for loop over the columns and rows of the board and see whether a pattern exists. If player 1 or player 2 wins, we assign it to a winner variable:

def has_winner(self):
        winner = None
        for i in range(3):
            # Check row combos
            if self.board[i][0] != "" and self.board[i][0] == self.board[i][1] and self.board[i][1] == self.board[i][2]:
                winner = self.board[i][0]
               
            # Check column combos
            elif self.board[0][i] != "" and self.board[0][i] == self.board[1][i] and self.board[1][i] == self.board[2][i]:
                winner = self.board[0][i]

Similar to checking the columns and rows, we also check for the diagonals:

# Check Diagonals
        if self.board[0][0] != "" and self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:
            winner= self.board[0][0]
        elif self.board[0][2] != "" and self.board[0][2] == self.board[1][1] and self.board[1][1] == self.board[2][0]:
            winner = self.board[0][2]

Finally, if we have a winner, we shall update the Status label at the bottom of the application. Here is our final method:

def has_winner(self):
        winner = None
        for i in range(3):
            # Check row combos
            if self.board[i][0] != "" and self.board[i][0] == self.board[i][1] and self.board[i][1] == self.board[i][2]:
                winner = self.board[i][0]
               
            # Check column combos
            elif self.board[0][i] != "" and self.board[0][i] == self.board[1][i] and self.board[1][i] == self.board[2][i]:
                winner = self.board[0][i]

        # Check Diagonals
        if self.board[0][0] != "" and self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:
            winner= self.board[0][0]
        elif self.board[0][2] != "" and self.board[0][2] == self.board[1][1] and self.board[1][1] == self.board[2][0]:
            winner = self.board[0][2]

        if winner != None:
            if winner == "X":
                self.Status.Text = "Player 1 Won the Match"
            else:
                self.Status.Text = "Player 2 Won the Match"

            return True

How to reset the game?

Now that our game is ready, we need a way to reset the game. Thankfully, we have created a Reset button that we will use to reset the game.

First, head to the __init__ method, copy the additional code we have added to the initial __init__ function, and paste it into the ResetClick() method. Next, we need to reset the Buttons’ Text attribute as well as the Status label. To do this, we simply empty the Text attribute of each button and re-initialize the Status.Text field. Our method code looks like:

def ResetClick(self, Sender):
        self.board = [["", "", ""], 
                    ["", "", ""], 
                    ["", "", ""]]
        self.p1 = "X"
        self.p2 = "O"
        self.player_status = 1

        self.Pos1.Text = ""
        self.Pos2.Text = ""
        self.Pos3.Text = ""
        self.Pos4.Text = ""
        self.Pos5.Text = ""
        self.Pos6.Text = ""
        self.Pos7.Text = ""
        self.Pos8.Text = ""
        self.Pos9.Text = ""

        self.Status.Text = "Player "+ str(self.player_status) + " Move"
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - resetting the values

After all this, TicTacToe.py will contain the following code:

import os
from delphifmx import *

class TicTacToeGUI(Form):

    def __init__(self, owner):
        self.Title = None
        self.Status = None
        self.Line1 = None
        self.Line2 = None
        self.Line3 = None
        self.Line4 = None
        self.Pos1 = None
        self.Pos2 = None
        self.Pos3 = None
        self.Pos4 = None
        self.Pos6 = None
        self.Pos5 = None
        self.Pos7 = None
        self.Pos8 = None
        self.Pos9 = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TicTacToe.pyfmx"))

        self.board = [[self.Pos1.Text, self.Pos2.Text, self.Pos3.Text], 
                    [self.Pos4.Text, self.Pos5.Text, self.Pos6.Text], 
                    [self.Pos7.Text, self.Pos8.Text, self.Pos9.Text]]
        self.p1 = "X"
        self.p2 = "O"
        self.player_status = 1

    def FormCreate(self, Sender):
        pass

    def Line4Click(self, Sender):
        pass

    def make_move(self, player, row, col, Pos):
        if Pos.Text != "":
            self.Status.Text = "Please try again!"
        else:
            self.board[row][col] = player
            Pos.Text = player
            if player == "X":
                self.player_status = 2
            else:
                self.player_status = 1

            if self.has_winner()==True:
                pass
            elif len("".join([self.board[i][j] for i in range(3) for j in range(3)])) == 9:
                self.Status.Text = "Tie! Game Over!"
            else:
                self.Status.Text = "Player "+ str(self.player_status) + " Move"

    def Pos1Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 0, 0, self.Pos1)
        else:
            self.make_move(self.p2, 0, 0, self.Pos1)

    def Pos2Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 0, 1, self.Pos2)
        else:
            self.make_move(self.p2, 0, 1, self.Pos2)

    def Pos3Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 0, 2, self.Pos3)
        else:
            self.make_move(self.p2, 0, 2, self.Pos3)

    def Pos4Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 1, 0, self.Pos4)
        else:
            self.make_move(self.p2, 1, 0, self.Pos4)

    def Pos5Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 1, 1, self.Pos5)
        else:
            self.make_move(self.p2, 1, 1, self.Pos5)

    def Pos6Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 1, 2, self.Pos6)
        else:
            self.make_move(self.p2, 1, 2, self.Pos6)

    def Pos7Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 2, 0, self.Pos7)
        else:
            self.make_move(self.p2, 2, 0, self.Pos7)

    def Pos8Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 2, 1, self.Pos8)
        else:
            self.make_move(self.p2, 2, 1, self.Pos8)

    def Pos9Click(self, Sender):
        if self.player_status == 1:
            self.make_move(self.p1, 2, 2, self.Pos9)
        else:
            self.make_move(self.p2, 2, 2, self.Pos9)

       

    def has_winner(self):
        winner = None
        for i in range(3):
            # Check row combos
            if self.board[i][0] != "" and self.board[i][0] == self.board[i][1] and self.board[i][1] == self.board[i][2]:
                winner = self.board[i][0]
               
            # Check column combos
            elif self.board[0][i] != "" and self.board[0][i] == self.board[1][i] and self.board[1][i] == self.board[2][i]:
                winner = self.board[0][i]

        # Check Diagonals
        if self.board[0][0] != "" and self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:
            winner= self.board[0][0]
        elif self.board[0][2] != "" and self.board[0][2] == self.board[1][1] and self.board[1][1] == self.board[2][0]:
            winner = self.board[0][2]

        if winner != None:
            if winner == "X":
                self.Status.Text = "Player 1 Won the Match"
            else:
                self.Status.Text = "Player 2 Won the Match"

            return True

    def ResetClick(self, Sender):
        self.board = [["", "", ""], 
                    ["", "", ""], 
                    ["", "", ""]]
        self.p1 = "X"
        self.p2 = "O"
        self.player_status = 1

        self.Pos1.Text = ""
        self.Pos2.Text = ""
        self.Pos3.Text = ""
        self.Pos4.Text = ""
        self.Pos5.Text = ""
        self.Pos6.Text = ""
        self.Pos7.Text = ""
        self.Pos8.Text = ""
        self.Pos9.Text = ""

        self.Status.Text = "Player "+ str(self.player_status) + " Move"

With this, our desktop application is ready, and you can run TicTacToeMain.py to play.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - editing the final screen

How to Build Tic-Tac-Toe As An Android Application Using PythonFMXBuilder?

The Delphi4Python Exporter exports the tic-tac-toe application with initialization logic for a desktop-based application. Therefore, we will use the PythonFMXBuilder to convert it to an Android app. Check out the instruction provided here to set up your PythonFMXBuilder application if you didn’t setup earlier.

So, open up PythonFMXBuilder and click on Project > New project on the toolbar. Enter the name of the project that you want to build here, which would be TicTacToe in this case.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - creating a new project

Before adding our Python files, we need to change some code to allow us to run our project on Android. Let’s create a new file named TicTacToeMain_Android.py and paste the contents of TicTacToeMain.py.

Next, add your Python files and any other supporting project files you used to build your application. Here we will not be adding TicTacToeMain.py as it will only be used to run our desktop application:

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the script

Next, right-click on TicTacToeMain_Android.py file and set it to the main file. But before we can build an .apk, let’s some important changes to our code.

First off, Android applications are initialized automatically by Delphi applications. Because the program will be initialized automatically, we don’t need to initialize it or set a title manually. The Application.MainForm doesn’t need to be initialized either but just needs a variable. Last but not least, similar to the initialization, we don’t need to launch or destroy the program because Android takes care of both tasks.

Here is what our TicTacToeMain_Android.py looks like:

from delphifmx import *
from TicTacToe import TicTacToeGUI

def main():
    Application.MainForm = TicTacToeGUI(Application)
    Application.MainForm.Show()

if __name__ == '__main__':
    main()
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the script in PythonFMX Builder

Save the file with the code changes you’ve just made.

We are now ready to convert our app to Android. PythonFMXBuilder gives developers three options for building applications: build, deploy, and run. You can learn more about these options by reading PythonGUI’s e-book. You can easily install the app on your mobile device thanks to PythonFMXBuilder. For the time being, we’ll use a .apk file to create an Android application. Click the Build Project button on the toolbar to create your file.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the build button

You will be prompted with a “Build process done” notification in the Messages box once the.apk has been entirely generated. Your generated file will be in the pathtoPythonFMXBuilderGUIexeFolderappsTicTacToebin folder.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - showing the location of the Android APK package

Just copy and paste this .apk file into your phone’s storage. If you access this file from your phone and click on it, you will be prompted with an installation message, which you should proceed with. Then, your tic-tac-toe game will be ready for usage.

Here is what our tic-tac-toe game looks like on an Android device:

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the app running on an Android phone

The following three screenshots illustrate the scenarios of either of the players winning and a tie.

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - the game in action!
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - Player 2 wins!
How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - more game play

Are you prepared to create your more apps using DelphiFMX?

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - a laptop on the download Delphi 11.3 screen

Congratulations on completing this tutorial. We hope that it has helped you realize how easy Python GUI development is when using the correct tools.

This tutorial demonstrated the effectiveness of Delphi for Android application development. We saw how DelphiFMX is a very powerful tool with a wide range of features and customization choices. Additionally, we demonstrated how the PyScripter makes Python programming even more enjoyable and simple. So if you want to learn more about Python GUI development, we recommended downloading the Python GUI getting started e-book to learn more about the features of Python GUI.

Now that you have seen how the right set of Python GUI tools can be used to create Android apps click here and install Delphi to start creating Python-based apps right away!

What are the FAQs regarding this topic?

How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem - a laptop showing an FAQ page

What is P4D?

A free set of components called Python for Delphi (P4D) integrates the Python DLL into Delphi. They make it simple to run Python programs and to develop new Python modules and types. Python extensions can be developed as DLLs, among other things.

What is an Android app?

Android Apps are software programs that are created to operate on an Android device or emulator. The acronym APK, which stands for Android package, is often used to refer to a file.

Why is PyScripter a popular IDE?

PyScripter began as a straightforward IDE that offered a robust scripting solution for Delphi programs. Over time, it developed into a fully functional stand-alone Python IDE. It was created in Delphi. However, Python scripts can be added using Python4Delphi (P4D). Because it is written in a compiled language, it is lightweight compared to other IDEs.

The Python interpreter and debugger, file explorer, project manager, and other features of PyScripter can all be used. In addition, it can be used for creating simple programs as well as in Quantum Chemistry, Machine Learning, and many other domains.

Can you build GUIs in Python?

It might be challenging to design a straightforward graphical user interface that is compatible with many platforms. However, this is not always the case. You and your users may design visually stunning user interfaces using Python and the DelphiFMX and DelphiVCL packages from Embarcadero!

The post How To Create A Tic-Tac-Toe Game Using Delphi Python EcoSystem first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-tic-tac-toe-game-using-delphi-python-ecosystem/feed/ 0 9497
How To Write A Simple Todo Gui Application Using Delphifmx https://pythongui.org/how-to-write-a-simple-delphi-python-gui-todo-app/ https://pythongui.org/how-to-write-a-simple-delphi-python-gui-todo-app/#respond Tue, 28 Feb 2023 13:40:36 +0000 https://pythongui.org/?p=9423 A graphical user interface (GUI) is an essential part of any application that allows users to interact with the program and perform necessary actions easily. Python is a powerful popular programming language widely used to...

The post How To Write A Simple Todo Gui Application Using Delphifmx first appeared on Python GUI.

]]>
A graphical user interface (GUI) is an essential part of any application that allows users to interact with the program and perform necessary actions easily. Python is a powerful popular programming language widely used to create different types of applications. However, it is intended mainly for writing backend code and generally does not have simple tools for creating a user interface. Therefore, if you need to create a GUI in Python, you should use our best Python GUI tools on the market.

This article will explain how to use the RAD Studio with Delphi Community Edition to design the application’s GUI. Then we will export created GUI using Delphi4PythonExporter and add functionality to the created application’s UI using the DelphiFMX package for Python. When we have finished, we will have created a fully working Python program with a really slick and professional GUI or graphical user interface.

What is DelphiFMX?

DelphiFMX is a Python package that provides Python developers with access to the FireMonkey (FMX) GUI framework of the Delphi programming language. It is freely redistributable and supports GUI application development for Windows, MacOS, Linux, and Android. DelphiFMX for Python does not require Delphi or any prior knowledge of Object Pascal.

What is Delphi4PythonExporter?

With the Delphi4PythonExporter extension, Python developers can use the design features of the Delphi IDE, such as drag and drop editor, preview, styles, event method binding, etc. They can use Delphi to build great programs and then offer Python implementations of them. It allows them to create an open-source GUI in Python without writing a single line of design code in Python.

How to create a TODO application using these tools?

Let’s create a simple GUI application where users can create a list of TODO tasks, add tasks to the list, and review and delete them.

What are the requirements to create this project?

To create a Python GUI TODO application using this tutorial, we need to install Delphi IDE – Delphi Comunity Edition, DelphiFMX package, and Delphi4PythonExporter.

Read the following GUI project setup article to learn how to install these tools.

How to create a project in Delphi?

First, open Delphi Community Edition and create a blank application (click File -> New -> Multi-Device Application).

How To Write A Simple Todo Gui Application Using Delphifmx - creating a new project

In the dialog box that opens, select Blank Application and click OK.

How To Write A Simple Todo Gui Application Using Delphifmx - creating a blank application

After that, a project with a default name will be created. We can change the name by clicking File -> Save As. Afterward, we should select the directory to save the project, enter a name, and click Save. After creating the project, a UI designer will open a form on which we can place other components. To change the form’s name, select the form, and in the Object Inspector, find the Name property and enter the desired name.

How To Write A Simple Todo Gui Application Using Delphifmx - using the object inspector

How do I add visual components to my Delphi form?

Now let’s add visual components to the form. All visual components are located in the Palette panel. Expand the Standard tab and drag the TLabel, TEdit, TListBox, and two TButton components onto the form.

How To Write A Simple Todo Gui Application Using Delphifmx - adding visual components to a screen form

We can change the position and size of the components using the WYSIWYG graphic designer or select the required component and change the desired property in the Object Inspector. In addition, we can also change borders, color, font, title, displayed text, and many other properties of visual components. Depending on the type of component, the properties may vary.

How To Write A Simple Todo Gui Application Using Delphifmx - an example screen

After we have placed all the visual components on the form, double-click the Add task and Delete task buttons to generate procedures to handle events by clicking those buttons automatically. Add comment lines to them to preserve those empty event methods.

5-5831750

How to export the Delphi project to a Python script?

Once our project’s GUI is ready, we can export it to Python.

Click Tools -> Export to Python -> Export Entire Current Project.

How To Write A Simple Todo Gui Application Using Delphifmx - exporting the project to Python

Fill in the Application Title and Application Directory in the dialog box and click Export. After that, two Python files will be created:

  • The first file contains the application initialization.
  • The second file contains form logic. Also, a form file .pyfmx will be created.
How To Write A Simple Todo Gui Application Using Delphifmx - the Python export form

If the export is successful, a corresponding message will appear.

What files were created during export?

During export, two Python files should have been created: MyTestProject.py and TestUnit.py. The MyTestProject.py is the main Python file, and its code contains the following:

from delphifmx import *
from TestUnit import TestForm

def main():
    Application.Initialize()
    Application.Title = 'MyTestProject'
    Application.MainForm = TestForm(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

In the main() function, the application is initialized using the Application.Initialize() method. The application is then given a title and specifies that the main form / main window is the TestForm class from TestUnit.py file:

Application.Title = 'MyTestProject'
Application.MainForm = TestForm(Application)
Application.MainForm.Show()

Then the application is run using the Application.Run() method. Finally, after the program is closed, the Application.MainForm.Destroy() method is executed, which releases all the resources occupied by the program.

To get a detailed understanding of the above code, please go through the free eBook bundle that we developed. This eBook explains the ideology around Delphi-Python EcoSystem, all Python GUI offerings, and much more.

image-1412714-2407127

The generated TestUnit.py file code looks like the following:

import os
from delphifmx import *

class TestForm(Form):

    def __init__(self, owner):
        self.taskEdit = None
        self.Label1 = None
        self.btnAdd = None
        self.btnDelete = None
        self.listBox = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TestUnit.pyfmx"))

    def btnAddClick(self, Sender):
        pass

    def btnDeleteClick(self, Sender):
        pass

In this file, all form components are initialized. Also, there are empty event methods btnAddClick and btnDeleteClick that handle the events of pressing buttons on the form. Since these methods are empty so far, the buttons will not work when the program is launched. To run the application GUI, you need to execute the MyTestProject.py file.

How do I add logic to my app?

Now we can add operation logic using the DelphiFMX Python package. For working with Python code, we can use the popular open-source Python IDE PyScripter.

When we click the Add button, we should check if the text field is not empty – if self.taskEdit.Text != ''. If so, the entered text will be added to the TODO list – self.listBox.Items.Add(self.taskEdit.Text) and the text field will be cleared – self.taskEdit.Text = ''.

def btnAddClick(self, Sender):
         if self.taskEdit.Text != '':
             self.listBox.Items.Add(self.taskEdit.Text);
             self.taskEdit.Text = '';

To delete an item/task from the TODO list, select it and click the Delete Task button. In the deletion procedure, we must first determine the index of the chosen record – index = self.listBox.ItemIndex. If it is greater than or equal to 0 - if index >= 0 (which means there is a selected entry) then we delete it self.listBox.Items.Delete(index).

def btnDeleteClick(self, Sender):
        index = self.listBox.ItemIndex
        if index >= 0:
            self.listBox.Items.Delete(index)

The modified TestUnit.py code looks like the following:

import os
from delphifmx import *

class TestForm(Form):

    def __init__(self, owner):
        self.taskEdit = None
        self.Label1 = None
        self.btnAdd = None
        self.btnDelete = None
        self.listBox = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "TestUnit.pyfmx"))

    def btnAddClick(self, Sender):
         if self.taskEdit.Text != '':
             self.listBox.Items.Add(self.taskEdit.Text);
             self.taskEdit.Text = '';

    def btnDeleteClick(self, Sender):
        index = self.listBox.ItemIndex
        if index >= 0:
            self.listBox.Items.Delete(index)

Now we can run and test the created application by running the MyTestProject.py file.

How To Write A Simple Todo Gui Application Using Delphifmx - the running ToDo app

Do you want to create your own Python GUI application?

This article taught you how to easily create GUIs in Python using the best Python GUI tools. You can use the DelphiFMX Python package to create Python-based GUI applications. Also, use Delphi IDE and Delphi4PythonExporter add-ons to become more efficient and scale your applications.

The post How To Write A Simple Todo Gui Application Using Delphifmx first appeared on Python GUI.

]]>
https://pythongui.org/how-to-write-a-simple-delphi-python-gui-todo-app/feed/ 0 9423
How To Create A Currency Converter Application Using Delphi Python EcoSystem https://pythongui.org/how-to-create-a-currency-converter-application-using-delphi-python-ecosystem/ https://pythongui.org/how-to-create-a-currency-converter-application-using-delphi-python-ecosystem/#respond Fri, 10 Feb 2023 11:00:00 +0000 https://pythongui.org/?p=9261 A GUI is a valuable part of software application programming regarding human-computer interaction, replacing text-based commands with user-friendly actions. Therefore, knowing how to develop GUI applications as an experienced Python developer will be helpful. So,...

The post How To Create A Currency Converter Application Using Delphi Python EcoSystem first appeared on Python GUI.

]]>
A GUI is a valuable part of software application programming regarding human-computer interaction, replacing text-based commands with user-friendly actions. Therefore, knowing how to develop GUI applications as an experienced Python developer will be helpful. So, if you want to learn how to make stunning GUI applications using Python, you have come to the right place! In this post, you will learn how to build a simple Currency Converter Android application with the help of some of the best Python GUI tools on the market.

Last time, we created a Currency Converter GUI application using the plain DelphiFMX python package. In this tutorial, we want to build the same application for Android devices by leveraging other tools and products like Delphi4PythonExporter, Delphi Community Edition, and PythonFMXBuilder in the Delphi-Python EcoSystem.

What is DelphiFMX?

DelphiFMX is a Python package that is natively compiled and powered by the Python4Delphi library. It is freely redistributable and provides Python developers access to the Delphi programming language’s FireMonkey (FMX) GUI framework. GUI development for Windows, MacOS, Linux, and Android is supported.

Embarcadero Delphi’s FireMonkey (FMX) is a graphical user interface framework for native cross-platform application development. For hardware-accelerated rendering, it makes use of the GPU via DirectX or OpenGL. It has a robust styling system and is user-extensible. DelphiFMX for Python does not require Delphi or any previous knowledge of Object Pascal.

What is Delphi4PythonExporter?

Delphi4PythonExporter is a critical offering for a thriving Python and Delphi ecosystem.

Python developers can use Delphi IDE’s flagship UI design capabilities to save time writing design code in Python. You can use a WYSIWYG preview, including styles, as you design. In addition, users can also use the features at design time to connect event methods to various events on the GUI application (for example, OnClick). Finally, Pythoneers can use the following approach to scale your large-scale Python GUI application.

Delphi developers can also benefit from the Exporter. They can use their Delphi skills to create great applications and then offer Python implementation of those applications, giving your new capabilities an entirely new dimension. This allows users to create open-source GUIs in Python without writing a single line of design code in Python.

What is PythonFMXBuilder?

The PythonFMXBuilder is an application builder for Python that uses DelphiFMX for Python to build and deploy Android applications. This allows you to bundle a custom Python script into an Android app, deploy it to your phone, and then you can submit it to the app store as per the requirement.

How can you create a currency conversion application for Android using these tools?

How To Create A Currency Converter Using PythonGUI

Let’s create a simple currency converter for Android where a user can provide the desired currency and the amount in that currency. The application would then output the exchange amount in a defined currency.

What are the requirements to complete this task?

For this tutorial, you will need Python, DelphiFMX, PythonFMXBuilder, Delphi4PythonExporter, Delphi, and any text editor or IDE that supports Python (PyScripter is recommended). In addition, you will also need a basic understanding of Python and Delphi, so we recommend checking out this article on mixing Python and Delphi.

If you don’t have these tools installed on your PC, check out this Powerful Python GUI Project Setup article to get started.

You can grab the code for this tutorial from our Git repository at: https://github.com/Embarcadero/PythonBlogExamples/tree/main/Currency_Converter_GUI_With_Exporter

How to create a form in Delphi?

Open Delphi CE and create a blank application (File > New > Multi-Device Application > Blank Application > Ok). This will open up a new project for you with a blank form. We have named our Delphi unit as CurrencyConverter.pas and the project as CurrencyConversion.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - a screenshot of the RAD Studio IDE with the app in it

Since we want to create a currency converter application, we should add some combo boxes – TCombobox and text boxes – TEdit, from the standard palette where the user can add their desired currencies and the amount they want to convert.

2-3183770

It is important to add labels – TLabel, with each combo box and text box. We even need to add a button – TButton, which when clicked, will calculate the currency conversion amount.

Next, rename the text of each label by right-clicking on that label and selecting Quick Edit.

How To Create A Currency Converter  - Application Using Delphi Python EcoSystem - selecting quick edit
How To Create A Currency Converter Application Using Delphi Python EcoSystem - editing the label name

For instance, above, we have a label whose Name is FromLabel since the label will only have Text "From".

Similarly, rename the Buttons with intuitive names that will help us program them later. In our case, we are editing the Name and Text of the button to Convert.

In addition, we rename our Form to CurrencyConverterApp using Quick Edit.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - naming the CurrencyConvertor application

This is what our Form looks like:

How To Create A Currency Converter Application Using Delphi Python EcoSystem - the form

We can even add some color to the Form’s background by selecting the Form’s fill property from the Object Inspector. After these changes, our form will look much more visually attractive:

How To Create A Currency Converter Application Using Delphi Python EcoSystem - how to change the form color
How To Create A Currency Converter Application Using Delphi Python EcoSystem - the form, with a different background

Since we are creating an Android app, let’s even view our form as it would appear on an Android device by changing the Style from Windows to Android:

How To Create A Currency Converter Application Using Delphi Python EcoSystem - changing the target to Android

This will change the appearance of our form:

How To Create A Currency Converter Application Using Delphi Python EcoSystem - the form

Then as we double-click on that button, we have added to our form, a ConvertClick event gets created with the code for its event method being added to the CurrencyConverter.pas that corresponds to our CurrencyConverter.fmx form.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - the RAD Studio IDE showing the currency convertor app

In the event method, you must type at least a single comment (//). This will ensure the method remains as we save the file. There is no need to write any run-time implementation code because we don’t export the run-time implementation using the Delphi4PythonExporter.

How to export the Delphi form as a Python Script?

You can now convert and save this form as a Python script by selecting Tools > Export To Python > Export Current Entire Project.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - exporting the app to Python

Delphi generates the Python scripts (CurrencyConverter.py and CurrencyConversion.py) in your chosen directory. You can optionally rename CurrencyConversion.py to CurrencyConverterMain.py. With this, there is a .fmx form that contains all the form’s visual information.

The generated code of CurrencyConverterMain.py is as follows:

from delphifmx import *
from CurrencyConverter import CurrencyConverterApp

def main():
    Application.Initialize()
    Application.Title = 'CurrencyConverter'
    Application.MainForm = CurrencyConverterApp(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

To get a detailed understanding of the above code, please go through the free eBook bundle that we developed. This eBook explains the ideology around Delphi-Python EcoSystem, all Python GUI offerings, and much more.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - get a free Python e-book

Now, let’s look at the contents of CurrencyConverter.py, where we will write the logic of our application:

import os
from delphifmx import *

class CurrencyConverterApp(Form):

    def __init__(self, owner):
        self.FromAmount = None
        self.Currency1 = None
        self.Amount1 = None
        self.Currency2 = None
        self.Amount2 = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromCurrency = None
        self.ToCurrency = None
        self.ToAmount = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "CurrencyConverter.pyfmx"))

    def ConvertClick(self, Sender):
        pass

How to run your currency converter using the generated Python script?

Note that in the above code, the method CurrencyClick is empty with a pass statement. Therefore, we first need to add functionality to this button such that when a user has provided two currencies and the desired conversion amount of one of the currencies and then clicks on this button, it will display the converted amount at the appropriate place.

How to add functionality to the convert button?

To add a currency conversion logic, we first build a nested dictionary. The data dictionary is the code below that provides a map between the given currencies. For example, you may want to check the conversion rate from USD to GIP. To do this, check the data['USD']['GIP'] to find the worth of USD $1 in GIP. Next, we populate our combo boxes with the items in our nested dictionary. We do this by appending the keys of the dictionary to the Items of the combo boxes. Here is what our final __init__() function looks like:

def __init__(self, owner):
        self.data = {
                "USD":{"EUR":0.96, "CAD":1.34, "CHF":0.95, "GBP":0.84, "OMR":0.39, "GIP":0.85, "KYD":0.84, "JOD":0.71, "BHD":0.38, "KWD":0.31},
                "EUR":{"USD":1.04, "CAD":1.39, "CHF":0.98, "GBP":0.87, "OMR":0.40, "GIP":0.87, "KYD":0.87, "JOD":0.74, "BHD":0.36, "KWD":0.32},
                "CAD":{"EUR":0.72, "USD":0.75, "CHF":0.71, "GBP":0.63, "OMR":0.29, "GIP":0.64, "KYD":0.63, "JOD":0.53, "BHD":0.28, "KWD":0.23},
                "CHF":{"EUR":1.02, "CAD":1.41, "USD":1.06, "GBP":0.89, "OMR":0.41, "GIP":0.90, "KYD":0.88, "JOD":0.75, "BHD":0.40, "KWD":0.33},
                "GBP":{"EUR":1.15, "CAD":1.59, "CHF":1.13, "USD":1.19, "OMR":0.46, "GIP":1.00, "KYD":1.00, "JOD":0.84, "BHD":0.45, "KWD":0.37},
                "OMR":{"EUR":2.50, "CAD":3.47, "CHF":2.46, "GBP":2.18, "USD":2.60, "GIP":2.32, "KYD":2.17, "JOD":1.84, "BHD":0.98, "KWD":0.80},
                "GIP":{"EUR":1.15, "CAD":1.59, "CHF":1.13, "USD":1.19, "OMR":0.46, "GBP":1.00, "KYD":1.00, "JOD":0.84, "BHD":0.45, "KWD":0.37},
                "KYD":{"EUR":1.15, "CAD":1.59, "CHF":1.13, "USD":1.19, "OMR":0.46, "GIP":1.00, "GBP":1.00, "JOD":0.84, "BHD":0.45, "KWD":0.37},
                "JOD":{"EUR":1.36, "CAD":1.88, "CHF":1.33, "GBP":1.19, "OMR":0.45, "GIP":1.19, "KYD":0.43, "USD":1.41, "BHD":0.53, "KWD":0.43},
                "BHD":{"EUR":2.56, "CAD":3.54, "CHF":2.51, "GBP":2.23, "OMR":1.02, "GIP":2.24, "KYD":0.82, "JOD":1.88, "USD":2.65, "KWD":0.82},
                "KWD":{"EUR":3.13, "CAD":4.34, "CHF":3.07, "GBP":2.73, "OMR":1.25, "GIP":2.73, "KYD":2.72, "JOD":2.30, "BHD":1.22, "USD":3.25}
            } # Currency conversion data recorded on 7th Nov 2022
        self.FromAmount = None
        self.Currency1 = None
        self.Amount1 = None
        self.Currency2 = None
        self.Amount2 = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromCurrency = None
        self.ToCurrency = None
        self.ToAmount = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "CurrencyConverter.pyfmx"))

        # Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromCurrency.Items.append(key)
            self.ToCurrency.Items.append(key)

Next, we extract the data from the text box – FromAmount defined for the input currency and use it to calculate the conversion. Here is what our CurrencyClick method looks like:

def ConvertClick(self, Sender):
        given = self.FromCurrency.Selected.Text
        to = self.ToCurrency.Selected.Text
        amountGiven = int(self.FromAmount.Text)
        amountCalculated  = self.data[given][to] * amountGiven
        self.ToAmount.Text = round(amountCalculated, 2)

You should also know that Delphi4Python Exporter exports the application initialization logic for a desktop-based application by default. Therefore, we need adjustments in Android’s app code compared to the desktop application code.

Our current application uses a Python dictionary to store a specific date’s conversion ratios. Instead, you can get real-time data on all the available currencies and exchange rates using APILayer’s Exchange Rates Data API. We have demonstrated currency conversion using API in one of our previous articles.

So your final CurrencyConverter.py should look like this:

import os
from delphifmx import *

class CurrencyConverterApp(Form):

    def __init__(self, owner):
        self.data = {
                "USD":{"EUR":0.96, "CAD":1.34, "CHF":0.95, "GBP":0.84, "OMR":0.39, "GIP":0.85, "KYD":0.84, "JOD":0.71, "BHD":0.38, "KWD":0.31},
                "EUR":{"USD":1.04, "CAD":1.39, "CHF":0.98, "GBP":0.87, "OMR":0.40, "GIP":0.87, "KYD":0.87, "JOD":0.74, "BHD":0.36, "KWD":0.32},
                "CAD":{"EUR":0.72, "USD":0.75, "CHF":0.71, "GBP":0.63, "OMR":0.29, "GIP":0.64, "KYD":0.63, "JOD":0.53, "BHD":0.28, "KWD":0.23},
                "CHF":{"EUR":1.02, "CAD":1.41, "USD":1.06, "GBP":0.89, "OMR":0.41, "GIP":0.90, "KYD":0.88, "JOD":0.75, "BHD":0.40, "KWD":0.33},
                "GBP":{"EUR":1.15, "CAD":1.59, "CHF":1.13, "USD":1.19, "OMR":0.46, "GIP":1.00, "KYD":1.00, "JOD":0.84, "BHD":0.45, "KWD":0.37},
                "OMR":{"EUR":2.50, "CAD":3.47, "CHF":2.46, "GBP":2.18, "USD":2.60, "GIP":2.32, "KYD":2.17, "JOD":1.84, "BHD":0.98, "KWD":0.80},
                "GIP":{"EUR":1.15, "CAD":1.59, "CHF":1.13, "USD":1.19, "OMR":0.46, "GBP":1.00, "KYD":1.00, "JOD":0.84, "BHD":0.45, "KWD":0.37},
                "KYD":{"EUR":1.15, "CAD":1.59, "CHF":1.13, "USD":1.19, "OMR":0.46, "GIP":1.00, "GBP":1.00, "JOD":0.84, "BHD":0.45, "KWD":0.37},
                "JOD":{"EUR":1.36, "CAD":1.88, "CHF":1.33, "GBP":1.19, "OMR":0.45, "GIP":1.19, "KYD":0.43, "USD":1.41, "BHD":0.53, "KWD":0.43},
                "BHD":{"EUR":2.56, "CAD":3.54, "CHF":2.51, "GBP":2.23, "OMR":1.02, "GIP":2.24, "KYD":0.82, "JOD":1.88, "USD":2.65, "KWD":0.82},
                "KWD":{"EUR":3.13, "CAD":4.34, "CHF":3.07, "GBP":2.73, "OMR":1.25, "GIP":2.73, "KYD":2.72, "JOD":2.30, "BHD":1.22, "USD":3.25}
            } # Currency conversion data recorded on 7th Nov 2022
        self.FromAmount = None
        self.Currency1 = None
        self.Amount1 = None
        self.Currency2 = None
        self.Amount2 = None
        self.Title = None
        self.FromLabel = None
        self.ToLabel = None
        self.Convert = None
        self.FromCurrency = None
        self.ToCurrency = None
        self.ToAmount = None
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "CurrencyConverter.pyfmx"))

        # Load the currencies in key values of the self.data dictionary into the FromCurrency and ToCurrency combo boxes
        for key in self.data.keys():
            self.FromCurrency.Items.append(key)
            self.ToCurrency.Items.append(key)

    def ConvertClick(self, Sender):
        given = self.FromCurrency.Selected.Text
        to = self.ToCurrency.Selected.Text
        amountGiven = int(self.FromAmount.Text)
        amountCalculated  = self.data[given][to] * amountGiven
        self.ToAmount.Text = round(amountCalculated, 2)

Let’s run the CurrencyConverterMain.py file and check if it’s working well on the Desktop before converting it into an Android application.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - the app as it appears when it runs

How to run the currency converter as an Android application using PythonFMXBuilder?

Delphi4Python Exporter exports the application initialization logic for a desktop-based application by default, and PythonFMXBuilder will ship the application we have created to an Android app. But before we can export our application to Andriod, we need to make minor code adjustments. 

Firstly, we don’t need the application initialization or to set a title because the Android application is a Delphi application and will be initialized automatically. Furthermore, we don’t need to set the Application.MainForm, but need a variable for the Form. Lastly, we don’t need to run or destroy the application because Android will take care of the application life cycle.

So, we have to make changes to CurrencyConverterMain.py file accordingly for it to be installed as an Android app.

Now let’s save our modified file as CurrencyConverterMain_Android.py and is shown below:

from delphifmx import *
from CurrencyConverter import CurrencyConverterApp

def main():
    Application.MainForm = CurrencyConverterApp(Application)
    Application.MainForm.Show()

if __name__ == '__main__':
    main()

Now, save the changes made above. Then open the PythonFMXBuilder application and click Project > New project on the toolbar. Enter the name of the project that you want to build here.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - the PythonFMXBuilder options

Add your Python files and any other supporting project files that you use to create your application by selecting File > Add File. One of the best practices is to take a modular approach to build your application where we can write all the logic/implementations in separate Python files and call them from the main Python file just like we did above:

How To Create A Currency Converter Application Using Delphi Python EcoSystem - setting the main form

Here, we’re setting the CurrencyConverterMain_Android.py to the main file from our two script files by right-clicking on the file and selecting the option.

Now, we are all set to build and deploy our app to Android device. PythonFMXBuilder provides three options for developers to build applications, namely:

  • Build,
  • Deploy
  • Run

To learn more about these options, download and read PythonGUI’s ebook.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - click to download a free e-book

To get the app up and running on your phone, you must first enable USB debugging on your Android device. To do so, on your Android device, go to Settings > About Phone > Version and tap on the Build Number a few times. It displays a message that says, “You are now a developer.” Then, in Developer Options, enable USB Debugging.

Connect your phone to the PC with a USB cable/cord now. Allow “USB Debugging” permission by hitting Allow. Then, in the upper right corner of your FMXBuilder window, click the Reload button image-9717684 to load the list of devices, and then choose the first device using the “Load Devices” button. Click the Run button to execute Build, Deploy, and Launch. So your app will launch soon on your connected Android device.

How To Create A Currency Converter Application Using Delphi Python EcoSystem - running the project

Let’s go ahead and test this app. If everything is set up correctly, then you should click on the Convert button, and this will convert the given amount as per the exchange rate/ratio of the selected currency trading pair:

How To Create A Currency Converter Application Using Delphi Python EcoSystem - the app running
How To Create A Currency Converter Application Using Delphi Python EcoSystem - alternate view

Wow! Now, currency conversions are at your fingertips.

Are you ready to create your own applications using PythonGUI?

How To Create A Currency Converter Application Using Delphi Python EcoSystem - a laptop showing the download screen for Delphi CE

Well done on reaching the end of this tutorial! Hopefully, this has been an eye-opener for you regarding how simple it is to build Python GUIs with the correct toolkit. We have seen how Python bindings for Delphi GUI libraries are essential for the Python GUI developer community.

Furthermore, Delphi Community Edition is a very important tool. It includes a streamlined IDE, code editor, integrated debugger, award-winning visual designers to speed development, powerful data access and binding technologies, hundreds of visual components, and a limited commercial use license.

Now that you have seen how the PythonFMXBuilder is used for deploying your Python scripts on Android and the Delphi4PythonExporter to simplify your UI design, click here and install Delphi to start creating Python-based apps right away!

What are the FAQs surrounding this topic?

How To Create A Currency Converter Application Using Delphi Python EcoSystem - a laptop showing an FAQ section

What is Embarcadero?

Embarcadero is a subsidiary of Idera, Inc. Idera, Inc., the parent company of global B2B software productivity brands whose solutions enable technical users to do more with less and less time.

Embarcadero tools are designed for the world’s most elite developers who create and maintain the world’s most critical applications. Our customers choose Embarcadero because we are the developer champion, assisting them in developing more secure and scalable enterprise applications faster than any other tool on the market. For over 30 years, Embarcadero’s award-winning products have been relied on by ninety of the Fortune 100 and an active community of more than three million users worldwide.

What is APILayer?

APILayer is the leading provider of off-the-shelf, cloud-based API products designed to assist developers and businesses worldwide to operate efficiently and effectively. Organizations of all sizes struggle to support complex digital transformations and the increasing demand for connectivity and real-time data. APILayer does precisely that!

What is Delphi?

Delphi is a high-level programming language that supports an object-oriented paradigm. It is a Rapid Application Development (RAD) paradigm that can create applications ranging from database solutions to mobile applications. Delphi is now widely regarded as the quickest way to develop, compile, package, and deploy cross-platform native applications for Windows, macOS, iOS, Android, and Linux.

What features does PyScripter have?

PyScripter is an Integrated development environment (IDE) for Python that is free and open source. It was created using Delphi’s Object Pascal and Python.

It began as a lightweight IDE to provide a powerful scripting solution for Delphi applications. It evolved into a full-featured stand-alone Python IDE. It is written in Delphi using Python4Delphi (P4D) and can be extended with Python scripts. Because it is written in a compiled language, it is relatively light compared to other IDEs. PyScripter functions as a syntax highlighting editor, Python interpreter and debugger, file explorer, project manager, and many others.

The post How To Create A Currency Converter Application Using Delphi Python EcoSystem first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-currency-converter-application-using-delphi-python-ecosystem/feed/ 0 9261
How To Get Started With Python GUI Development? https://pythongui.org/how-to-get-started-with-python-gui-development/ https://pythongui.org/how-to-get-started-with-python-gui-development/#respond Mon, 30 Jan 2023 11:00:00 +0000 https://pythongui.org/?p=9553 Third-party development packages/frameworks are made to simplify a developer’s job. They facilitate the development of a specific type of application or the use of a specific language. Instead of manually coding the user interface in...

The post How To Get Started With Python GUI Development? first appeared on Python GUI.

]]>
Third-party development packages/frameworks are made to simplify a developer’s job. They facilitate the development of a specific type of application or the use of a specific language. Instead of manually coding the user interface in Python, a Graphical User Interface (GUI) framework for Python makes the process much simpler.

This article will serve as a basic introduction to an e-book that covers all the tools a developer should know about when starting with Python GUI development. So, let’s get started.

Who should read the e-book?

How To Get Started With Python GUI Development? A laptop showing hte Python tools download page

The DelphiFMX and DelphiVCL Python libraries are created using Embarcadero’s Delphi programming language and toolkit. Fortunately, using the libraries is simple for Python developers and doesn’t require prior knowledge or expertise with Delphi. The “Getting Started With Python GUI” e-book is for you if you’re a Python developer and want to build excellent user interfaces.

However, Delphi developers who desire an introduction to Python coding can also benefit from the manual. Along with this book, the DelphiVCL and DelphiFMX libraries should make it easier for you to design stunning graphical user interfaces for your Python projects.

How To Get Started With Python GUI Development? An infographic inviting you to download the Python GUI ebook

How to compare Python and Delphi?

This book mostly discusses Python programming, although it also covers Delphi as a library source. You don’t have to pick one over the other. Both are effective programming languages, and a programmer can carry a variety of them in their toolbox, allowing them to choose the best one for the job.

What is Delphi for Python?

The main goal of Delphi for Python is to give Python programmers access to free Python bindings for Delphi’s GUI frameworks. Delphi’s two distinct frameworks, VCL and FMX constitute the foundation for two Python packages: DelphiVCL, a native library for Windows, and DelphiFMX, a multiplatform GUI development library. This manual focuses on getting you going with them both.

The Python for Delphi library, which also powers the well-known PyScripter Python IDE, powers both the DelphiVCL and DelphiFMX packages. So, Python for Delphi serves as a two-way link between Python and Delphi, giving Delphi programmers access to all of Python’s features and providing Python programmers with Delphi libraries.

Both the packages are hosted at the Python package management-Pip and GitHub. Both Conda environments and older, prebuilt Python virtual environments are supported.

What is the History of Delphi and Python?

How To Get Started With Python GUI Development? Timeline for Delphi and Python infographic

Niklaus Wirth developed the Pascal programming language in 1970 to help teach students concepts such as structured programming and other useful techniques. The original Pascal gave rise to several variations. The ABC programming language was then created in 1987. Guido van Rossum spent some time working on the imperative general-purpose programming language ABC. He later created Python, ABC’s successor, in 1991. The Python language advanced with the introduction of Python 2.0 and Python 3 which is the version available at the time of writing.

As Pascal’s replacement, Delphi, an Object Pascal dialect, was introduced in 1995. This initial release comprised VCL, Delphi, and a graphical user interface (GUI) framework.

Not content with its huge success on the Windows platform Delphi briefly had a Linux target as early as 2001 in the form of Kylix although it was eventually deprecated due to technical challenges. However, Delphi still continued to push the goal of expanding beyond the Windows system and added strong Mac support in 2011 followed closely by the excellent FireMonkey GUI framework for cross-platform compatibility. In 2013, Delphi added support for iOS and Android and further built on that by adding support for the ARM compiler. Then, Embarcadero launched Delphi Tokyo in 2017 with renewed high-quality support for Linux adding in full Linux GUI apps and Windows Subsystem for Linux (WSL) support too.

Are you ready to start developing Python GUIs?

How To Get Started With Python GUI Development? A person looking at a laptop screen showing part of the Python GUI Ebook

Your application’s GUI makes a first impression. Making a positive first impression is essential if you want to be successful. The fact that so many frameworks are available in Python is just one of the reasons the programming language is so well-liked for GUI programming. Embarcadero’s Delphi for Python frameworks are very well-liked and appropriate for beginners, even though numerous solutions are accessible for developers with various and distinctive tastes.

Now that you know what to expect from this amazing e-book, click here to download it and learn more about Python GUI development easily!

What are some FAQs regarding Python GUI?

How To Get Started With Python GUI Development? A person typing at a laptop showing the PyScripter IDE on the screen

What is a GUI?

Instead of text-based UIs, typed command labels, or text navigation, the GUI, or graphical user interface, enables users to interact with electronic devices by graphical icons and an auditory indicator.

What is Python?

Python is a high-level, all-purpose programming language. Code readability is prioritized in its design philosophy, which uses indentation heavily. Python uses garbage collection and has dynamic typing. It supports a variety of programming models, such as functional, object-oriented, and structured programming.

What are some Python GUI tools?

Several useful tools include PyScripter, Delphi Community Edition, Delphi FMX, Delphi VCL, and PythonFMXBuilder.

What is DelphiVCL?

The Visual Component Library (VCL) is a collection of visual components that enables the quick creation of Windows programs in the Delphi and C++ programming languages. Building Windows, online, database, and console applications are just a few activities that may be accomplished using the extensive range of visual, non-visual, and utility classes found in VCL.

What is DelphiFMX?

Delphi is a robust programming language that allows you to create high-performance programs despite its seeming simplicity. The app development and runtime platform that powers RAD Studio, Delphi, and C++Builder is called FireMonkey (sometimes known as FMX). It is made for development teams who want to quickly bring multi-device, native applications for Windows, OS X, Android, and iOS into app stores and businesses.

What kind of programs can you make using Delphi for Python?

You can create a currency converter, employee management service, other simple applications, and much more. The possibilities are endless.

The post How To Get Started With Python GUI Development? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-get-started-with-python-gui-development/feed/ 0 9553
How To Make A Python Script For Solving MP2 Equations https://pythongui.org/how-to-make-a-python-script-for-solving-mp2-equations/ https://pythongui.org/how-to-make-a-python-script-for-solving-mp2-equations/#respond Wed, 25 Jan 2023 11:00:00 +0000 https://pythongui.org/?p=9446 Recently, we showed the basics of quantum chemistry is, and how to do it using Python. This will be a continuation of it. In this article, we will discuss how to write a python script...

The post How To Make A Python Script For Solving MP2 Equations first appeared on Python GUI.

]]>
Recently, we showed the basics of quantum chemistry is, and how to do it using Python. This will be a continuation of it. In this article, we will discuss how to write a python script for solving mp2 equations. Make sure you check out the previous article to learn the very basics. 

The theory behind it requires years of studying quantum mechanics, mathematics, chemistry, and sometimes even some biology, and combining these fields together to study nature using computer models. This is not what we are going to do here! However, I can give you some hints about how a complicated problem can be made much easier using Python script. We are going to use the PySCF package to perform some calculations.

In the examples in the previous article, you can perform calculations of the energy of a molecule using the Hartree-Fock theory and using Density Functional Theory. These methods are very important and useful, though in some cases, one wants to get to the next level in terms of accuracy.

What is correlation energy?

After multiple approximations, it is possible to recover about 99% of the exact energy of a molecule. While it may sound excellent, the whole of chemistry is in the remaining 1%, which is also called correlation energy. Among the methods improving on this starting point (i.e., Hartree-Fock theory) is perturbation theory.

The name sounds funny and weird at the same time. You can think of something that disturbs the molecule a bit. But not too much. Let’s say the molecule is placed in a magnetic field. The interaction between them affects the energy and the properties of the molecule. They can be modelled by defining new parameters in the Schrödinger equation.

How To Make A Python Script For Solving MP2 Equations - an image of bubbles and stars

How to calculate the MP2 correlation energy?

If you read the previous article, you know that the electrons of atoms and molecules live in what we call orbitals. Within Hartree-Fock theory, we can model the orbitals using a set of mathematical functions called a basis set. There are coefficients telling what the weight of each basis function is. These coefficients are written in matrix form, which is called the Fock matrix.

After lots of mathematical operations, one obtains a set of equations that have to be solved. The solution gives the total energy of the molecule and optimises the orbital coefficients that give the best energy. However, these orbitals can be used as input in the perturbation theory approach. The most common method within it carries the names of two scientists – Møller–Plesset perturbation theory. It is usually truncated to the second order and abbreviated as MP2 for conciseness.

Here is an example of how to do it in practice using Python. We will use water as an example. First, we will define the coordinates, then specify the basis set and that the molecule is symmetric. Next, we have to run the Hartree-Fock calculation. Finally, we can also perform the MP2 calculation using the optimized wave function that was just calculated.

from pyscf import gto, scf, mp

mol = gto.Mole()

# defining the molecule
mol.atom = '''
O        -1.82473        1.24653       -0.01294
H        -0.85684        1.28190        0.01714
H        -2.10358        1.95337        0.58838'''

# specifying the basis set
mol.basis = 'ccpvdz'
mol.symmetry = 1
mol.build()

# Computational method
# Hartree-Fock theory
mf = mol.RHF().run()
# MP2
mf_mp2 = mp.MP2(mf).run()

The code above prints the Hartree-Fock energy, as well as the MP2 energy. Their difference is the MP2 correlation energy.

converged SCF energy = -76.0259881597798
E(MP2) = -76.2308195860744  E_corr = -0.204831426294622

A note about the units. Probably these numbers do not speak much to you. They are in what we call “atomic units”, also known as hartree units. It is a bit hard to give you a perspective about its magnitude in terms of everyday objects or phenomena, but I will try. If you are into tech, you might know that modern high-end CPUs run at less than 1.5 volts. 1 hartree is equal to about 27 electron-volts. Check out Wikipedia if you want to know more about the units of energy.

How To Make A Python Script For Solving MP2 Equations - a person at a data center

What do we mean by the computational cost of calculations?

The example for water finishes immediately. However, some quantum chemical calculations can take hours and even days. Improving the results using second-order perturbation theory involves using the orbitals obtained in a Hartree-Fock calculation. This approach is more accurate, but it is computationally heavy. It depends on the number of integrals that the program needs to calculate in order to reach the final result.

Why are quantum chemistry calculations so computationally heavy?

There are mathematical techniques that introduce some approximations which do not affect the accuracy significantly, but they speed up the calculations. They carry names such as density fitting and resolution of identity. The hardest part of the equations is solving two-electron integrals. Essentially, they depict the electrostatic repulsion between two electrons occupying two possible orbitals. We place electron 1 in orbital 1 and electron 2 in orbital 2. Then each of them is squared in the integral expression. The other set of two-electron integrals describes the so-called exchange interaction, which has no analogue in the macroscopic world. The two electrons are placed each in two different orbitals – electron 1 in orbital 1 and electron 2 in orbital 2. Then, their places are flipped – electron 1 goes to orbital 2, and electron 2 goes to orbital 1. Sounds simple, but the math behind it is very demanding.

How To Make A Python Script For Solving MP2 Equations - a person studying a laptop

How to simplify and speed up the calculations?

The two-electron integrals can be expanded using different functions called an auxiliary basis set. They give little penalty to the accuracy, but the speedup is quite good. Still, it is impossible to calculate a whole protein with millions of atoms using correlated quantum chemistry methods. They are usually performed using classical Newtonian mechanics, where the nuclei are moving in an electrostatic potential created by the electrons. But that is a story for another day.

How big molecules can be studied using MP2?

One little challenge would be to check how the number of atoms affects the speed of the calculation. Or more precisely, the number of electrons. A hydrogen atom only has one electron, but iron has 26. You can guess which one takes longer to calculate. You can test on your own how many seconds it takes to calculate water versus a big porphyrin molecule. Here are the coordinates of its atoms

mol.atom = '''
H 3.209599995 3.172309777 0.000000000
N 0.000000000 -2.113600613 0.000000000
N 2.031813914 0.000000000 0.000000000
N 0.000000000 2.113600613 0.000000000
N -2.031813914 0.000000000 0.000000000
C 1.126850920 -2.888627221 0.000000000
C -1.126850920 -2.888627221 0.000000000
C 1.126850920 2.888627221 0.000000000
C -1.126850920 2.888627221 0.000000000
C 2.850160984 -1.083939750 0.000000000
C 2.850160984 1.083939750 0.000000000
C -2.850160984 -1.083939750 0.000000000
C -2.850160984 1.083939750 0.000000000
C 0.683827200 -4.249372023 0.000000000
C -0.683827200 -4.249372023 0.000000000
C 0.683827200 4.249372023 0.000000000
C -0.683827200 4.249372023 0.000000000
C 4.248378966 -0.675836785 0.000000000
C 4.248378966 0.675836785 0.000000000
C -4.248378966 -0.675836785 0.000000000
C -4.248378966 0.675836785 0.000000000
C 2.433989580 -2.416542873 0.000000000
C -2.433989580 -2.416542873 0.000000000
C -2.433989580 2.416542873 0.000000000
C 2.433989580 2.416542873 0.000000000
H 1.341416542 -5.103998738 0.000000000
H -1.341416542 -5.103998738 0.000000000
H 1.341416542 5.103998738 0.000000000
H -1.341416542 5.103998738 0.000000000
H 5.096138011 -1.344322017 0.000000000
H 5.096138011 1.344322017 0.000000000
H -5.096138011 -1.344322017 0.000000000
H -5.096138011 1.344322017 0.000000000
H 3.209599995 -3.172309777 0.000000000
H -3.209599995 -3.172309777 0.000000000
H -3.209599995 3.172309777 0.000000000
H 0.000000000 -1.102285542 0.000000000
H 0.000000000 1.102285542 0.000000000'''

This is what the molecule looks like if you open it in a molecular viewer such as Avogadro.

How To Make A Python Script For Solving MP2 Equations - a molecule

What have we learned in this article?

Do you feel more of a quantum chemist after this article? No worries if you don’t. You can always learn more. There is an excellent implementation of a wide variety of quantum chemistry methods available in PySCF that you can test on your own, and you will learn more about it. How about you try some fancier molecule? You can do that in the PyScripter IDE. You can find installation instructions for PySCF inside PyScripter in the previous article about quantum chemistry.

PyScripter is available for download for free at https://www.embarcadero.com/free-tools/pyscripter/free-download

The post How To Make A Python Script For Solving MP2 Equations first appeared on Python GUI.

]]>
https://pythongui.org/how-to-make-a-python-script-for-solving-mp2-equations/feed/ 0 9446
How To Make a Powerful Delphi Python GUI Project Setup https://pythongui.org/how-to-make-a-powerful-delphi-python-gui-setup/ https://pythongui.org/how-to-make-a-powerful-delphi-python-gui-setup/#respond Mon, 23 Jan 2023 05:25:15 +0000 https://pythongui.org/?p=9476 A graphical user interface, more commonly known as a GUI, is an important component of software application programming for human-computer interaction, replacing text-based commands with user-interactive visual actions. With the aid of a GUI, users...

The post How To Make a Powerful Delphi Python GUI Project Setup first appeared on Python GUI.

]]>
A graphical user interface, more commonly known as a GUI, is an important component of software application programming for human-computer interaction, replacing text-based commands with user-interactive visual actions. With the aid of a GUI, users can perform operations on a device, platform, program, or application without having to type commands or comprehend the underlying coding. So, if you want to learn how to create stunning GUI applications using Python, you’ve come to the right place! In this article, we will look at how to set up a multiplatform Delphi-Python GUI project to build GUI applications using some of the best Python GUI tools on the market.

What are the essential requirements to create the Delphi Python GUI project setup?

If you want to create a Desktop GUI application for the multiplatform, the DelphiFMX Python package is the way, whereas the DelphiVCL Python package is the way to target the Windows platform only.

  • DelphiFMX – Python package to develop Multi-platform (Windows, GNU/Linux, macOS, Android) GUI applications.
  • DelphiVCL – Python package to develop Windows-only GUI applications.

What are DelphiFMX and DelphiVCL?

DelphiFMX and DelphiVCL are natively compiled Python packages that are powered by the Python4Delphi library. They’re free to use and distribute. They give Python developers access to Delphi’s rich and mature VCL and FireMonkey (FMX) GUI frameworks, which provides a simple way to create GUIs compatible across all platforms.

VCL by Embarcadero Delphi is a GUI framework for the Windows platform, whereas FireMonkey (FMX) is for native cross-platform application development that uses hardware-accelerated rendering via DirectX or OpenGL. Both of them have a strong styling system and are user-extensible.

How To Make a Powerful Delphi Python GUI Project Setup - the Delphi FMX page for Delphi-Python

How to Install DelphiFMX and DelphiVCL in Python?

The easiest way to install DelpiVCL and DelphiFMX Python packages is via PIP:

This is how to install DelphiFMX in Python

pip install delphifmx

This is how to install DelphiVCL in Python

pip install delphivcl

You can create your GUI applications using the above-mentioned Python packages without additional dependencies. However, as discussed below, we also provide additional tools for an easy and efficient way to create and scale your GUI applications.

What are the additional requirements to create the perfect Delphi Python GUI project setup?

Products and tools like Delphi IDE, Delphi4PythonExporterPythonFMXBuilder, and PyScripter allow Python developers to create all kinds of amazing professional quality applications easily.

To reduce the development time and for you to scale your GUI applications, we have built various tools:

  • Delphi IDE – Download the Delphi IDE to design the UI of GUI applications and take advantage of the WYSIWYG preview of the UI.
  • Delphi4PythonExporter – An open-source tool to export the UI designed in Delphi IDE to Python.
  • PythonFMXBuilder – An open-source application to build, debug and deploy DelphiFMX-based GUI applications for the Android platform. This is not needed if you want to target only desktop applications.
  • PyScripter – An open-source Python IDE to easily write code and run Python applications.

What is Delphi?

Delphi is an extremely powerful yet easy-to-learn object-oriented programming language. It has a Rapid Application Development (RAD) paradigm that can be used to create anything from database solutions to mobile applications. Delphi is noted for its ease of deployment of its apps, which do not require additional runtimes or dependencies, along with its robustness and single-source cross-platform capabilities. As a result, Delphi is widely regarded as the most efficient way to create, compile, package, and deploy cross-platform native applications for Windows, macOS, iOS, Android, and Linux.

How to install Delphi?

As a beginner, you have a few options to install the Delphi IDE. They are:

Delphi Community Edition is an excellent tool for creating visually appealing, high-performance native Delphi apps for Windows, macOS, iOS, and Android. To install this IDE, visit: embarcadero.com/products/delphi/starter. Then, complete the form, and the download will begin:

How To Make a Powerful Delphi Python GUI Project Setup - a Delphi-Python graphic on how to download the free community edition of Delphi

The Delphi Community edition is free, so the required product key will be emailed to you. So all you have to do is extract and install the IDE.

When you start to feel confident about working with Delphi using Community Edition, you can consider the Delphi Architect Edition Trail for 30 days to discover the full power of Delphi. To install the Delphi Trail, visit: embarcadero.com/products/delphi/start-for-free.

How To Make a Powerful Delphi Python GUI Project Setup - how to start for free with Delphi

What is Delphi4PythonExporter?

Delphi4PythonExporter, shortly known as D4PExporter, is a crucial offering for a thriving Python and Delphi ecosystem.

Python developers can use Delphi’s flagship UI design capabilities to save time writing design code in Python. They can use a WYSIWYG preview, including styles, as you design. In addition, users can also use the features at design time to connect event methods to various events on the GUI application (for example, OnClick). Finally, Pythoneers can use the following approach to scale your large-scale Python GUI application.

Delphi developers can also benefit from the Exporter. They can use their Delphi skills to create great applications and then offer Python implementation of those applications, giving your new capabilities and providing an entirely new dimension. This allows users to create open-source GUIs in Python without writing a single line of design code in Python.

How to Install Delphi4PythonExporter?

You can export the UI of either FMX (Multi-platform) or VCL (Windows only) applications. However, most importantly, you can take advantage of assigning empty event methods at design time using D4PExporter. This reduces the tedious work of coding the events and their associated methods in Python. As you export the UI designed in Delphi IDE, you will see this in action. Once you have Delphi installed, open the Delphi IDE, select Tools > GetIt Package Manager, and then search for Delphi4PythonExporter in the search bar of the pop-up window.

How To Make a Powerful Delphi Python GUI Project Setup - the GetIt package manager when using Delphi-Python

Click on the correct search result and hit Install. Restart Delphi IDE for changes to take effect. Now, whenever you select Tools in the Delphi IDE, you will also see an Export To Python option.

How To Make a Powerful Delphi Python GUI Project Setup - the Delphi4Python exporter tool for use with Delphi-Python

What is PythonFMXBuilder?

The PythonFMXBuilder is an application builder for Python that uses DelphiFMX for Python to build Android applications. This allows you to bundle a custom Python script into an Android app, deploy it to your phone, and then submit it to the app store as per the requirement.

How to Install PythonFMXBuilder?

While PythonFMXBuilder is made with Delphi, it does not require Delphi to use it.

To install/run the PythonFMXBuilder application, download the latest release (pre-built binaries are provided in releases) from PythonFMXBuilder’s GitHub repository. Download the latest release at: github.com/Embarcadero/PythonFMXBuilder/releases/tag/v0.7.0

Select your version and download. Here we will use the latest Windows 64-bit binary:

How To Make a Powerful Delphi Python GUI Project Setup - finding the binaries for the Delphi-Python work

Extract the .zip file and rename the folder to PythonFMXBuilder for simplicity.

Open the PythonFMXBuilderGUI.exe executable application in the extracted folder by double-clicking it.

How To Make a Powerful Delphi Python GUI Project Setup - the PythonFMXBuilder GUI location for use with Delphi-Python

Next, download, install, and set up the Android SDK using the wiki guide link provided in the repository. Do the same for Java JDK using its wiki guide:

How To Make a Powerful Delphi Python GUI Project Setup - instructions on how to install for Android and Delphi-Python

All these steps are provided in detail at: github.com/Embarcadero/PythonFMXBuilder/wiki/Step-by-step-guide-to-create-an-Android-application-using-PythonFMXBuilder

Now you’re all set with PythonFMXBuilder.

What is PyScripter?

How To Make a Powerful Delphi Python GUI Project Setup - the PyScripter download page used with Delphi-Python

PyScripter is a Python-integrated development environment (IDE) for Windows that is free and open source. It was created using Delphi’s Object Pascal and Python.

PyScripter started as a simple IDE to provide a powerful scripting solution for Delphi applications. It gradually evolved into a full-featured stand-alone Python IDE. It is written in Delphi and can be extended with Python scripts using Python4Delphi (P4D). It is relatively light compared to other IDEs because it is written in a compiled language. In addition, it is a portable IDE that can be used as a syntax highlighting editor, a Python interpreter and debugger, a file explorer, and a project manager, among other things. You can download the PyScripter from the following link: embarcadero.com/free-tools/pyscripter/free-download and install it.

Are you ready to build GUI applications using the Delphi Python Ecosystem?

This article covers both the essential and the ultimate workbench setup for building applications using The Delphi Python Ecosystem. Either you choose to go ahead with the minimal or the perfect setup that is mentioned above; we got you covered with an eBook to get you started. The eBook bundle contains the Getting Started with Python GUI development eBook, 15 DelphiFMX for Python Styles, and 13 DelphiVCL for Python styles. All styles support High DPI to help your applications look fantastic, and the DelphiFMX styles work seamlessly on all Windows, macOS, Linux, and Android platforms. The eBook covers the basics of programming Python with these libraries; no Delphi experience is necessary. So unlock your potential for excellent Python GUI development by downloading the eBook bundle at: lp.embarcadero.com/PythonGUIgettingStarted

How To Make a Powerful Delphi Python GUI Project Setup - click to get the free Python GUI e-book

The post How To Make a Powerful Delphi Python GUI Project Setup first appeared on Python GUI.

]]>
https://pythongui.org/how-to-make-a-powerful-delphi-python-gui-setup/feed/ 0 9476
What Is The Best Python Graph Tool? graph-tool vs NetworkX https://pythongui.org/what-is-the-best-python-graph-tool-graph-tool-vs-networkx/ https://pythongui.org/what-is-the-best-python-graph-tool-graph-tool-vs-networkx/#respond Wed, 18 Jan 2023 11:00:00 +0000 https://pythongui.org/?p=9324 What is graph-tool? graph-tool is a powerful Python script module for graph manipulation and statistical analysis (a.k.a. networks). In contrast to most other Python modules with similar functionality, the core data structures and algorithms are...

The post What Is The Best Python Graph Tool? graph-tool vs NetworkX first appeared on Python GUI.

]]>
What is graph-tool?

graph-tool is a powerful Python script module for graph manipulation and statistical analysis (a.k.a. networks). In contrast to most other Python modules with similar functionality, the core data structures and algorithms are written in C++, with extensive use of template metaprogramming and a heavy reliance on the Boost Graph Library. This gives it performance comparable to a pure C/C++ library (in terms of memory usage and computation time).

If you are looking for a decent introduction to basic knowledge in graph and network visualization, check out my article for Embarcadero Technologies here.

What Is The Best Python Graph Tool? graph-tool vs NetworkX - the graph-tool logo
graph-tool logo. Source: Reference [1].

Why graph-tool?

The following are the reasons why graph-tool might be the best network and graph visualization tools out there:

1. Fast

Most of the time, you can expect the algorithms to run just as fast as if graph-tool were a pure C/C++ library.

The following table shows brief performance comparisons between graph-tool and two other popular graph libraries with Python bindings, igraph and NetworkX [2]:

Algorithmgraph-tool (16 threads)graph-tool (1 thread)igraphNetworkX
Single-source shortest path0.0023 s0.0022 s0.0092 s0.25 s
Global clustering0.011 s0.025 s0.027 s7.94 s
PageRank0.0052 s0.022 s0.072 s1.54 s
K-core0.0033 s0.0036 s0.0098 s0.72 s
Minimum spanning tree0.0073 s0.0072 s0.026 s0.64 s
Betweenness102 s (~1.7 mins)331 s (~5.5 mins)198 s (vertex)+ 439 s (edge)(~ 10.6 mins)10297 s (vertex)13913 s (edge)(~6.7 hours)

Note: The test was performed by calling the functions several times, and calculating the average time taken per function call. The hardware used for this test is Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz with 8 cores and 16 threads. The results for graph-tool with OpenMP enabled using 16 threads are shown in the second column, and the results using only one thread are shown in the third column.

When OpenMP is disabled, both graph-tool and igraph appear to deliver comparable overall performance. Even in this case, graph-tool appears to be faster systematically.

2. OpenMP (Open Multi-Processing) support

Provides excellent performance on multi-core architectures, without degrading it on single-core machines.

3. Extensive features

Including an extensive array of features, such as support for arbitrary vertex, edge or graph properties, efficient “on the fly” filtering of vertices and edges, powerful graph I/O using the GraphML, GML and dot file formats, graph pickling, graph statistics (degree/property histogram, vertex correlations, average shortest distance, etc.), centrality measures, standard topological algorithms (isomorphism, minimum spanning tree, connected components, dominator tree, maximum flow, etc.), generation of random graphs with arbitrary degrees and correlations, detection of modules and communities via statistical inference, and much more.

4. Powerful visualization

Has its own layout algorithms and versatile, interactive drawing routines based on cairo and GTK+, but it can also work as a very comfortable interface to the excellent graphviz package.

5. Well documented

Every single function in the module is documented in the docstrings and in the online documentation [3], which is full of examples.

How to install graph-tool on Windows?

We cannot directly install graph-tool on Windows. For now, graph-tool is not supported in Windows, even installation with conda on Windows would also fail. On other OS, you can successfully install graph-tool via conda, by adding the ostrokach-forge channel [4].

In this article, we will demonstrate two ways of installation: Installing graph-tool using Docker Desktop and using Anaconda on WSL (Windows Subsystem for Linux). 

How to install graph-tool on Windows using Docker Desktop?

The best solution and OS-agnostic way to install graph-tool is using Docker. In this section, we will demonstrate the step-by-step in installing graph-tool using Docker, to assist you; in case you have little or no familiarity with using Docker. The following are the step-by-step graph-tool installation using Docker Desktop, for Windows users:

If you already install Docker on your Windows correctly, run the following command on your cmd to pull the graph-tool image:

docker pull tiagopeixoto/graph-tool
What Is The Best Python Graph Tool? graph-tool vs NetworkX - a terminal window showing graph-tool being installed into Docker desktop

Open Docker Desktop, go to the Images tab, and run the graph-tool image:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - a GUI showing graph-tool being installed

Go to Optional settings, to give your container a representative name, for example, graph-tool-python:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - the settings choice for running a Docker container
What Is The Best Python Graph Tool? graph-tool vs NetworkX - checking the container name for our Docker container

Open the container, by going to the Containers tab, and run the graph-tool-python container:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - confirming Docker is running properly

And graph-tool would be installed and run successfully.

How to install graph-tool on Windows using Anaconda on WSL?

This section assumes you are already familiar with Linux on Windows using WSL (Windows Subsystem for Linux)  [5], and you already installed Anaconda on your Linux system [6]. In this demo, I installed graph-tool on Ubuntu 18.04 on WSL on Windows 10.

Why not install it directly via package managers for GNU/Linux, you might ask? As instructed in Reference [7]? If you install graph-tool directly via package managers for GNU/Linux, you might encounter the following error, that might be caused by the package is missing in the your selected distribution:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - installing via WSL

You might need to change the distribution and try it one by one (available distribution: bookworm, bullseye, buster, sid, bionic, eoan, focal, hirsute, impish, jammy), that might be too time consuming. Read more about it in Reference [8]:

So, the more straightforward way is by installing it via Anaconda.

The easiest way to install graph-tool is to create a new environment and install it there:

conda create --name gt -c conda-forge graph-tool
What Is The Best Python Graph Tool? graph-tool vs NetworkX - using Anaconda

You can also install graph-tool without creating a new environment, but the solver is likely to fail (or hang) if your environment already contains many packages, whose dependencies may conflict with the graph-tool dependencies. This is particularly likely if your environment contains packages from the official Anaconda distribution, rather than the conda-forge distribution.

Activate the newly-created graph-tool or gt environment:

conda activate gt

After that, install additional packages as needed:

conda install -n gt -c conda-forge ipython jupyter
What Is The Best Python Graph Tool? graph-tool vs NetworkX - installing via Anaconda part 2

How to start graph-tool interactive sessions? 

with IPython (for Docker users)

Run the following line on your Windows cmd, to activate the graph-tool using interactive Python (IPython) [7]:

docker run -it -u user -w /home/user tiagopeixoto/graph-tool ipython

If you successfully activate the IPython for graph-tool, your command prompt would look like the following screenshot:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - running an interactive session

with Jupyter Notebook (for WSL users)

First, activate your Anaconda environment that contains the graph-tool library:

conda activate gt

Run Jupyter Notebook with this command on your Ubuntu on WSL cmd:

jupyter notebook
What Is The Best Python Graph Tool? graph-tool vs NetworkX - using a Jupyter notebook
What Is The Best Python Graph Tool? graph-tool vs NetworkX - interactive with Jupyter

How to create your first graphs?

The graph tool module includes a Graph class as well as several algorithms that work with it. For the best performance, the internals of this class, as well as most of its algorithms, are written in C++ using the Boost Graph Library.

Let’s create your first graph using graph-tool with the following scripts [9]:

from graph_tool.all import *

g = Graph()
ug = Graph(directed=False)

ug = Graph()
ug.set_directed(False)
assert ug.is_directed() == False

g1 = Graph()
g2 = Graph(g1)

v1 = g.add_vertex()
v2 = g.add_vertex()

e = g.add_edge(v1, v2)
graph_draw(g, vertex_text=g.vertex_index, output="two-nodes.png")

A simple directed graph with two vertices and one edge would be created and saved as a two-nodes.png file by the script above.

What Is The Best Python Graph Tool? graph-tool vs NetworkX - graph output 1

Are there more graph-tool advanced examples?

In this section, we will try a more advanced example, that starts by loading a dataset, and then performing stochastic block model inference and visualizing the result with graph-tool.

First, we will start by loading the graph-tool dataset collection [10]. 

Here is the excerpt of the graph-tool dataset descriptions:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - a graphic of datasets

For example, we will work with the “football” dataset. Run the following scripts on the graph-tool IPython:

g = graph_tool.collection.data["football"]
print(g)
print(g.gp.readme)
print(g.gp.description)
What Is The Best Python Graph Tool? graph-tool vs NetworkX - graph output  - the results of using print(g)
What Is The Best Python Graph Tool? graph-tool vs NetworkX - graph output - the football choices
What Is The Best Python Graph Tool? graph-tool vs NetworkX - graph output

And let’s infer the best partition of the network using the following scripts [11]:

state = graph_tool.inference.minimize_blockmodel_dl(g)
state.draw(pos=g.vp.pos, output="football-sbm-fit.svg")

The script above will perform stochastic block model inference of a network of American college football teams. The colors correspond to inferred group membership of the nodes.

What Is The Best Python Graph Tool? graph-tool vs NetworkX - a nice network graph

How to browse the graph-tool plotting results?

How to show all the graph-tool plotting results by exporting the container (for Docker users)

You may notice that opening the plot results in Docker is tricky. It won’t be easily accessible as in your usual Windows’ or even Linux File Explorer.

You can see the following screenshot showing that the usual Linux or cmd commands are not working in Docker’s terminal:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - the terminal before exporting

To tackle this problem, and get your graph-tool outputs, you may need to archive your container’s file system into a tar file first. Open your command prompt, and run the following command [12]:

docker export container_name > contents.tar

For example:

docker export modest_knuth > contents.tar

The process might be time-consuming (and consuming large space as well), as it will export the entire contents of our selected container.

What Is The Best Python Graph Tool? graph-tool vs NetworkX - using Anaconda

After the exporting contents are completed, open the contents.tar file, and go to the /home/user directory to get the file you need. For example, from our previous sections: two-nodes.pdf and football-sbm-fit.svg.

How do we browse all the graph-tool plotting results via File Explorer (for Ubuntu on WSL users)?

For long-time Windows users, you might also notice that browsing the plot results or accessing files in general using GUI in WSL is tricky too. It won’t be easily accessible as in your usual Windows’ or even native Linux File Explorer.

But, in the latest Windows 10 update, we can easily browse Linux files from File Explorer, like we usually browse Windows files.

For example on my laptop, Go to Linux -> home -> user, and you would find your graph-tool outputs:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - graph output  - the graph output in Windows explorer

Is there another easier alternative? Try NetworkX!

Whether graph-tool provides publication-quality outputs & collections of sophisticated algorithms, we can consider that graph-tools is not beginner friendly, due to the following reasons:

  • Not easy to install or configure. The installation steps are not conventional.
  • Not supported in Windows.
  • If you insist on using graph-tool on Windows, the easiest way to use graph-tool is via Docker (because it is OS agnostic), as we’ve already shown in the demo above, or using dual OS employing WSL.
  • By using graph-tool via Docker, it means you have limited options in using it (either with IPython or Jupyter Notebook). And using Jupyter Notebook would lead you to set up a notebook server using VM, which might increase the challenges for beginners.
  • This means you can’t use it with your familiar or favorite IDEs like PyScripter, Spyder, etc.  

In contrast with the challenges above, NetworkX can easily be installed via pip or conda on all OS, and can easily be used in any famous Python IDE.

We’ve reviewed NetworkX, how to install it, and all the requirements, even create Windows GUI for it in the following articles:

What Is The Best Python Graph Tool? graph-tool vs NetworkX - NetworkX graph output
Solve a real AI problem – Solve the traveling salesman problem with NetworkX and Python4Delphi.

and you can watch the demo of NetworkX4D, along with other 5 famous Python libraries here:

In addition, if you’re looking for other powerful data visualization libraries, check out this article:


To get started with PyScripter, a free, feature-rich, and lightweight Python IDE, click here.

Download RAD Studio to make more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which simplifies the creation of Python GUIs for Windows using Delphi.

Consider DelphiVCL, which simplifies the creation of Windows GUIs with Python.


References & further readings

[1] Peixoto, T. P. (2022).

graph-tool official website. graph-tool.skewed.de

[2] Peixoto, T. P. (2022).

graph-tool performance comparison. graph-tool.skewed.de/performance

[3] Peixoto, T. P. (2022).

Welcome to graph-tool’s documentation! graph-tool 2.45 documentation. graph-tool.skewed.de/static/doc/index.html

[4] Uliana, R. (2017).

Installing graph-tool for Python 3 on Anaconda. Medium. ronie.medium.com/installing-graph-tool-for-python-3-on-anaconda-3f76d9004979

[5] Microsoft Learn. (2022).

Install Linux on Windows with WSL. learn.microsoft.com/en-us/windows/wsl/install

[6] DigitalOcean. (2018).

How To Install Anaconda on Ubuntu 18.04 [Quickstart]. digitalocean.com/community/tutorials/how-to-install-anaconda-on-ubuntu-18-04-quickstart

[7] Peixoto, T. P. (2022).

graph-tool installation instructions. graph-tool 2.45 GitLab repository. git.skewed.de/count0/graph-tool/-/wikis/installation-instructions

[8] Stack Overflow. (2020).

Error in installing graph-tool in Ubuntu 18.04. stackoverflow.com/questions/61485539/error-in-installing-graph-tool-in-ubuntu-18-04

[9] Peixoto, T. P. (2022).

Quick start using graph-tool. graph-tool 2.45 documentation. graph-tool.skewed.de/static/doc/quickstart.html

[10] Peixoto, T. P. (2022).

graph_tool.collection – Dataset collection. graph-tool 2.45 documentation. graph-tool.skewed.de/static/doc/collection.html

[11] Peixoto, T. P. (2022).

Inferring modular network structure. graph-tool 2.45 documentation.  graph-tool.skewed.de/static/doc/demos/inference/ inference.html

[12] Stack Overflow. (2014).

Exploring Docker container’s file system. stackoverflow.com/questions/20813486/exploring-docker-containers-file-system

The post What Is The Best Python Graph Tool? graph-tool vs NetworkX first appeared on Python GUI.

]]>
https://pythongui.org/what-is-the-best-python-graph-tool-graph-tool-vs-networkx/feed/ 0 9324
How To Create A Currency Converter Python GUI App With DelphiFMX https://pythongui.org/how-to-create-a-currency-converter-python-gui-app-with-delphifmx/ https://pythongui.org/how-to-create-a-currency-converter-python-gui-app-with-delphifmx/#respond Wed, 04 Jan 2023 11:00:00 +0000 https://pythongui.org/?p=8899 A graphical user interface, more commonly known as a GUI, is an important component of software application programming for human-computer interaction, replacing text-based commands with user-interactive visual actions. With the aid of a GUI, users...

The post How To Create A Currency Converter Python GUI App With DelphiFMX first appeared on Python GUI.

]]>
A graphical user interface, more commonly known as a GUI, is an important component of software application programming for human-computer interaction, replacing text-based commands with user-interactive visual actions. With the aid of a GUI, users can perform operations on a device, platform, program, or application without having to type commands or comprehend the underlying coding. So, if you want to learn how to create stunning GUI applications using Python, you’ve come to the right place! In this article, we will look at how to build a simple currency conversion application using some of the best Python GUI tools on the market.

What is DelphiFMX?

DelphiFMX is a natively compiled Python module powered by the Python4Delphi library. It’s free to use and distribute, and it gives Python developers access to Delphi’s mature and rich FireMonkey GUI framework, which provides a simple way to create GUIs compatible across all platforms.

FireMonkey by Embarcadero Delphi is a GUI framework for native cross-platform application development that uses hardware-accelerated rendering via DirectX or OpenGL. It also has a strong styling system and is user extensible.

How To Create A Currency Converter Python GUI App With DelphiFMX - the Delphi FMX screen

How can you create a currency conversion Python GUI application using DelphiFMX?

Let’s create a basic GUI application where a user can provide a currency name and an amount in that currency. Our application would output the exchange amount in any desired currency.

How To Create A Currency Converter Python GUI App With DelphiFMX - a laptop showing a Python script

What are the requirements to complete the Currency Conversion Python GUI application?

For this tutorial, you will need Python and any text editor or an IDE that supports Python development (PyScripter is recommended). In addition to this, you will need to install the DelphiFMX package. You will also need a basic understanding of Python and DelphiFMX.

You can install the DelphiFMX Python package via PyPi:

pip install delphifmx

You can grab the code for this tutorial from our git repository at: github.com/Embarcadero/PythonBlogExamples/tree/main/Currency_Converter_GUI

How to create a simple UI application?

How To Create A Currency Converter Python GUI App With DelphiFMX - example code screenshot 1

Let’s get acquainted with some basic functions of this library to progress with our currency converter app. For this, we can create a basic DelphiFMX application simpleGUI.py that displays a short message:

from delphifmx import *

Application.Initialize()
Application.Title = "Delphi FMX"

main_window = Form(Application)
Application.MainForm = main_window

main_window.SetProps(Caption = "Python4Delphi")
msg = Label(main_window)
msg.SetProps(Parent = main_window,
    Text = "Delphi FMX For Python GUIs",
    Position = Position(PointF(20, 20)),
    Width = 200)
main_window.SetProps(Width = 315, Height = 400) #Window dimensions
main_window.Show()
Application.Run() #Main loop
main_window.Destroy()

Running this code would display the following:

How To Create A Currency Converter Python GUI App With DelphiFMX - a blank Python GUI screen

To get a detailed understanding of the above code, please go through the free eBook bundle that we developed. This eBook explains the ideology around Delphi-Python EcoSystem, Python GUI offerings, and much more.

How To Create A Currency Converter Python GUI App With DelphiFMX - a link asking you to download a free Python GUI ebook

How to enhance a Python GUI to create a currency converter?

Let’s create a new Python file CurrencyConverter.py and write code in it. Our code will use two libraries:

import requests
from delphifmx import *
How To Create A Currency Converter Python GUI App With DelphiFMX - example code screenshot 2

Now, we will define a class CurrencyConvert that will define our main form:

class CurrencyConvert(Form):
    def __init__(self, owner):
        self.SetProps(Caption = "Currency Converter App", width=350)

        #Non-editable Labels
        self.heading = Label(self)
        self.heading.SetProps(Parent = self, Text = "Currency Converter", Position = Position(PointF(70, 10)), 
                              Width=200, Height=40, StyleLookup = 'listboxheaderlabel')

        self.fromm = Label(self)
        self.fromm.SetProps(Parent = self, Text = "From", Position = Position(PointF(20, 60)), 
                            StyleLookup = 'listboxitemlabel')

        self.to = Label(self)
        self.to.SetProps(Parent = self, Text = "To", Position = Position(PointF(20, 180)), 
                         StyleLookup = 'listboxitemlabel')

        self.C1 = Label(self)
        self.C1.SetProps(Parent = self, Text = "Currency: ", Position = Position(PointF(20, 90)))

        self.C2 = Label(self)
        self.C2.SetProps(Parent = self, Text = "Currency: ", Position = Position(PointF(20, 210)))

        self.A1 = Label(self)
        self.A1.SetProps(Parent = self, Text = "Amount: ", Position = Position(PointF(180, 90)))

        self.A2 = Label(self)
        self.A2.SetProps(Parent = self, Text = "Amount: ", Position = Position(PointF(180, 210)))

        self.A2Value = Label(self) #To display converted value
        self.A2Value.SetProps(Parent = self, Text = "-", Position = Position(PointF(180, 240)))

        #Editable textboxes
        self.editA1 = Edit(self) #Currency1 amount
        self.editA1.SetProps(Parent = self, Position = Position(PointF(180, 120)), Height = 20)

        #Drop-down menu for currency
        self.comboC1 = ComboBox(self) #Currency1 name
        self.comboC1.SetProps(Parent = self, Position = Position(PointF(20, 120)), Height = 20)

        self.comboC2 = ComboBox(self) #Currency2 name
        self.comboC2.SetProps(Parent = self, Position = Position(PointF(20, 240)), Height = 20)

        #Getting Country Codes
        self.__load_country_codes()

        #Button
        self.convert = Button(self)
        self.convert.SetProps(Parent = self, Text = "Convert", Position = Position(PointF(170, 300)), 
                              Width = 100, OnClick = self.__button_click_convert)

    def __load_country_codes(self): #To get country codes
        pass

    def __button_click_convert(self, sender): #Method called when convert button clicked
        pass

Here we are making a simple form with eight labels using the Label class of delphifmx. Some of these labels are being used to display information regarding components in our application and guide the user better. With that said, the primary label of interest is self.A2Value, which we will use to display the converted amount from a given currency to the desired currency. Moreover, we also create a two combo boxes self.comboC1 and self.comboC2 that will display all available currencies that are available in the API in the form of a dropdown menu. These comboxes drop-down list will get populated with all of the country codes using the __load_country_codes method. In addition, we create a single textbox using the Edit class that we will use to define the input amount to be converted.

Next, we define a simple Button object self.convert with text, Convert, which when clicked, will call the __button_click_convert method of our class. For now, we leave the method empty.

How To Create A Currency Converter Python GUI App With DelphiFMX - example code screenshot 3

Now, we will define our main method that initializes the CurrencyConvert form that we defined earlier:

def main():
    Application.Initialize()
    Application.Title = "Currency Converter Using Delphi FMX"
    Application.MainForm = CurrencyConvert(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

Adding the following lines will initiate the app whenever this Python code file is run:

if __name__ == '__main__':
    main()

Running the code will give us this GUI:

How To Create A Currency Converter Python GUI App With DelphiFMX - the Currency Converter screen

How to add functionality to the convert button in our Python GUI?

Earlier, we had left the __button_click_convert method as empty. Now let us redefine this function such that it can display the converted currency amount on the form.

How To Create A Currency Converter Python GUI App With DelphiFMX - example code screenshot 4

For our application, we can use a currency exchange API to convert currencies, which in our case is APILayer’s Exchange Rates Data API.

Here is how we define our button click method:

def __button_click_convert(self, sender): #Method called when convert button clicked
        given = self.comboC1.Selected.Text
        to = self.comboC2.Selected.Text
        amountGiven = int(self.editA1.Text)
        url = "https://api.apilayer.com/currency_data/convert?to={}&from={}&amount={}".format(to, given, amountGiven)

        headers= {
        "apikey": "" ### Enter your Currency Data API's Unique API key in this string ###
        } 

        response = requests.request("GET", url, headers=headers) #API GET request

        result = response.json() #Reading json response
        self.A2Value.Text = str(result["result"]) #Displaying the response

In this function, we will first have to retrieve the values input by the user. To do this, we call the Text property of the Selected property of our ComboBox class to get the currency code for conversion. We store this in our local variable named given (which stores the current currency) and to (which specifies the currency to be converted in). Then, using the Text property of the Edit class, we get the amount of the current currency and store it in the variable amountGiven

Next, we define our exchange rate API. To do this, we first create a free account on APILayer’s Exchange Rates Data API. The variable headers is where we specify our API key. Please enter the generated API key for you to an “apikey” key value of the headers dictionary. Finally, we can retrieve our currency amount by calling the API using a GET request. Finally, we store the response json in a result variable and display the converted current value on our A2Value label.

How do we initialize our currencies using the APILayer API in Python?

As mentioned previously we will be using the __load_country_codes method to initialize our currencies by populating our combo boxes. Here is how we define the method:

def __load_country_codes(self):
        url = "https://api.apilayer.com/currency_data/list"
        
        headers= {
        "apikey": "" ### Enter your Currency Data API's Unique API key in this string ###
        } 

        response = requests.request("GET", url, headers=headers) #API GET request

        result = response.json() #Reading json response
        codes = list(result['currencies'].keys())
        for code in codes:
            self.comboC1.Items.append(code)
            self.comboC2.Items.append(code)

When the function __load_country_codes is called in the __init__ method, it simply calls the Exchange Rates Data API and retrieves all the currencies supported by the API. Once all the information has been retrieved, it extracts all the symbols from the response and provides them in drop-down list of the combo boxes. We are making use of the append() method of the Items property (attribute) of the ComboBox class to add items into it.

Why should you use APILayer’s Exchange Rates Data API in Python?

The Exchange Rates Data API is a real-time, intraday, and historical market data API. With over 15 exchange rate data sources, the Exchange rates API is a powerful and robust RESTful API that delivers exchange rate data for more than 170 world currencies.

How To Create A Currency Converter Python GUI App With DelphiFMX - setting up the APILayer details

This API contains many endpoints, each of which serves a distinct purpose or use case. For example, receiving the most recent exchange rate information for a specific set or all currencies; converting one currency to another; receiving data time-series for one or more currencies; preserving the API daily for fluctuation data are among the endpoints.So your final CurrencyConverter.py should look like this:

#Imports
import requests
from delphifmx import *

class CurrencyConvert(Form):
    def __init__(self, owner):
        self.SetProps(Caption = "Currency Converter App", width=350)

        #Non-editable Labels
        self.heading = Label(self)
        self.heading.SetProps(Parent = self, Text = "Currency Converter", Position = Position(PointF(70, 10)), 
                              Width=200, Height=40, StyleLookup = 'listboxheaderlabel')

        self.fromm = Label(self)
        self.fromm.SetProps(Parent = self, Text = "From", Position = Position(PointF(20, 60)), 
                            StyleLookup = 'listboxitemlabel')

        self.to = Label(self)
        self.to.SetProps(Parent = self, Text = "To", Position = Position(PointF(20, 180)), 
                         StyleLookup = 'listboxitemlabel')

        self.C1 = Label(self)
        self.C1.SetProps(Parent = self, Text = "Currency: ", Position = Position(PointF(20, 90)))

        self.C2 = Label(self)
        self.C2.SetProps(Parent = self, Text = "Currency: ", Position = Position(PointF(20, 210)))

        self.A1 = Label(self)
        self.A1.SetProps(Parent = self, Text = "Amount: ", Position = Position(PointF(180, 90)))

        self.A2 = Label(self)
        self.A2.SetProps(Parent = self, Text = "Amount: ", Position = Position(PointF(180, 210)))

        self.A2Value = Label(self) #To display converted value
        self.A2Value.SetProps(Parent = self, Text = "-", Position = Position(PointF(180, 240)))

        #Editable textboxes
        self.editA1 = Edit(self) #Currency1 amount
        self.editA1.SetProps(Parent = self, Position = Position(PointF(180, 120)), Height = 20)

        #Drop menu for currency
        self.comboC1 = ComboBox(self) #Currency1 name
        self.comboC1.SetProps(Parent = self, Position = Position(PointF(20, 120)), Height = 20)

        self.comboC2 = ComboBox(self) #Currency2 name
        self.comboC2.SetProps(Parent = self, Position = Position(PointF(20, 240)), Height = 20)
        
        #Getting Country Codes
        self.__load_country_codes()

        #Button
        self.convert = Button(self)
        self.convert.SetProps(Parent = self, Text = "Convert", Position = Position(PointF(170, 300)), 
                              Width = 100, OnClick = self.__button_click_convert)

    def __load_country_codes(self):
        url = "https://api.apilayer.com/currency_data/list"
        
        headers= {
        "apikey": "" ### Enter your Currency Data API's Unique API key in this string ###
        } 

        response = requests.request("GET", url, headers=headers) #API GET request

        result = response.json() #Reading json response
        codes = list(result['currencies'].keys())
        for code in codes:
            self.comboC1.Items.append(code)
            self.comboC2.Items.append(code)

    def __button_click_convert(self, sender): #Method called when convert button clicked
        given = self.comboC1.Selected.Text
        to = self.comboC2.Selected.Text
        amountGiven = int(self.editA1.Text)
        url = "https://api.apilayer.com/currency_data/convert?to={}&from={}&amount={}".format(to, given, amountGiven)

        headers= {
        "apikey": "" ### Enter your Currency Data API's Unique API key in this string ###
        } 

        response = requests.request("GET", url, headers=headers) #API GET request

        result = response.json() #Reading json response
        self.A2Value.Text = str(result["result"]) #Displaying the response

def main():
    Application.Initialize()
    Application.Title = "Currency Converter Using Delphi FMX"
    Application.MainForm = CurrencyConvert(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

if __name__ == '__main__':
    main()

How can we test our Currency Converter Python GUI app?

Now let us test the functionality of our code. First, run the application and start populating the combo boxes and the text boxes. Here we will try to convert US Dollar – $1 to Euros equivalent:

How To Create A Currency Converter Python GUI App With DelphiFMX - the Python GUI screen for the currency converter in action

If everything is set up correctly, then you should simply click on the Convert button, and this will convert the given USD $1 amount into Euros as per the exchange rates at the moment you clicked on Convert button using the API:

How To Create A Currency Converter Python GUI App With DelphiFMX - the results of currency conversion using the APILayer API in a Python GUI

In addition, since we are using APILayer’s Exchange Rates API to get real-time data of 170+ currencies, we should also be able to convert other currencies. So add the Canadian Dollar “CAD” and amount to the From field and do the same for Omani Rial “OMR” in the To field. Let’s say we want to know the equivalent of 213 CAD in OMR. Clicking Convert gives us the following result:

How To Create A Currency Converter Python GUI App With DelphiFMX - more example screen shots

Why should Python developers use PyScripter to create Python GUIs?

How To Create A Currency Converter Python GUI App With DelphiFMX - the PyScripter download page shown on a laptop screen

PyScripter is a Python-integrated development environment (IDE) for Windows that is free and open source. It was created using Delphi’s Object Pascal and Python.

PyScripter started as a simple IDE to provide a powerful scripting solution for Delphi applications. It gradually evolved into a full-featured stand-alone Python IDE. It is written in Delphi and can be extended with Python scripts using Python4Delphi (P4D). It is relatively light compared to other IDEs because it is written in a compiled language. In addition, it is a portable IDE that can be used as a syntax highlighting editor, a Python interpreter and debugger, a file explorer, and a project manager, among other things.

What have you learned in this Python Currency Converter GUI application tutorial?

How To Create A Currency Converter Python GUI App With DelphiFMX - a person with their hands on the keyboard of a laptop ready to download PyScripter

Congratulations on finishing this tutorial! Hopefully, this has opened your eyes to how simple it is to build Python GUIs with the right toolkit. In addition, we’ve seen how important Python bindings for Delphi GUI libraries are for the Python GUI developer community.

A user interface does not have to be difficult to design. Pip packages give you access to a wide range of Python tools. DelphiFMX is an extremely capable application with numerous capabilities and customization options. It is highly recommended for Windows, Linux and Mac desktop application developers due to its inherent support for hardware acceleration. If you want to learn more about Python GUI’s features, you can download the Python GUI getting started e-book.

How To Create A Currency Converter Python GUI App With DelphiFMX - an image for someone to click to download a free e book

In addition, we also saw how using PyScipter while using the DelphiFMX library makes Python programming even more fun and easy.

Now that you know all about PyScripter click here and create your own application using your favorite IDE. 

What are the FAQs about creating a Python GUI Currency Converter app?

How To Create A Currency Converter Python GUI App With DelphiFMX - a laptop showing the PyScripter help page

What is Delphi?

Delphi is an extremely powerful yet easy to learn object-oriented programming language. It has a Rapid Application Development (RAD) paradigm that can be used to create anything from database solutions to mobile applications. It is noted for the ease of deployment of Delphi apps – which do not require any additional runtimes or dependencies, along with its robustness and single-source cross-platform capabilities. As a result, Delphi is widely regarded as the most efficient way to create, compile, package, and deploy cross-platform native applications for Windows, macOS, iOS, Android, and Linux. 

Products and tools like Delphi Community Edition, Python4Delphi, DelphiFMX, DelphiVCL, PyScripter, Delphi4PythonExporter, and PythonFMXBuilder allow Python developers to create all kinds of amazing professional quality applications very easily.

What other applications can you create using PyScripter and DelphiFMX?

With DelphiFMX, you are limited only by your imagination. Delphi, along with PyScripter, provides you with powerful tools that you can use to create powerful, versatile applications, including, but not limited to, calculators, alarm clocks, stopwatches, and even simple games.

What is Embarcadero?

Embarcadero is an Idera, Inc. subsidiary. Idera, Inc. is the parent company of global B2B software productivity brands whose solutions allow technical users to do more in less time.

Embarcadero creates tools intended for the world’s most elite developers who create and maintain the most critical applications. Embarcadero is the developer champion for our customers, assisting them in developing secure and scalable enterprise applications that are faster than any other tool on the market. Embarcadero’s award-winning products have been relied on by ninety percent of the Fortune 100 and a global community of more than three million users for over 30 years.

What is DelphiVCL?

DelphiVCL is a Visual Component Library that supports Delphi’s state-of-the-art user interface. These include a majority of native Windows controls, as well as controls with enhanced features and functionality. If you wish to develop applications only for Windows platform, you can take advantage of DelphiVCL.

What is APILayer?

APILayer is a leading provider of off-the-shelf, cloud-based API products that help developers and businesses all over the world run more efficiently and effectively. Organizations of all sizes are struggling to support complex digital transformations, as well as the growing demand for connectivity and real-time data. APILayer does exactly that!

The post How To Create A Currency Converter Python GUI App With DelphiFMX first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-currency-converter-python-gui-app-with-delphifmx/feed/ 0 8899
How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI https://pythongui.org/how-to-build-an-asynchronous-employee-management-service-using-fastapi-and-python-gui/ https://pythongui.org/how-to-build-an-asynchronous-employee-management-service-using-fastapi-and-python-gui/#comments Mon, 02 Jan 2023 11:00:00 +0000 https://pythongui.org/?p=8683 APIs, or Application Programming Interfaces, can be an extremely useful way of making your software accessible to users, potentially across the globe. Good programming language frameworks make it simple to create high-quality products quickly. They...

The post How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI first appeared on Python GUI.

]]>
APIs, or Application Programming Interfaces, can be an extremely useful way of making your software accessible to users, potentially across the globe. Good programming language frameworks make it simple to create high-quality products quickly. They can even make the development process more enjoyable. FastAPI is a new Python web framework that checks all the boxes for being an excellent API development framework and is powerful and efficient. In addition, it integrates well with many Python GUI applications.

In this article, we will look at some interesting features of FastAPI, focusing on async methods and how to use them to create web APIs quickly. By the end, you’ll be able to start creating production-ready web APIs. We will then learn about creating your own Python GUI using DelphiFMX and PyScripter which I think is the best Python IDE. Finally, we will integrate the web API into the GUI application.

What is the significance of asynchronous programming?

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a laptop showing the FastAPI download page

Asynchronous programming is a multi-tasking paradigm where a unit of work can run independently of the primary application thread. When the work is finished, it notifies the main thread of the worker thread’s success or failure.

This programming method has many key advantages; for instance, it is faster and more responsive than its synchronous counterpart. A program with asynchronous methods can become faster and present information to the user as it is processed, never allowing the project to become unresponsive and thus providing a better user experience.

This kind of programming even allows improved testing and error handling. If an operation in a different thread fails for whatever reason, you can handle the error or anomaly without restarting the entire project.

Furthermore, async ensures increased scalability since you can easily add new features or increase processing power to handle more requests by offloading operations to different threads.

Unfortunately, it also comes with some disadvantages, such as code complexity where code can become significantly more complex and difficult to debug, and thread overload which is where you overdo the amount of work the thread is doing which then impacts the synchronicity of your project so that becomes a hindrance rather than a help.

So, using asynchronous programming over synchronous programming isn’t a matter of what is better; it is a matter of when to use what.

You’ll generally want to use synchronous programming if your project focuses on a single task or if the tasks are highly time or response dependent and cannot run in parallel, such as web pages or video rendering. When you have a lot of tasks that don’t depend on each other or tasks that take a long time and can be run in the background, such as database manipulation, you’ll want to use asynchronous programming. Thus, any management system would be a good use case for async programming.

What is Python AsyncIO?

AsyncIO is a co-routine-based concurrency model in Python that provides elegant constructs for writing concurrent Python code without using threads.

This standard library package enables developers to create concurrent programs using async/await syntax. It enables developers to create unique functions known as co-routines for asynchronous programming by using a simple async keyword and is thus regarded as the ideal fit for IO-bound and high-level structured network code in Python.

Is it possible to build an asynchronous Python service with FastAPI?

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a laptop with a person editing a Python script

Yes, it is! Let us move on and start building an asynchronous employee management service in Python. But before we start with this application, there are some prerequisites that you need to install.

What are the prerequisites for creating an asynchronous service with Python?

First of all, you will need to install FastAPI and Uvicorn packages. You can easily install them using pip by running:

pip install fastapi uvicorn

FastAPI is a fairly new python web framework with built-in support for async API endpoints. The library will be used to construct a custom API for our employee management service. Meanwhile, Uvicorn is our chosen Asynchronous Server Gateway Interface (ASGI) server. This will help us run our app.

Next, you will need to install SQLAlchemy and aiosqlite using:

pip install SQLAlchemy aiosqlite

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper (ORM) that gives application developers the full power and flexibility of SQL. We will use this to create our database that will store all employee information while we use aiosqlite to interact with our database.

We can start building our service once we’ve installed our dependencies.

You can grab the code for this tutorial from our git repository at: github.com/Embarcadero/PythonBlogExamples/tree/main/Async_FastAPI_GUI_client

How to Use SQLAlchemy and AsyncIO to Create a Database?

Let’s begin by creating a database to store our Employee data.

First, we will configure our database using a simple Python script. To do this, create a file named employee.py and first import the necessary packages:

# Importing packages
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import Column, Integer, String

Next, we will create a local instance of SQLLite (a database named employees.db):

DB_URL = "sqlite+aiosqlite:///./employees.db"

We will use aiosqlite to communicate with the database as it supports async queries.

So, we create a database engine using the create_async_engine function.

Then sessionmaker creates a session with two unique flags, expire_on_comit, and class_. We set expire_on_comit to False, ensuring that our database entries and fields are always available even after a commit is made on our server session. Setting class_ to AsyncSession lets our database know this is a new async session:

# Creating a database instance
engine = create_async_engine(DB_URL, future=True, echo=True)

# Creating a session maker
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
# Creating a base to configure DB models
Base = declarative_base()

Now, we are ready to configure our database.

Since we’re building an employee management service, our main database would contain some identifying attributes like id and firstName along with further details, such as joinYear, which gives the year when the employee joined the organization. We can define our database by using the Base we declared previously:

# Configuring our DB model with tablename "employees"
class Employee(Base):
    __tablename__ = 'employees'

    # Initializing the columns and their data types
    id = Column(Integer, primary_key=True)
    firstName = Column(String, nullable=False)
    lastName = Column(String, nullable=False)
    gender = Column(String, nullable=False)
    role = Column(String, nullable=False)
    joinYear = Column(Integer, nullable=False)

Note that using the __tablename__ attribute above, we initialize the name of the database. We then assign each column a respective Column object, assign their data types, and declare whether they can be null using nullable, and specify whether they can be used as a primary_key for the database.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a screen showing the required FastAPI packages being imported

Here is what our final employee.py file looks like:

# Importing packages
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import Column, Integer, String

# Configuring
DB_URL = "sqlite+aiosqlite:///./employees.db"

# Creating a database instance
engine = create_async_engine(DB_URL, future=True, echo=True)

# Creating a session maker
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)

# Creating a base to configure DB models
Base = declarative_base()

# Configuring our DB model with tablename "employees"
class Employee(Base):
    __tablename__ = 'employees'

    # Initializing the columns and their data types
    id = Column(Integer, primary_key=True)
    firstName = Column(String, nullable=False)
    lastName = Column(String, nullable=False)
    gender = Column(String, nullable=False)
    role = Column(String, nullable=False)
    joinYear = Column(Integer, nullable=False)

To create a new entity, we will use a Data Access Layer (DAL), which will be responsible for all the SQL functions for our database. We do this by creating a new file, employee_dal.py, and adding some package imports:

from typing import List, Optional
from sqlalchemy import update, delete
from sqlalchemy.future import select
from sqlalchemy.orm import Session
from employee import Employee

Next, we define a new class named EmployeeDAL that will have four methods:

class EmployeeDAL():
    def __init__(self, db_session: Session):
        self.db_session = db_session

    async def create_employee(self, firstName: str, lastName: str, gender: str, role: str, joinYear: int):
        # Creating an Employee object
        new_employee = Employee(firstName=firstName,lastName=lastName, gender=gender, role=role, joinYear=joinYear)

        # Saving employee to the database
        self.db_session.add(new_employee)
        await self.db_session.flush()

    async def get_employees(self) -> List[Employee]:
        # Retrieving all employees from database and returning them
        q = await self.db_session.execute(select(Employee).order_by(Employee.id))
        return q.scalars().all()

    async def update_employee(self, employee_id: int, firstName: Optional[str], lastName: Optional[str], gender: Optional[str], role: Optional[str], joinYear: Optional[int]):
        # Retrieve employee from database
        q = update(Employee).where(Employee.id == employee_id)

        # Change the employee details
        if firstName:
            q = q.values(firstName=firstName)
        if lastName:
            q = q.values(lastName=lastName)
        if gender:
            q = q.values(gender=gender)
        if role:
            q = q.values(role=role)    
        if joinYear:
            q = q.values(joinYear=joinYear)
       
        # Update employee entity in the database
        q.execution_options(synchronize_session="fetch")
        await  self.db_session.execute(q)

    async def delete_employee(self, employee_id: int):
        # Deleting an employee from database and returning them
        await self.db_session.execute(delete(Employee).where(Employee.id == employee_id))

The create_employee() function receives details regarding an employee and creates a new Employee object. It then uses the object to save a new record to the database. A get_employees() function returns all the employees in the database in ascending order based on the employee id. The update_employee() function receives an employee id and optional new fields for the employee to update in the database. Lastly, the delete_employee() function receives an employee id and deletes the mentioned employee from the database.

It is important to note that in the update_employee() function, we add an execution parameter called synchronize_session. This method tells the session to “refresh” the updated entries using the fetch method, ensuring that all data in the memory will be up-to-date with the newly updated employee values.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a screenshot of the asynchronous service's source code for the get_employees and update_employees methods

Now that our database is ready, we can create an endpoint for our management service.

How to create an API endpoint with FastAPI?

Let’s start by creating a new file named app.py and importing symbols from the necessary packages:

# Importing necessary packages
from typing import List, Optional
import uvicorn
from fastapi import FastAPI
from employee import Employee, engine, Base, async_session
from employee_dal import EmployeeDAL

We then create an instance of FastAPI that will handle all the endpoints of our application:

# Creating an app instance
app = FastAPI()

Next, we create a startup function using the @app.on_event("startup") decorator, that will run when we start our application:

# Initializing the database on startup
@app.on_event("startup")
async def startup():
    # create db tables
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

The startup() function initializes our FastAPI and creates an instance of our database. This is done by either reading an already existing instance of employees.db or creating a new instance of our database.

All endpoints we make will asynchronously create a DB session and an EmployeeDAL instance with the session and then call their respective DAL functions. The main endpoint we are making is called employees and will have three methods. So, let us look at how we can create different methods for our employees endpoint.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a screenshot of Python code accessing some data in a database

What Will the GET Method Be?

The GET method for our employee management service will request the database to return all the employees:

# Creating a GET endpoint
@app.get("/employees")
async def get_all_employees() -> List[Employee]:
    # Creating an async session
    async with async_session() as session:
        async with session.begin():
            # Get and return all employees from database
            employee_dal = EmployeeDAL(session)
            return await employee_dal.get_employees()

The GET method creates an asynchronous session using async_session(). It then creates an instance of EmployeeDAL and later uses the get_employees() DAL function to get all of the employees in our database.

What Will the POST Method Be?

The POST method will serve to add an employee to our database. To do this, we will utilize the create_employee() DAL function that we created previously. This method’s response will be the details of the successfully added employee.

# Creating a POST endpoint
@app.post("/employees")
async def create_employee(firstName: str, lastName: str, gender: str, role: str, joinYear: int):
    # Creating an async session
    async with async_session() as session:
        async with session.begin():
            # Creating an EmployeeDAL instance (i.e., our employee)
            employee_dal = EmployeeDAL(session)
            # Adding said employee to the database
            await employee_dal.create_employee(firstName, lastName, gender, role, joinYear)
            return {"firstName": firstName, "lastName": lastName, "gender": gender, "role": role, "joinYear": joinYear}

What Will the DELETE Method Be?

The DELETE method will help us delete employees from our database. We will do this by the delete_employee() DAL function. The method will return the id of the deleted employee.

@app.delete("/employees/{employee_id}")
async def delete_employee(employee_id: int):
    # Creating an sync session
    async with async_session() as session:
        async with session.begin():
            employee_dal = EmployeeDAL(session)
            # Update employee with new updated details
            await employee_dal.delete_employee(employee_id)
            return {"id": employee_id}

What Will the PUT Method Be?

Finally, we create a PUT method that will allow us to update an existing employee in our database. This is done by calling the update_employee() DAL function in an EmployeeDAL instance. This method will simply return the id of the employee whose details have just been updated successfully.

# Creating a PUT endpoint
@app.put("/employees/{employee_id}")
async def update_employee(employee_id: int, firstName: Optional[str] = None, lastName: Optional[str] = None, 
                          gender: Optional[str] = None, role: Optional[str] = None, joinYear: Optional[int] = None):
    # Creating an sync session
    async with async_session() as session:
        async with session.begin():
            employee_dal = EmployeeDAL(session)
            # Update employee with new updated details
            await employee_dal.update_employee(employee_id, firstName, lastName, gender, role, joinYear)
            return {"id": employee_id}

How to Run the Server?

Finally, to run our server, we will run our app using uvicorn:

# Starting a FastAPI application
if __name__ == '__main__':
    uvicorn.run("app:app", port=8000, host='127.0.0.1')

The code above starts our FastAPI application using the uvicorn ASGI server on port 8000 with our custom endpoint.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a screenshot of Python code being debugged

Here is what our final server file (app.py) looks like:

# Importing necessary packages
from typing import List, Optional
import uvicorn
from fastapi import FastAPI
from employee import Employee, engine, Base, async_session
from employee_dal import EmployeeDAL

# Creating an app instance
app = FastAPI()

# Initializing the database on startup
@app.on_event("startup")
async def startup():
    # create db tables
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

# Initial get endpoint.
@app.get("/")
async def home():
    return "Employee Management! Visit Swagger Docs to test it out."

# Creating a POST endpoint
@app.post("/employees")
async def create_employee(firstName: str, lastName: str, gender: str, role: str, joinYear: int):
    # Creating an async session
    async with async_session() as session:
        async with session.begin():
            # Creating an EmployeeDAL instance (i.e., our employee)
            employee_dal = EmployeeDAL(session)
            # Adding said employee to the database
            await employee_dal.create_employee(firstName, lastName, gender, role, joinYear)
            return {"firstName": firstName, "lastName": lastName, "gender": gender, "role": role, "joinYear": joinYear}

# Creating a GET endpoint
@app.get("/employees")
async def get_all_employees() -> List[Employee]:
    # Creating an async session
    async with async_session() as session:
        async with session.begin():
            # Get and return all employees from database
            employee_dal = EmployeeDAL(session)
            return await employee_dal.get_employees()

@app.delete("/employees/{employee_id}")
async def delete_employee(employee_id: int):
    # Creating an sync session
    async with async_session() as session:
        async with session.begin():
            employee_dal = EmployeeDAL(session)
            # Update employee with new updated details
            await employee_dal.delete_employee(employee_id)
            return {"id": employee_id}

# Creating a PUT endpoint
@app.put("/employees/{employee_id}")
async def update_employee(employee_id: int, firstName: Optional[str] = None, lastName: Optional[str] = None,
                          gender: Optional[str] = None, role: Optional[str] = None, joinYear: Optional[int] = None):
    # Creating an sync session
    async with async_session() as session:
        async with session.begin():
            employee_dal = EmployeeDAL(session)
            # Update employee with new updated details
            await employee_dal.update_employee(employee_id, firstName, lastName, gender, role, joinYear)
            return {"id": employee_id}

# Starting a FastAPI application
if __name__ == '__main__':
    uvicorn.run("app:app", port=8000, host='127.0.0.1')

So, to run the server, simply execute your app.py python file. This will start an instance of your FastAPI application, ready to receive any API calls.

How to utilize a Python service as a client?

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a desktop screen showing the FastAPI endpoints

There are several ways to make API calls; we will explain them briefly below.

What is Swagger?

When you visit http://127.0.0.1:8000/docs in your browser, an automatic API documentation with all of the endpoints will appear. This is the Swagger UI.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a close-up of some FastAPI endpoints

The Swagger UI is automatic, interactive API documentation created while creating your custom FastAPI endpoints. Here you will have options to make calls to your API’s various endpoint methods.

For example, you can make a POST call to add an employee to your database:

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - defining the CreateEmployee endpoint

Once you execute this, you will get a similar response as below:

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - tesing the end point using curl

As you can see, the response object returns a JSON that provides all the attributes of the newly added employee in your database.

What are query parameters?

As shown in the above screenshots of Swagger Docs, all the attributes we provide to swagger while making API calls are query parameters.

Other function parameters declared but not included in the path parameters are automatically treated as “query” parameters.

In addition to the Swagger UI, we can use traditional query parameters to send requests to our service. The query is the group of key-value pairs that come after the ? in a URL and are separated by & characters.

For example, a URL representing a POST call to add an employee:

http://127.0.0.1:8000/employees/?firstName=Tom&lName=Sheldon&gender=M&role=Manager&joinYear=2015

How to use the requests Python package to create a client for an API?

Finally, you can also use the HTTP protocol to send client requests to the server, retrieve specific data, and also information on whether the transaction was successful.

Python has many packages that allow you to send and receive data from your client and server, but for this example, we will use the Python’s requests package to send and examine exchanges between the client and server.

Let’s install the requests package and confirm it’s installation:

pip install requests

To create a client endpoint using HTTP protocols, first, create a new file named simple_client.py import the requests package in your code:

import requests

Next, configure your base URL according to your server’s uvicorn running instance:

BASE = "http://127.0.0.1:8000/"

You can now send a GET request using get() method of requests package. This will fetch all the retrieved data using our API call:

# GET
response = requests.get(BASE + "employees")
response = response.json()
print(response)

Similarly, you can send a POST request using the requests.post method, but this time defining the query parameters:

# POST
endpointURL = BASE + "employees"
params = {"firstName": "Fifa", 
          "lastName": "Badar", 
          "gender": "F", 
          "role": "Teacher", 
          "joinYear":"2022" }
response = requests.post(endpointURL, params=params)
response = response.json()
print(response)

Though we can communicate with our service manually, this is quite time-consuming. Thus, the best way to exchange information between the client and the server is through a GUI. We will discuss this later in the article with one of the best options for GUI in Python.

Why should you use PyScripter to create APIs?

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - the Pyscripter download screen

An integrated development environment (IDE) can be the difference between a good and bad programming experience. Moreover, a good IDE simplifies code development management, saving time and frustration, and making coding an overall good experience. This is where PyScripter outperforms its competitors.

PyScripter is currently the best IDE, and it started as a simple IDE to supplement the excellent Python for Delphi (P4D) components by providing a reliable scripting solution for Delphi applications. It has a more modern user interface and is faster than some other IDEs because it is written in a compiled language. It also has several features that make it an excellent Python development environment.

This amazing IDE includes handy features such as brace highlighting, code folding, code completion, and syntax checking as you type. It includes a Python interpreter that allows users to run Python programs without saving them. Finally, this IDE accepts files dropped from Explorer or other browsers applications, which could save you time making it an ideal IDE for developing and testing APIs.

How can we build a Python GUI for this API?

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - the Embarcadero DelphiVCL and DelphiFMX Python library landing page

Making a simple graphical user interface (GUI) can be difficult, but it doesn’t have to be. Many Python libraries allow you to create GUIs; however, none are comparable to the DelphiFMX package, which allows you to create attractive user interfaces that you and your users will appreciate.

What is DelphiFMX?

DelphiFMX is a Python module that is natively compiled and powered by the Python4Delphi library. This cross-platform framework is freely redistributable and provides Python developers access to the FireMonkey GUI framework. It is versatile and provides a robust structure for Windows, Linux, macOS, and Android.

How can we use the DelphiFMX library to create a stunning Python GUI?

The DelhpFMX package for Python allows us to create powerful and stunning GUIs with minimal code. But before creating a GUI for our service, we first have to install DelphiFMX. So, open up the terminal and run the following command:

pip install delphifmx

Once installed, create a new Python file, eg. FMX_GUI_client.py, in your employee management service code directory.

Now, we can start building our service. First, import the relevant packages and initialize the BASE as the server URL:

import requests
from delphifmx import *

BASE = "http://127.0.0.1:8000/" # Base URL where the web service is being hosted locally
How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - another screenshot of a FastAPI endpoint

Next, we define an EmployeeManager class that will define our main form:

import requests
from delphifmx import *

BASE = "http://127.0.0.1:8000/" # Base URL where the web service is being hosted locally

class EmployeeManager(Form):
    def __init__(self, owner):
        self.SetProps(Caption = "Employee Management", Width = 600, Height = 420)

        # Adding labels for each textbox
        self.fName = Label(self)
        self.fName.SetProps(Parent = self, Text = "First Name: ", Position = Position(PointF(20, 20)))

        self.lName = Label(self)
        self.lName.SetProps(Parent = self, Text = "Last Name: ", Position = Position(PointF(20, 50)))

        self.gender = Label(self)
        self.gender.SetProps(Parent = self, Text = "Gender: ", Position = Position(PointF(20, 80)))

        self.role = Label(self)
        self.role.SetProps(Parent = self, Text = "Role: ", Position = Position(PointF(20, 110)))

        self.year = Label(self)
        self.year.SetProps(Parent = self, Text = "Year Joined: ", Position = Position(PointF(20, 140)))

        self.id = Label(self)
        self.id.SetProps(Parent = self, Text = "Employee ID: ", Position = Position(PointF(400, 60)))

        # Adding textboxes
        self.editFName = Edit(self)
        self.editFName.SetProps(Parent = self, Position = Position(PointF(100, 20)), Height = 20)

        self.editLName = Edit(self)
        self.editLName.SetProps(Parent = self, Position = Position(PointF(100, 50)), Height = 20)

        self.editGender = Edit(self)
        self.editGender.SetProps(Parent = self, Position = Position(PointF(100, 80)), Height = 20)

        self.editRole = Edit(self)
        self.editRole.SetProps(Parent = self, Position = Position(PointF(100, 110)), Height = 20)

        self.editYear = Edit(self)
        self.editYear.SetProps(Parent = self, Position = Position(PointF(100, 140)), Height = 20)
       
        self.editId = Edit(self)
        self.editId.SetProps(Parent = self, Position = Position(PointF(400, 80)), Height = 20)

        # Adding buttons to call the 3 methods of our API endpoint
        self.addEmployee = Button(self)
        self.addEmployee.SetProps(Parent = self,Text = "Add Employee", Position = Position(PointF(250, 110)), 
                                  Width = 100, OnClick = self.__button_click_add)

        self.view = Button(self)
        self.view.SetProps(Parent = self, Text = "View Employees", Position = Position(PointF(250, 140)), 
                           Width = 100, OnClick = self.__button_click_view)

        self.update = Button(self)
        self.update.SetProps(Parent = self, Text = "Update Employee", Position = Position(PointF(400, 110)), 
                             Width = 100, OnClick = self.__button_click_update)
       
        self.delete = Button(self)
        self.delete.SetProps(Parent = self, Text = "Delete Employee", Position = Position(PointF(400, 140)), 
                             Width = 100, OnClick = self.__button_click_delete)

        # List box to display all API call responses or any other messages
        self.list = ListBox(self)
        self.list.SetProps(Parent = self, Position = Position(PointF(20, 170)), Width = 550, Height = 200)

Here we are creating six labels: fname, lname, gender, role, year, and id using DelphiFMX’s Label class. We then create textboxes for each defined label using the Edit class. These textboxes will take input from the user to add some values to our application. Finally, we define three buttons addEmployee, view, and update, which will allow us to add employees to our database, view all the employees, or update the employee details in our database respectively. You can optionally use TColor to define the colors for your GUI.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a screenshot of the form_show and form_close methods along with some button click code

Now, we define private class methods that add functionality to our GUI and its buttons:

def __button_click_add(self, sender): # Called when addEmployee button clicked
        data = {"firstName": self.editFName.text,
                "lastName": self.editLName.text,
                "gender": self.editGender.text,
                "role": self.editRole.text, 
                "joinYear": int(self.editYear.text)}
        endpointURL = BASE + "employees"
        response = requests.post(endpointURL, params=data)
        self.list.items.add("Your Entry was successfully added!")
        self.list.items.add(response.json())

        self.editFName.text = self.editLName.text = self.editGender.text = self.editRole.text = self.editYear.text = ""

    def __button_click_update(self, sender): # Called when update button clicked
        # If conditions to support the optional feature of your update call
        if self.editFName.text=="":
            fname = None
        else:
            fname = self.editFName.text
        if self.editLName.text=="":
            lname = None
        else:
            lname = self.editLName.text
        if self.editGender.text=="":
            gender = None
        else:
            gender = self.editGender.text
        if self.editRole.text=="":
            role = None
        else:
            role = self.editRole.text
        if self.editYear.text=="":
            year = None
        else:
            year = int(self.editYear.text)

        endpointURL = BASE+"employees/"
        data = {"firstName": fname,
                "lastName": lname,
                "gender": gender, 
                "role": role, 
                "joinYear": year}
        response = requests.put(endpointURL+str(self.editId.text), params=data)
        response = response.json()
        self.list.items.add("Your Entry was successfully updated!")
        self.list.items.add(response)

    def __button_click_view(self, sender): # Called when view button clicked
        response = requests.get(BASE + "employees")
        response = response.json()
       
        if response != []:
            for employee in response:
                self.list.items.add(employee)
        else:
            self.list.items.add("Your Employee Database is empty!")

    def __button_click_delete(self, sender):
        endpointURL = BASE + "employees/"
        response = requests.delete(endpointURL+str(self.editId.text))
        response = response.json()
        self.list.items.add("Your Entry was successfully deleted!")
        self.list.items.add(response)

Lastly, we will define the main method that runs our GUI:

def main():
    Application.Initialize()
    Application.Title = "Employee Management Using Delphi FMX"
    Application.MainForm = EmployeeManager(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

We can finally call our main function to run our GUI application. Optionally, you can add the following lines of code to run the GUI whenever the file is run:

if __name__ == '__main__':
    main()

What does our Python GUI look like?

Running the code will give the following GUI:

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a screenshot of the example GUI

If your server is running, then your GUI must be completely functional, and you can start making calls to your endpoints.

Clicking the View Employees button will display all the employees in your database:

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - the FastAPI example in action

We can see that the employee we added earlier using the swagger UI is in our database.

You can fill in all the employee details and add an employee to your database using the Add Employee button.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - the employee management screen

Below, you can see that an employee was successfully added to the database:

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - getting back results

Similarly, you can even update an employee’s details using the Update Employee button. Let’s consider that Jane has changed her last name. So we will type her id in the Employee ID text box and then update the field that we need to.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - showing the JSON results

Note that, to make updates using the PUT call, giving any parameter other than Employee ID is optional.

Now let’s view the list of employees again using View Employees to see if the changes have been reflected:

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - the view employees button

We can see that the changes have been made! Now, let’s even test our async API’s delete functionality by deleting the employee using the Delete Employee button with id number 1.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - the delete employee method

We can see the success message and API request’s appropriate response, but let’s view employees one last time to ensure the deletion:

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - testing the employee endpoints

Are you ready to create your own APIs using FastAPI and Python GUI?

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a laptop on the download PyScripter page

Great job on making it this far! We have successfully built an employee management service, using FastAPI and SQLAlchemy, that maintains an organization’s employee data. New employees can be added here, while existing employee details can be viewed or updated. Since this service is an example of database management, it was the perfect use case for asynchronous programming.

Hopefully, this tutorial has given you a better understanding of DelphiFMX and how to use it with FastAPI to build apps that are production-ready by default and offer the finest developer experience.

Now that you’re ready, click here and start creating your own highly performant production-ready applications with FastAPI and the best GUI framework in the market.

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - an image with a link to download a free ebook and styles bundle for Python GUI

What are some FAQs about APIs related to creating a Python GUI and asynchronous service?

How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI - a laptop showing the PyScripter help screen

What are some benefits of asynchronous programming?

Using async programming improves performance, responsiveness, and user experience. With it, following page refreshes are no longer required because page load delays are eliminated.

Furthermore, even if other requests are running, you can use more than one feature at a time. Also, asynchronous applications use few resources and are very scalable, and the time it takes to respond to one request has no bearing on the time it takes to respond to others.

Another important aspect is that when one thread fails, the others keep rendering. It is also beneficial that the developer can make custom error messages using the built-in callback.

What is Embarcadero?

Embarcadero tools are designed for the world’s most elite developers who create and maintain the world’s most critical applications.

Embarcadero specializes in building business-critical applications in a demanding vertical scaling. It allows users to write steadfast code quickly and pass stringent code reviews faster than any other. In addition, it provides help from elite developers who understand C++ and Delphi’s scalability and stability and rely on the decades of innovation those languages bring to development.

Why is DelphiVCL famous in Python GUI?

DelphiVCL for Python is a widely known and recognized Python GUI framework geared toward native Windows development. It uses the Windows-only VCL framework and brings a powerful, flexible GUI framework to Windows, Linux, macOS, and Android.

What makes FastAPI one of the best libraries for creating apps in Python?

Many reasons make FastAPI one of the best APIs for creating production-ready applications. The first is the speed of development. Autocompletion and type hints in your favorite IDE or code editor are available in FastAPI. This is because the framework was designed to reduce the developer’s workload. Additional plugins, such as Flask-Marshmallow, are not required for FastAPI validation and serialization.

Secondly, the speed of execution: is fast too. FastAPI is capable of async execution. The server and toolkit it is based on are thanks to Uvicorn and Starlette. Flask lacks that capability as of now, giving FastAPI an advantage.

The post How To Build An Asynchronous Employee Management Service Using FastAPI And Python GUI first appeared on Python GUI.

]]>
https://pythongui.org/how-to-build-an-asynchronous-employee-management-service-using-fastapi-and-python-gui/feed/ 5 8683
What Are Command Line Arguments And How To Pass Arguments To A Python Script https://pythongui.org/what-are-command-line-arguments-and-how-to-pass-arguments-to-a-python-script/ https://pythongui.org/what-are-command-line-arguments-and-how-to-pass-arguments-to-a-python-script/#respond Wed, 28 Dec 2022 11:00:00 +0000 https://pythongui.org/?p=9122 There are different ways to run a Python script. One of them is using the command line. To interact with the program when running the script you can use command line arguments. In this article,...

The post What Are Command Line Arguments And How To Pass Arguments To A Python Script first appeared on Python GUI.

]]>
There are different ways to run a Python script. One of them is using the command line. To interact with the program when running the script you can use command line arguments. In this article, we will show how to pass arguments to a Python script and how to process them.

What are command line arguments?

Command line arguments are specific information passed to the program when it is started. For example, if the program needs to output data to a file, you can pass it as a command line argument instead of hardcoding it. A program can have one or more command-line arguments.

Why do we need to use command line arguments?

We can use command-line arguments to interact with the program in a GUI-like manner. Using them, we can transfer important information to the program, easily configure it, change its behavior, and experiment with how the program will work with different values of the arguments.

How to pass arguments to a Python script?

When running a Python script, command-line arguments are passed after its name. This example runs the Python script “test.py”, which has two command-line arguments: arg1 and arg2.

python test.py arg1 arg2

How to parse Python command line arguments?

There are several ways for parsing command-line arguments in Python.

You can use the sys module to pass arguments to a Python script

This is a basic Python module that implements command-line arguments in a simple sys.argv list structure and provides access to any command-line argument.

The first command line argument in the list, sys.argv[0], is the Python script name. The rest of the list items are command-line arguments. Each element contains one argument. In order to get the number of elements in the list, you need to use the len(sys.argv) command.

Let’s consider the following example.

import sys

print 'Number of arguments:', len(sys.argv) - 1
print 'Script name:', sys.argv[0]
print 'Argument List:', str(sys.argv[1:])

This script prints the number of Python command line arguments, the name of the program, and the list of arguments. Save it to a file called “test.py” and run it using the command:

python test.py arg1 arg2 arg3

The result of executing the script will be as follows:

Number of arguments: 3
Script name: test.py
Argument List: ['arg1', 'arg2', 'arg3']

The getopt module is used when we pass arguments to a Python script

The getopt Python module allows you to parse command line options and argument values. For this, the getopt() method is used, which has the following parameters:

  • args is a list of command line arguments.
  • short_options are the option letters to be recognized. If the parameter needs to be assigned a value, then a colon ‘:’ is placed after it.
  • long_options is a list of long option names to support. These are optional arguments.

The getopt.getopt() method returns two elements:

  • A list of (option, value) pairs.
  • The list of program arguments remains after removing the parameter list.

Consider the following script.

import getopt, sys

arguments = sys.argv[1:]
options, values = getopt.getopt(arguments, "hi:o:", ["in=","out="])
for opt, val in options:
    if opt in ("-h", "--help"):
        print ("Displaying help")
    elif opt in ("-i", "--ifile"):
        print "Input file:", val
    elif opt in ("-o", "--ofile"):
        print "Output file:", val

This script can take three arguments on the command line: -h (used to display help), -i or –ifile (input file), -o or –ofile (output file).

The result of running the script:

python test.py -h
Displaying help
python test.py -i in
Input file: in
python test.py -o out
Output file: out

Parse commands with the argparse module when we need to pass arguments to a Python script

This module offers a convenient command line interface. It allows the program to specify the necessary arguments and gets them from sys.argv itself.

Below is an example of how to use argparse module to accept a name parameter.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name")

args = parser.parse_args()

print"name=", args.name
What are command line arguments and how to pass arguments to a python script? An image of a laptop with the PyScripter download page displayed on it.

How to use PyScripter for creating Python scripts?

PyScipter is a fast powerful free Python IDE. It has a user-friendly interface and offers many features that greatly simplify the process of developing in Python:

  • Code editor with syntax highlighting.
  • Built-in Python interpreter with debugging, editor views, and code exploration.
  • The ability to use drag-and-drop operations for editing, context indentation, curly bracket highlighting, and syntax highlighting.
  • Check syntax as you type.
  • Ability to create templates by saving layouts with specified names.
  • Automatic code completion.
  • Ability to run created programs in different ways.
  • The ability to track the history of teams.

Install PyScipter and appreciate the benefits it provides for creating and running Python scripts.

FAQ

How do you pass arguments to a Python script?

To pass arguments to the Python script, you need to use the command line and specify the necessary arguments after the name of the script file.

How do you pass multiple arguments to a Python script?

You need to specify the required number of parameters in the function definition. When running a script, list all the arguments one by one after the script name.

How many arguments can be passed to a Python script?

There is no limit to the number of arguments that can be passed to a function when it is called. So you can use as many arguments as you need.

What are the 4 types of arguments in Python?

  1. Default arguments are arguments that have a default value that is used if no other value has been passed to the function.
  2. Keyword (named) arguments are arguments whose value is assigned by their name. When a function is called, not only the value of the argument should be passed, but its name, the ‘=’ assignment sign, and the value.
  3. Positional arguments are arguments whose values are assigned based on their position when the function is called. For example, the first positional argument must come first when calling a function. By default, Python functions use positional arguments.
  4. Arbitrary arguments. They are used when it is not known in advance how many arguments need to be passed.

How to give input to a Python script from command line?

Use the input() function to get the string or number that the user has entered.

The post What Are Command Line Arguments And How To Pass Arguments To A Python Script first appeared on Python GUI.

]]>
https://pythongui.org/what-are-command-line-arguments-and-how-to-pass-arguments-to-a-python-script/feed/ 0 9122
How to Write Your First Python Script Like a Professional? https://pythongui.org/how-to-write-your-first-python-script-like-a-professional/ https://pythongui.org/how-to-write-your-first-python-script-like-a-professional/#respond Wed, 21 Dec 2022 11:00:00 +0000 https://pythongui.org/?p=9088 Python is one of the most popular programming languages. Beginners and professional programmers use it to perform tasks of varying difficulty. This language is easy to learn, so if you are just a novice Python...

The post How to Write Your First Python Script Like a Professional? first appeared on Python GUI.

]]>
Python is one of the most popular programming languages. Beginners and professional programmers use it to perform tasks of varying difficulty. This language is easy to learn, so if you are just a novice Python script writer, you can easily get started. In this article, we will talk about how to set up a working environment, what tools to use, and how to write Python script.

What is a Python script?

A Python script is a plain text file with a .py extension that contains lines of Python code. Python code is very similar to pseudocode. It has a simple syntax and is easy for beginners to learn.

How to write a Python script?

Install Python3

To start creating and running Python scripts, first, you need to install Python on your system. Download the latest stable version of Python from the official website and install it by following the instructions. After that, you will be able to run your scripts using python script.py and get an interactive shell on the command line by typing in python at the terminal prompt.

How to Write Your First Python Script Like a Professional? The Python interactive shell

How to choose a Python code editor?

You can use any text editor for Python programming. For example, Notepad or GEdit. For greater convenience, you can choose such editors as Notepad++ or Sublime Text. They support automatic code formatting and syntax highlighting. There are also code editors that have code debugging tools, auto-completion and IntelliSense, easy navigation, and many other useful features.

Another way to write Python code is to use an integrated development environment (IDE), which includes different development tools in a single application. The final choice of code creation program depends on your needs.

How to create a Python script file

Create a folder on your computer in which you will save Python files. Open the folder in your code editor and create a file called circle.py. Place the following Python commands in it:

# Define variable radius
radius = 10

# Calculate area
area = 3.14 * 2 * radius

# Print result
print("Area of the circle is", area)

In this example, we created a variable radius and assigned it a value of 10. After that, we calculated the area of a circle with a given radius and printed the result on the screen.

Now let’s complicate this example. The radius variable will be entered by the user, and the value of the circle area will be calculated in a function that will have one input argument and return the result.

# Define area function
def area(radius):
    result = 3.14 * 2 * radius
    return result

# Read number and convert it to int
radius = int(input("Enter a number: "));

# Call area function and print result
print("Area of the circle is", area(radius))

If a non-integer value is specified when entering the radius, the program will generate an error. You should use the try-catch block to handle errors in Python programs.

# Try block
try:

    # Define area function
    def area(radius):
        result = 3.14 * 2 * radius
        return result

    # Read number and convert it to int
    radius = int(input("Enter a number: "));

    # Call area function and print result
    print("Area of the circle is", area(radius))

# Exception block
except (ValueError):
    # Print error message
    print("Error! Please, enter a numeric value")

If you want the created code to run several times, you need to use a loop. Let’s add a while loop to the created example, which will allow us to calculate the area of the circle 5 times for different radiuses.

# Try block
try:
    
    # Define area function
    def area(radius):
        result = 3.14 * 2 * radius
        return result

    # Initialize counter
    counter = 0
    # Iterate the loop 5 times
    while counter < 5:
        # Read number and convert it to int
        radius = int(input("Enter a number: "));

        # Call area function and print result
        print("Area of the circle is", area(radius))

        # Increment the counter
        counter = counter + 1

# Exception block
except (ValueError):
    # Print error message
    print("Error! Please, enter a numeric value")

How to run Python script?

To run the created script, open the folder containing the script file in the command line and execute the following command:

python circle.py

The result of the execution of the program is shown in the figure.

How to Write Your First Python Script Like a Professional? The program execution results

If you use an IDE to write Python scripts, then you can run the finished script using its tools.

Why should you use PyScripter Python IDE for writing Python scripts?

PyScripter is a free, powerful, and open-source Python IDE. It has a simple and user-friendly interface that you can easily learn, even if you do not yet have much experience in Python development.

PyScripter offers all the features you need for easy and fast development:

  • Modern and simple graphic interface.
  • Syntax highlighting.
  • Code auto-completion.
  • Full Python debugging with remote debugging support.
  • Integrated Unit testing.
  • Integrated Python interpreter.
  • Ability to run scripts without saving them.
  • And more.

In addition, there is a large community of developers who will help you in solving problems that may arise.

Start creating Python scripts with PyScripter and see that this tool is perfect for you!

FAQ about writing a Python script

Where can I write Python script?

Python scripts are text files, so you can use any text editor to write them. For example, Visual Studio Code, Notepad++, Vim, etc. But the best option for writing a Python script is to use an IDE, as it offers several tools to speed up and simplify scripting. For example, PyScripter Python IDE, IDLE, and PyCharm.

How do you write a Python script?

To begin with, you need to install Python and choose a code editor which you will use to create the script. After that, create a new py file and put the script in it. You can create your functions and import libraries to reuse ready-made functionality.

Is Python scripting easy?

Yes, Python is considered one of the easiest programming languages for beginners to learn. If you have never written Python scripts, you can easily start doing it.

How do I start coding a Python script?

You need to install Python and use any text editor to write a Python script. Create a Python file called “hello.py” and put the following code there: print(“Hello World”). After running the script, the message “Hello World” will be displayed on the screen.

Is Python a script or code?

Python is an interpreted programming language. To run a Python program, the source code is converted to bytecode, which is run by an interpreter. Therefore, Python is a scripting language.

The post How to Write Your First Python Script Like a Professional? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-write-your-first-python-script-like-a-professional/feed/ 0 9088
What Is Quantum Chemistry And How To Do It Easily In Python? https://pythongui.org/what-is-quantum-chemistry-and-how-to-do-it-easily-in-python/ https://pythongui.org/what-is-quantum-chemistry-and-how-to-do-it-easily-in-python/#respond Mon, 19 Dec 2022 11:00:00 +0000 https://pythongui.org/?p=9067 What is quantum chemistry? What do you think of when you hear the word chemistry? You imagine explosions, smoking glassware, and colorful compounds, right? But did you know that chemistry can be done outside a...

The post What Is Quantum Chemistry And How To Do It Easily In Python? first appeared on Python GUI.

]]>
What is quantum chemistry?

What do you think of when you hear the word chemistry? You imagine explosions, smoking glassware, and colorful compounds, right? But did you know that chemistry can be done outside a lab, and we can use Python tools to help too? There are chemical reactions that are difficult to perform experimentally. The reagents might be too expensive, the process outcome might be yet unknown, or it might be too time-consuming to perform a large series of reaction pathways in order to see which ones (if any) give the desired product. Chemistry can also be done by modelling atoms’ and molecules’ chemical and physical properties. The field of computational chemistry includes several research areas, including quantum chemistry and molecular dynamics.

What Is Quantum Chemistry And How To Do It Easily In Python? A chemist with a pipette and test tubes

An introduction to quantum chemical calculations

Quantum chemistry is a borderline field where chemistry and quantum physics meet. Quantum chemists typically use supercomputers to perform complicated calculations.

Quantum chemical calculations aim to obtain the total energy of a molecule and, from there, derive its properties. It sounds simple, however, only very few cases can be solved exactly, one of which is the hydrogen atom. The so-called Schrödinger equation can be solved for practically all molecules after applying a series of approximations. Not even the most powerful supercomputer can give the exact solution.

Quantum chemistry has been traditionally implemented using Fortran and C, though, in recent times, Python scripting has become increasingly popular due to its simplicity and the pre-existing libraries.

What Is Quantum Chemistry And How To Do It Easily In Python? A laptop screen showing an atomic structure

Atoms and molecules

Everything around us consists of atoms organised in a specific way. Some atoms form crystalline lattices, while others combine into molecules. Most of these interactions are due to how the electrons of the atoms respond to each other.

Electrons have specific energy, and they are assigned to what are called orbitals. The term came about at the time when scientists believed that electrons are moving around the atomic nuclei just like planets orbit around the Sun. This was later proven to be wrong.

Electrons exhibit wave-particle duality, which is an unintuitive concept where the electron can act as a wave or as a particle in different cases. This is an intrinsic property of many particles.

pexels-rafael-classen-rcphotostockcom-10670941

What does quantum mechanics tell us about chemical systems?

Electronic structure theory describes the electronic behaviour and the electronic configuration of atoms, molecular systems and materials. Within it, molecular orbital theory describes how chemical bonding occurs as an overlap between atomic orbitals. Typically, a chemical bond is formed by two electrons.

Knowing the energy and the electronic structure of a chemical system makes it possible to derive its properties, such as chemical reactivity and spectroscopic behavior.

How do we know that the quantum mechanical model is correct?

As mentioned above, the exact solution to the Schrödinger equation is usually unknown. The calculations give approximate results. They need to be compared to experimental data for a set of cases before the quantum chemical method can be used routinely.

Significant advances came about in the 90s when a method called density functional theory (DFT) started to predict chemical properties accurately. The results obtained from such studies can explain the nature of various molecules, and it serves as a starting point for further investigations.

What Is Quantum Chemistry And How To Do It Easily In Python? A formula written on a blackboard in chalk

What is quantum chemistry used for?

Modern quantum chemistry is a widely recognised field of science that is indispensable in rationalising chemical reaction mechanisms, predicting molecular properties and developing new materials for various practical applications.

Large systems of thousands of atoms are typically too heavy to perform. A protein would require months and even years to complete the computation, even when using a simplified approximation.

How can we implement quantum chemistry in a Python program?

One masterful implementation of various theoretical methods is done in the PySCF code available as a package that can be installed using pip. I use PyScripter to perform calculations with a relatively low computational cost on my personal computer. Heavier ones can only be done on a supercomputer where they run on many processors, sometimes for several days.

How to install PySCF?

PySCF is available for Linux and Mac. Currently, compilation under Windows fails because some libraries do not exist for Windows. Linux users only need to type

pip install pyscf

Preferably, pip is part of a conda installation so that other required packages are pre-installed.

You will see the following error if you try installing PySCF under Windows:

What Is Quantum Chemistry And How To Do It Easily In Python? An MSBuild command line

I have installed PySCF on the Windows Subsystem for Linux (WSL). There are many tutorials online on how to enable it. I can write PySCF scripts using the feature of PySCF to open remote files. The WSL virtual machine is the “remote” server in this case. For more information, check out this blog post:

In the SSH server settings, I have defined the hostname as localhost, and I use the program called Putty to handle the SSH connection.

What Is Quantum Chemistry And How To Do It Easily In Python? A screenshot of the SSH connection details

How to calculate molecular properties in PyScripter

A PySCF run requires that specific parameters be defined in an input file. The computational method, the coordinates of the atoms have to be specified

I need to create an input file where I will add the values that the code needs.

First, I need to prepare the molecular structure by drawing it in an external program called Avogadro. It is free and open source. The nuclear positions are shown as balls for simplicity. The red one is oxygen, and the two white ones are hydrogen atoms. You probably still remember basic chemistry that H2O is the formula of water.

What Is Quantum Chemistry And How To Do It Easily In Python? An image of an atomic structure

Next, I went to the menu Extensions and selected Gaussian, which opens a small window with some settings. What I am interested in are the coordinates of the atoms in the text field. The last three rows contain the chemical symbol, O or H, and three numbers for each of them. These are the x, y and z coordinate. The rest of the settings in this window are not relevant to the example. I will copy the three lines and use them in the input file for PySCF.

What Is Quantum Chemistry And How To Do It Easily In Python? A screen shot of Avogadro

The input file starts by importing two modules from the PySCF package. The data structures are initialised, and the coordinates from Avogadro are subsequently given inside quote marks.

After the coordinates, I need to specify something called the basis set. It consists of mathematical functions that are used to approximate the molecular orbitals in the calculation.

Then, I tell PySCF to analyse if the molecule is symmetric – which is true for water.

#!/usr/bin/env python

from pyscf import gto, scf

mol = gto.Mole()

# optionally enable a more detailed output
# mol.verbose = 4

# defining the molecule
mol.atom = '''
O        -1.82473        1.24653       -0.01294
H        -0.85684        1.28190        0.01714
H        -2.10358        1.95337        0.58838'''

# specifying the basis set
mol.basis = 'ccpvdz'
mol.symmetry = 1
mol.build()

# Computational method
# Hartree-Fock theory
mf = scf.RHF(mol)
mf.kernel()

# Perform additional analyses
# mf.analyze()

I can save and call the above script just like any other Python script, and it gives the energy of the molecule.

$ ./scf.py
converged SCF energy = -76.0267679973746

What happens under the hood?

The user defines the parameters in the Python script that calls PySCF. The first step is constructing the so-called Fock matrix, which is essentially a way of representing molecular orbitals using a set of mathematical functions called a basis set. Each function is taken with a certain weight. These weight coefficients are optimised during the calculation. They are used to calculate the energy of the molecule. By varying the values, one obtains different energies. A theorem states that the lower the energy, the closer it is to the correct value. Typically, a specific threshold is compared to the difference in the energies of two sets of coefficients in the matrix.

What happens if I choose another computational method for PySCF?

If I select another computational method, the energy will be slightly different. I have replaced the lines under the comment “Hartree-Fock theory” with the following ones:

# Density functional theory
mf = mol.KS()
mf.xc = 'b3lyp'
mf.kernel()

Everything else in the script is unchanged. Here, I am using a popular density functional called B3LYP. There are hundreds of other options.

Calling PySCF gives the value

converged SCF energy = -76.3832396709755

You might be wondering why the numbers are not identical. Why are there different methods to begin with? Well, it is complicated.

The problem stems from the fact that it is impossible to measure what molecular orbitals are like, so we need to do mathematical tricks to approximate them. Only an infinite number of basis functions can approximate exactly the actual orbital. Apparently, we cannot use an infinite number of functions on a computer, so we have to limit them to a feasible amount.

What Is Quantum Chemistry And How To Do It Easily In Python? A person looking very happy with a piece of paper in their hand a laptop computer in front of them

What have you learned about quantum chemistry?

You made it to the end, congratulations!

Quantum chemistry is an exciting field of science. I am biased because it is my job, but I am sure many will get interested in checking what it is like to be a researcher. How about you calculate the energy of aspirin? Or maybe caffeine?

Take up the challenge and set up PySCF to become a quantum chemist, too!

PyScripter is available for download for free at

https://www.embarcadero.com/free-tools/pyscripter/free-download

What Is Quantum Chemistry And How To Do It Easily In Python?  A blackboard showing the chemical structure and formular for caffeine.

The post What Is Quantum Chemistry And How To Do It Easily In Python? first appeared on Python GUI.

]]>
https://pythongui.org/what-is-quantum-chemistry-and-how-to-do-it-easily-in-python/feed/ 0 9067
What’s The Best Python Graph Tool To Solve Your Business Problems https://pythongui.org/whats-the-best-python-graph-tool-to-solve-your-business-problems/ https://pythongui.org/whats-the-best-python-graph-tool-to-solve-your-business-problems/#respond Mon, 12 Dec 2022 11:00:00 +0000 https://pythongui.org/?p=8966 The need for graphing arises in various types of business, as they are often used to solve various tasks. That’s why it’s important to have a simple and convenient graph tool. Python offers a number...

The post What’s The Best Python Graph Tool To Solve Your Business Problems first appeared on Python GUI.

]]>
The need for graphing arises in various types of business, as they are often used to solve various tasks. That’s why it’s important to have a simple and convenient graph tool. Python offers a number of such tools. Using built-in functions, you can easily build and customize complex graphs of different types. So, what business problems do graphs solve, and what is the best graph tool Python available to build them? You will get the answers to these questions after reading this article.

What business problems can you solve with graphs and the right graph tool?

To solve most business problems, it is necessary to analyze some amount of data. With a graph, you can combine different sets of data into a structure that allows you to discover relationships and find the cause of a problem. Let’s look at some types of problems that can be solved using a graph.

  • Problems with the computer network. With the help of a graph, you can conveniently model a computer network, determine what parts it consists of, what connection method is used, etc. Using this information, you can easily find bottlenecks and ways to optimize the network.
  • Path problem. Graphs are used to solve the known problem of finding the shortest and longest path from a starting point to a final destination.
  • Fraud detection. Customer data and business events can be displayed graphically. Looking for suspicious patterns in customer activity data and cross-references to previously identified fraud will help spot potential fraud that may be ongoing.
  • Project Management. With the help of a graph, you can depict the sequence of events, which allows you to sort them according to priority, find the most important event, and calculate the number of resources that are necessary for the implementation of the project.
  • The problem of satisfying constraints. This is a common AI problem. To solve it you need to find a specific goal that satisfies a list of all constraints. Such problems are often modeled and solved using graphs.
What's The Best Python Graph Tool To Solve Your Business Problems - a laptop user with a collection of graphs on their laptop

What are the chart types?

Different types of charts are used to display data graphically. Each of them is used for different types of tasks. Below we list the most common types of charts.

  • Histogram. This graph type is used to quickly compare data by category, highlight differences, show trends, and identify historical highs and lows.
  • Line chart. It connects several different data points and is used to visualize trends in data over time.
  • Scatter chart. Represents many different data points on a single chart. It is used to study the relationship between different variables.
  • Treemap. Connects different segments of your data set to the whole. In this diagram, each rectangle in the treemap is subdivided into smaller rectangles or sub-rectangles depending on its proportion to the whole.
  • Bar chart. Used to compare different items or to show a comparison of items over time.
  • Area chart. This is a line chart, but the space between the horizontal axis and the line is filled with color or pattern. It is used to display the part-whole connection, display changes over time, and visualize large trends.

What are the best Python data visualization tools?

There are various Python graph tools that allow you to easily construct beautiful and user-friendly graphs. Let’s consider the most popular of them.

Matplotlib

Matplotlib is a popular Python package used to build interactive 2D graphics. It allows you to create static, interactive, and dynamic presentations. With Matplotlib, you can plot line graphs, scatter plots, bar graphs, and more.

The Matplotlib package is easy to understand and use. It allows you to create high-quality images in various formats including png, pdf, etc. In addition, Matplotlib controls various aspects of the image such as color, font size, etc.

This library requires additional code to be written to create a visualization, as it is low-level. Also, it is not suitable for time series data because it requires importing all the helper classes for the year, month, week, and day format.

Seaborn

Seaborn is a popular Python data visualization framework based on Matplotlib. It allows you to create beautiful and important statistical visual images. Seaborn offers a large library of graphical objects that includes bar graphs, pie charts, histograms, scatter charts, and more. It also includes many color palette selection tools. Seaborn is used for visualizing univariate and bivariate data, plotting time series data, and more.

This library is easy to use and offers simple graphing tools. You can easily change the data display format. Seaborn creates a dynamic and informative graph for data presentation, which simplifies the process of data analysis.

Among the disadvantages of Seaborn, it is worth noting that it has limited customization options and rarely uses interactive visualizations.

The Ggplot graph tool

Ggplot is a Python data visualization package that can create histograms, pie charts, scatter plots, error plots, etc. using a high-level API. It also allows the combining of many types of data visualization components or layers into a single visualization.

The Ggplot library is easy to use and has detailed documentation. You can use its save method if you need to show your presentations or discuss your ideas with colleagues.

Ggplot is not recommended for building highly specialized visualizations.

What's The Best Python Graph Tool To Solve Your Business Problems - a laptop running Ggplot

Plotly graph tool

Plotly is an open-source Python 3D data visualization library. With Plotly, you can create web data visualizations, plot scatter charts, histograms, line charts, bar charts, box charts, line charts, multiple axes, 3D charts, and more.

You can share finished graphs without revealing the code. Plotly has a simple syntax and also allows you to create visualizations using a graphical user interface. Using a variety of interactive tools, you can build 3D graphs. An important advantage of Plotly is its beautiful and convenient design.

Plotly’s weaknesses are its outdated documentation and confusing initial setup. In addition, it is quite difficult to associate graphs with one data source.

Geoplotlib

Geoplotlib is a Python data visualization library that allows you to plot geographic data and create maps of various formats. It can zoom in and out of the map, allowing them to show more detail. It handles full dataset import, map projection, and map fragments. Geoplotlib has hardware acceleration enabled.

Bokeh graph tool

Bokeh is a popular Python data visualization library that allows you to create detailed, highly interactive images for a variety of datasets. With Bokeh, you can easily create responsive graphics with high-performance interactivity for large or streaming datasets.

This library supports zooming, panning, selection, etc. It provides a low-level interface with additional flexibility for chart customization. Interactive graphics created with Bokeh can be saved in PNG and SVG formats.

Bokeh lets you create many of the same plots as Matplotlib, but with less code and higher resolution.

The main disadvantages of Bokeh are the lack of a three-dimensional graphics function and limited interactivity for work.

Pygal

Pygal is a popular Python package for creating interactive graphs that can be pasted into a web browser. It supports various types of charts such as line, bar, histogram, radar, pie charts, tree charts, etc.

With Pygal, you can create dynamic and interactive graphics on a web page. It allows you to create beautiful graphics using minimal coding. You can export finished graphics to various formats, including SVG, PNG, and others.

Pygal is not recommended for working with large data sets that contain thousands of points.

What's The Best Python Graph Tool To Solve Your Business Problems - a line graph

How to build graphs in Python easily using a graph tool?

PyScripter is a fast, feature-rich, and powerful open-source Python IDE. It packs a lot of features to make writing and debugging code easier. Download PyScripter for free and get a powerful tool for building graphs in Python.

FAQ

What is a graph algorithm in Python?

Python graph algorithm is a set of instructions that are executed to render a graph. Some graph algorithms implement the search for a specific node or a path between two given nodes, searching for maximum and minimum values.

Is there a graph tool module in Python?

Python has some great libraries for working with graphs. For example, NetworkX, python-igraph, graph-tool, and others.

Is Python good for plotting graphs?

Python has several simple and useful libraries that allow you to construct and manipulate beautiful graphs of various types, so it is good for graphing.

Which Python module is used to create graphs?

Matplotlib, Pygal, Bokeh, Geoplotlib, Plotly, Ggplot, and others.

The post What’s The Best Python Graph Tool To Solve Your Business Problems first appeared on Python GUI.

]]>
https://pythongui.org/whats-the-best-python-graph-tool-to-solve-your-business-problems/feed/ 0 8966
How To Build A ToDo TUI Application With Textual https://pythongui.org/how-to-build-a-todo-tui-application-with-textual-2/ https://pythongui.org/how-to-build-a-todo-tui-application-with-textual-2/#respond Fri, 09 Dec 2022 11:00:00 +0000 https://pythongui.org/?p=8821 Did you know it’s possible to build a rich UI that runs completely in the terminal? Even some experienced Python developers avoid using the terminal in favor of Graphical User Interfaces (GUIs). But, today, many...

The post How To Build A ToDo TUI Application With Textual first appeared on Python GUI.

]]>
Did you know it’s possible to build a rich UI that runs completely in the terminal? Even some experienced Python developers avoid using the terminal in favor of Graphical User Interfaces (GUIs). But, today, many developer tools use a Terminal User Interface (TUI) since they often spend a lot of time working in the terminal. Not only are there programs and tools, but there are also several games that run entirely in the terminal.

So, in this article, we will first develop a good understanding of TUIs and then move on to creating an interesting TUI using PyScripter to manage to-do lists.

What is a TUI?

How To Build A ToDo TUI Application With Textual - a close-up of a laptop showing a Python script being edited

A TUI, short for Terminal User Interface, uses the terminal’s advanced features as the basis for a kind of GUI, generally occupying the full area of the terminal. It uses escape codes on UNIX platforms and proprietary console commands on the Windows platform to take control of the entire console window and display a user interface. TUIs can handle input via the keyboard, but some modern systems also use mouse input. This is what makes them very special and different from conventional terminals.

Thus, a TUI allows users to interact with a program via the terminal. The TUI applications interact via UI, although many TUI programs also accept commands.

Why is Textual popular for making TUIs?

Textual is a Python framework for creating interactive applications that run in your terminal. It mainly adds interactivity to Rich, a rich text and formatting library, with a Python API inspired by modern web development.

On modern terminal software, Textual apps offer more than 16 million colors, mouse support, and smooth, flicker-free animation. Furthermore, a powerful layout engine and reusable components make it possible to build apps that rival the desktop and web experience.

Currently, the Textual framework runs on Linux, macOS, and Windows and requires Python 3.7 or above.

How to build a ToDo list TUI in Python?

How To Build A ToDo TUI Application With Textual - the PyScripter download page shown on a laptop

Let us now move to the main part of this tutorial and build a to-do list in Python. But first, there are some requirements that you need to install.

What are the requirements for this TUI tutorial?

For this tutorial, you will need Python 3.9+ installed on your computer. You might also need to install a feature-packed IDE like PyScripter to write the code.

Then, you can install textual via PyPI.

If you intend to run Textual apps simply, install textual using the following command:

pip install textual

However, if you plan to develop Textual apps, you should install "textual[dev]". This is because the [dev] part installs a few extra dependencies for development.

pip install "textual[dev]"

Now that we are done setting up our environment, let’s start building our ToDo list manager.

How to create a basic ToDo in textual?

We’ll start this tutorial by creating a TUI in Textual that serves our purpose and then add to it using Textual’s amazing CSS-supported features.

How To Build A ToDo TUI Application With Textual - part 1

First, we will create a file named Todo.py and import some functions required for our ToDo application:

from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Button, Header, Footer, Static

done = [] # All completed tasks will be added

The first line imports the App class that will act as the base of our application. Next, we import Container from textual.containers. As the name implies, this acts as a widget containing other widgets. 

Finally, we import Header, Footer, Button, and Static. The Header widget shows up at the top of our app and shows the title at the top of the app. The Footer, on the other hand, shows a bar at the bottom of the screen with bound keys. The Button creates a clickable button and Static acts as a base class for simple control. In addition, we also define a list named done that will contain all of the user’s completed tasks.
Let’s first create our Task class:

class Task(Static):
    """A widget to display the Task."""

The Task class is a simple class that inherits from Static. This creates a static widget allowing us to display the tasks we want on our app.

Next, we will create a Todo widget that will cleanly display our Task widgets:

class ToDo(Static):
    """A ToDo widget."""
    def __init__(self, text="") -> None:
        self.text = text
        super().__init__()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Event handler called when a button is pressed."""
        self.add_class("Task_Done") # Color Changing to Green
        done.append(self.text)
            
    def compose(self) -> ComposeResult:
        """Create child widgets of a ToDo."""
        yield Button("Done", id="Done", variant="success")
        yield Task(self.text)

As you can see the ToDo widget class also extends Static. This class has a compose() method that yields child widgets consisting of a Button object and a single Task object. The Button constructor takes a label argument that displays the text on the button. It also takes two optional parameters:

  • id is an identifier that can help identify different buttons and help in applying styles.
  • variant is a string that selects a default style. The “success” variant makes the button green.

These widgets will form a single Task in our application. 
In addition, we also define an on_button_pressed() method that acts as an event handler. Event handlers are methods called by Textual in response to an event, such as a key press, mouse click, etc. Event handlers begin with on_ followed by the name of the event they will handle. Hence, on_button_pressed will handle the Button.Pressed event. Our event handler assigns a CSS class named “Task_Done” (which we will define later) to the ToDo Class whenever our Button is pressed. This will effectively change the color of our task showing that the task is done.

How To Build A ToDo TUI Application With Textual - part 2

Finally, we can start building our ToDoApp. We will first begin by creating our ToDoApp class that will inherit from App. We also create a All_Tasks list that will store all our tasks:

class ToDoApp(App):
    """A Textual app to manage ToDos."""
    All_Tasks = []

Next, we a compose() method that displays our widgets to our app:

def compose(self) -> ComposeResult:
        """Called to add widgets to the app."""
        yield Header()
        yield Footer()
        yield Container(id="Tasks") # Associate Container widget with Task object

Here we only call three widgets. The Header, Footer, and Container. The container will contain all of the ToDo widgets in our TUI. Additionally, we add an id parameter to our Container to help us add widgets.

How to add key bindings in a Python TUI app?

Next, we add bindings to our app. For our application, we will bind four keys:

  • The q key binding will help us quit our TUI.
  • The d key binding will help us toggle between a dark and light mode in our TUI.
  • The r binding will read all the tasks in our todo.txt file and add them to our TUI.
  • Finally, we add a s binding that will save all the tasks that are not done in our TUI.

To create our key bindings, we create a BINDINGS list containing tuples that map (or bind) keys to actions in your app. The first value in the tuple is any one of the keys on the keyboard; the second value is the action/ function to be called; the final value is a short description of the function:

class ToDoApp(App):
    """A Textual app to manage ToDos."""

    BINDINGS = [
        ("d", "toggle_dark", "Toggle dark mode"), # Bind the d key to toggle_dark 
        ("q", "quit", "Quit"), # Bind the q key to quit
        ("r", "read", "Read"), # Bind the r key to read 
        ("s", "save", "Save") # Bind the s key to save
    ]

    def compose(self) -> ComposeResult:
        """Called to add widgets to the app."""
        yield Header()
        yield Footer()
        yield Container(id="Tasks") # Associate Container widget with Task object

Each key binding is mapped to a function that begins as action_. For example, d will be mapped to the action_toggle_dark() function by adding action_ at the beginning of the toggle_dark that’s present in the tuple. So, now let us define our functions.
We first define the dark mode function, action_toggle_dark(), which inverts the dark attribute:

def action_toggle_dark(self) -> None:
        """An action to toggle dark mode."""
        self.dark = not self.dark

Next, we define a helper method named add_ToDo():

def add_ToDo(self, text) -> None:
        """An action to add a Task."""
        new_ToDo = ToDo(text=text)
        self.query_one("#Tasks").mount(new_ToDo)
        new_ToDo.scroll_visible()

This function simply takes in a text argument, creates a ToDo object, and adds it to our Tasks Container. This will help us add multiple tasks in our app using a file. Now, we define the action_read() method:

def action_read(self) -> None:
        """An action to read tasks from todo.txt and display in Container."""
        Tasks = self.query("ToDo") # Get current tasks in the container if there were any
        if Tasks:
            Tasks.remove() # If there were some tasks then remove all of them
        try: # Read txt file and add all the tasks to Container
            with open("todo.txt", "r") as f:
                formatted = f.read().split("n")
                for i in formatted:
                    self.All_Tasks.append(i)
                    self.add_ToDo(i)
        except:
            # If no File found Print Error.
            print("Invalid or no filename given!")

The action_read() method takes in no arguments and is triggered when we press "r" on the keyboard. The function uses self.query("ToDo") to retrieve all ToDo objects in our app. If we have any existing ToDo objects, we simply remove them by calling .remove() method.

Next, we open and read the contents of our todo.txt file. The file contains a single task in one line. We iterate over all the tasks in our file and use the add_ToDo() helper function to add each task to our Container.

Finally, we can define our action_save() method that overwrites our existing todo.txt file:

def action_save(self) -> None:
        """Called to update todo.txt file such that all tasks done are removed."""
        not_done = []
        for i in self.All_Tasks:
            if i in done:
                continue
            not_done.append(i)
        
        with open("todo.txt", "w") as file: # Rewrite the file with only those tasks that are not done
            file.write("n".join(not_done))

The function simply reads all the tasks that we have in the given text file and checks them against all the tasks that are selected as done (via the done Button on_pressed method) in our global done list. It then overwrites the todo.txt file with all tasks that are not completed.

What does the final example code for the Python ToDo list TUI app look like?

Here is what our final Todo.py looks like:

from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Button, Header, Footer, Static

done = [] # All completed tasks will be added

class Task(Static):
    """A widget to display the Task."""

class ToDo(Static):
    """A ToDo widget."""
    def __init__(self, text="") -> None:
        self.text = text
        super().__init__()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Event handler called when a button is pressed."""
        self.add_class("Task_Done") # Color chanigng to green via Text_Done class in CSS
        done.append(self.text) # Add task to done list
           
    def compose(self) -> ComposeResult:
        """Create child widgets of a ToDo."""
        yield Button("Done", id="Done", variant="success") # Adding a button that says Done
        yield Task(self.text) # Display text according to Task object details in CSS

class ToDoApp(App):
    """A Textual app to manage ToDos."""
    All_Tasks = []

    BINDINGS = [ # Binding details displayed Footer
        ("d", "toggle_dark", "Toggle dark mode"), # Bind the d key to toggle_dark
        ("q", "quit", "Quit"), # Bind the q key to quit
        ("r", "read", "Read"), # Bind the r key to read
        ("s", "save", "Save") # Bind the s key to save
    ]

    def compose(self) -> ComposeResult:
        """Called to add widgets to the app."""
        yield Header()
        yield Footer()
        yield Container(id="Tasks") # Accociate Container widget with Task object

    def add_ToDo(self, text) -> None:
        """An action to add a Task."""
        new_ToDo = ToDo(text=text)
        self.query_one("#Tasks").mount(new_ToDo)
        new_ToDo.scroll_visible()

    def action_save(self) -> None:
        """Called to update todo.txt file such that all tasks done are removed."""
        not_done = []
        for i in self.All_Tasks:
            if i in done:
                continue
            not_done.append(i)
       
        with open("todo.txt", "w") as file: # Rewrite the file with only those tasks that are not done
            file.write("n".join(not_done))
           
    def action_read(self) -> None:
        """An action to read tasks from todo.txt and display in Container."""
        Tasks = self.query("ToDo") # Get current tasks in the container if there were any
        if Tasks:
            Tasks.remove() # If there were some tasks then remove all of them
        try: # Read txt file and add all the tasks to Container
            with open("todo.txt", "r") as f:
                formatted = f.read().split("n")
                for i in formatted:
                    self.All_Tasks.append(i)
                    self.add_ToDo(i)
        except:
            # If no File found Print Error.
            print("Invalid or no filename given!")

    def action_toggle_dark(self) -> None:
        """An action to toggle dark mode."""
        self.dark = not self.dark

if __name__ == "__main__":
    app = ToDoApp()
    app.run()

How to run and test our Python ToDo list TUI app?

Before running this code, let’s create some tasks. Create a todo.txt file in the same directory as your Todo.py file and add the following tasks in separate lines:

How To Build A ToDo TUI Application With Textual - running the TUI Python app

Now let’s execute Todo.py. This will give you the following output in the terminal:

How To Build A ToDo TUI Application With Textual -the Python ToDo app screen in action

If we press "r", the tasks contained in todo.txt will appear in the TUI:

How To Build A ToDo TUI Application With Textual - lot of buttons

Clicking the “Done” button will cause these tasks to be appended to our done list. For example, pressing the “Done” button corresponding to “Gym” will cause “Gym” to be appended to our done list. 

Pressing “s” will cause the completed tasks to be removed from todo.txt:

How To Build A ToDo TUI Application With Textual - a screenful of todo items

Even though the buttons are clickable and you can scroll the container, our TUI is not very interactive. This is because we have not applied any styles to our new widgets. That is where Textual’s new features come in. 

How to enhance this Python TUI using CSS?

CSS files are data files loaded by your app which contain information about styles to apply to your widgets. Textual has CSS support, allowing you to customize your application. As mentioned before, we can make our TUI more visually appealing using CSS. For this, let’s go ahead and create a CSS file, Todo.css.

How To Build A ToDo TUI Application With Textual - some example CSS

CSS files contain several declaration blocks. Here’s the first block that Todo.css will contain:

ToDo {
    layout: horizontal;
    background: #36454F;
    height: 7;
    margin: 1;
    min-width: 50;
    padding: 2;
}

The first line tells Textual that the styles should apply to the ToDo widget, while the lines between the curly brackets contain the styles themselves. layout: horizontal aligns child widgets horizontally from left to right. background: #36454F sets the background color to #36454F or charcoal but there are also other ways to specify colors, such as rgb(54,69,79). height: 7 sets the widget’s height equivalent to seven lines of text. margin: 1 will set a one-cell margin around the ToDo widget to create some space between widgets in the list. Now, min-width: 50 sets the width of the widget to at least fifty cells. Note that there is no maximum so that the width can go on to cover an entire window. Lastly, padding: 2 will set a padding of two cells around its child widgets to avoid cluttering.

Following are the contents of the rest of Todo.css:

Task {
    content-align: center middle;
    text-opacity: 70%;
    height: 3;
}

Button {
    width: 10;
    dock: left;
}

.Task_Done {
    text-style: bold;
    background: $success;
    color: $text;
}

The Task block aligns text to the center (horizontally) and middle (vertically) and sets its height to three lines. Using text-opacity, we can even fade the text slightly.

The Button block sets the width of buttons to ten cells equivalent to character widths and sets the dock style to left to align the widget to the left edge. 

We also wanted our ToDo widget to have two states. One would be a default state with a Done Button and the other when the Done Button is clicked; the widget has a green background and bold text. Thus, the last class is a rule where “.” indicates that .Task_Done refers to a CSS class called Task_Done. The new styles will only be applied to widgets with this CSS class. In the background and color options, the $ prefix picks a pre-defined color from the built-in theme. 

And we’re all done with styling our TUI. So, let’s add the path of this CSS path to our ToDoApp class in Todo.py to integrate our CSS file with our TUI app (it is interesting to note that Textual supports multiple CSS paths):

CSS_PATH = "Todo.css"
How To Build A ToDo TUI Application With Textual - showing where to edit the CSS path

Finally, we can run our app again to test it out:

How To Build A ToDo TUI Application With Textual - lots of buttons but repositioned and made more pleasing due to the CSS

You can mark “Cook” and “Study” as done by clicking on their corresponding buttons:

How To Build A ToDo TUI Application With Textual - a different look thanks to more CSS

You can then save this updated to-do list by pressing the “s” button. If we press “r” again, we can see the changes:

How To Build A ToDo TUI Application With Textual - CSS number 3

We can also confirm these changes by rechecking todo.txt:

How To Build A ToDo TUI Application With Textual - the ToDo list app

You may have noticed that we have used PyScripter throughout this project. This is because PyScripter is one of the best tools that you can have to organize your code and understand it better. So if you are starting with Python, PyScripter should be part of your starter kit.

Why should you use PyScripter to create TUIs?

How To Build A ToDo TUI Application With Textual - the DelphiFMX and PyScripter download page on a laptop screen

Embarcadero sponsors PyScripter, a popular, free, and open-source Python IDE. This IDE has all the features you’d expect from a modern Python IDE while remaining lightweight and fast. PyScripter is natively compiled for Windows, allowing it to use as little memory as possible while providing maximum performance. It also has full Python debugging capabilities, both locally and remotely. Another noteworthy feature of this IDE is its integration with Python tools like PyLint, TabNanny, Profile, etc. It can also run or debug files directly from memory.

PyScripter includes all the features you’d expect from a professional IDE, such as brace highlighting, code folding, code completion, and syntax checking as you type. It also has features you’d expect to find in a legitimate native app, such as dragging and dropping files into the PyScripter IDE. These features work in tandem to save time and make the development process simple and enjoyable.

In addition, PyScripter includes a Python interpreter with call indications and code completion. This program lets you run scripts without saving them and keeps a record of your command history. This IDE also includes a remote Python debugger for debugging Python code. As a result, variables, the watch window, and the call stack are visible. Additional debugging tools built into PyScripter include conditional breakpoints and thread debugging. Furthermore, PyScripter has debugger indications to help you debug your files without saving them, as well as the ability to destroy them.

Thus, PyScripter is a fantastic IDE seeking to create a Python IDE that can compete with other languages’ traditional Windows-based IDEs. It is lightweight, versatile, and extendable with a lot of features.

Furthermore, since it was built from the ground up for Windows, it is substantially faster and more responsive than cumbersome text editors, making it perfect for making TUIs.

Are you ready to build your own Python TUI?

How To Build A ToDo TUI Application With Textual - a laptop screen displaying the download PyScripter page

Congratulations on building a stunning to-do manager TUI! In this tutorial, you have learned several useful things about Python!

Textual is a TUI framework for Python inspired by modern web development. It has a very active repository on GitHub. This awesome framework is built on Rich and is currently a work in progress, but usable by programmers who don’t mind some API instability between updates.

You can conveniently build complex and simple TUIs with Textual in PyScripter. This IDE will make the entire process very seamless and enjoyable for you.

Now that you know PyScripter’s numerous features and how Textual works, go ahead and create your own TUIs in everyone’s favorite IDE!

What are the FAQs on building a Python TUI?

How To Build A ToDo TUI Application With Textual - a laptop with the DelphiFMX and DelphiVCl page open on its screen

What are some use cases of TUIs?

TUIs can be used to make programs like stopwatches, calculators, code and other file viewers, basic games, and to-do lists (as shown in this article).

There are several other possibilities. The only limit is your imagination!!

Which other TUI libraries are available in Python?

Pytermgui, picotui, and pyTermTk are other frameworks and libraries that can create interactive and attractive TUIs in Python.

What is the difference between CLI, GUI, and TUI?

GUI means Graphical User interface. You must have heard this word most commonly. It is the GUI that has enabled the common user to use computers. A GUI application is an application that can be run with a mouse, touchpad, or touchscreen.

The CLI is a command line program that accepts text input to perform a certain task. Any application you can use via commands in the terminal falls into this category.

TUI, i.e., Terminal User Interface, falls between GUI and CLI. It can also be called a kind of text-based GUI. Before the arrival of the GUI, everything used to run on the command line; then, the terminal user interface provided a kind of GUI on the command line. TUI programs can be run via a mouse or keyboard.

What is Python4Delphi?

In short, P4D offers a selection of real-world apps that can be modified to your individual needs and used in Python GUI.

Consider integrating Delphi’s GUI and desktop app development power with Python in your applications to give world-class solutions to your clients’ needs. Python4Delphi is the answer to your problems.

Python for Delphi (P4D) is a free Delphi and Lazarus component library that wraps the Python DLL. They make it simple to run Python scripts while allowing for new Python modules and types. The best feature of P4D is that it simplifies the use of Python as a scripting language. It also includes numerous customizable demos and tutorials that are ready to use in the development of real-world apps.

The post How To Build A ToDo TUI Application With Textual first appeared on Python GUI.

]]>
https://pythongui.org/how-to-build-a-todo-tui-application-with-textual-2/feed/ 0 8821
Is Python a Scripting Language or a Programming Language? https://pythongui.org/is-python-a-scripting-language-or-a-programming-language/ https://pythongui.org/is-python-a-scripting-language-or-a-programming-language/#respond Mon, 05 Dec 2022 11:00:00 +0000 https://pythongui.org/?p=8925 What is a Python script? Is Python a scripting language? Many people have these questions. However, you are often left with confusing answers. But here’s the reality. Python is a programming language. However, you can...

The post Is Python a Scripting Language or a Programming Language? first appeared on Python GUI.

]]>
What is a Python script? Is Python a scripting language? Many people have these questions. However, you are often left with confusing answers. But here’s the reality. Python is a programming language. However, you can use it for scripting as well. But what is a scripting language? Why Python is a popular scripting language? In this post, you will find all the details.

Is Python A Scripting Language – What Are The Differences Between Programming And Scripting Languages?

Is Python A Scripting Language – What Are The Differences Between Programming And Scripting Languages?

Similar to other programming languages, Python has many variants, like Pypy and Jython. However, it is considered to be a scripting language. Because it allows you to easily write scripts.

There are several differences between programming languages and scripting languages. However, here is the main one. Scripting languages do not need compilation. On the other hand, programming languages are directly interpreted.

Similar to JavaScript, Python scripting language doesn’t need any compilation before the execution. Other programming languages, like C++, require compilation.

Script language is very simple. As a result, you can quickly learn it. Also, Python uses less code. Hence, it is easier to use than other languages.

Let’s find some more differences between programming and scripting languages.

Is Python A Scripting Language – Platform-Specific vs Platform-Agnostic

Scripting languages are platform-specific. On the other hand, programming languages are platform-agnostic. In other words, they are cross-platform. They can execute themselves. For example, you can run Java on any operating system.

Is Python A Scripting Language – Interpreted vs Compiled

Programming languages are compiled. On the other hand, scripting languages are mostly interpreted. However, some scripting languages, like Python and Groovy, are both compiled and interpreted.

Is Python A Scripting Language – Faster vs Slower at Runtime

Programming languages don’t need to be compiled in real-time. As a result, they run faster than scripting languages.

Is Python A Scripting Language – More vs Less Code-Intensive

Programming languages are more code-intensive. It requires you to manually do a lot of things. However, scripting languages are less code-intensive. Therefore, you can get the job done by writing fewer lines of code.

Is Python A Scripting Language – Standalone Apps vs Apps as Part of a Stack

There are some things that you can’t do with a scripting language. For instance, you can’t use it to create standalone desktop and mobile applications. Because there’s no runtime environment for interpreting code.

Read: How To Exit A Python Script

Is Python A Scripting Language – What Are The Features Of Scripting Languages?

Is Python A Scripting Language – What Are The Features Of Scripting Languages?

Scripting and programming languages are quite similar to one another. But when it comes to features, you will find the real differences. For example, scripting languages require you to write significantly less code than programming languages. It eliminates complexities and boosts productivity. It’s one of the best scripting language features.

Also, scripting language provides all the basic features of modern programming languages. Examples include support for powerful variable types, standard control statements, and functions.

On top of that, scripting languages are free and open source. As a result, you get complete control to view and edit code the way you like.

Is Python A Scripting Language – Confusions About Scripting Languages

You might face several confusions about scripting languages from time to time. Let’s take a look at the main one.

People often get very confused with frontend vs backend scripting languages. However, it doesn’t make much sense to speak about them.

Because developers are mostly using just one frontend scripting language, which is JavaScript. Earlier, people used different languages, such as ActionScript and JScript. However, they are all deprecated.

In the context of scripting language, frontend vs backend scripting language is not that important. Instead, the significance lies in the runtime environment. Because the scripting language runs on it.

Keep in mind that ‘frontend’ simply refers to the things that a web browser can interpret. Examples include image, font, markup, stylesheet, and script.

Read: How To Run A Python Script?

Python Scripting Vs. Programming – Is Python A Scripting Language or A Programming Language?

Python is a programming language. However, you can use it as a scripting language as well.

Developers mainly use Python as a programming language. And its popularity is continuously increasing. Also, developers use other programming languages, such as PHP, C, and Ruby. But Python remains the most popular high-level programming language of the decade.

But why is it so popular? There are various reasons. The main one is simplicity. Machine learning with Python is very easy to understand for everyone. Students and beginners find it simpler. And it’s a very important factor.

People always prefer a simple way to learn about web development. Python is very easy in many aspects. That’s why people love learning Python. The language will continue to influence the world of learners.

Python Scripting Vs. Programming – Is Python A Scripting Language or A Programming Language?

Script language has a simple syntax. That’s why it’s incredibly easy to understand. Even if you are a beginner, you won’t face any issues understanding it. Hence, Python is widely used in programming. Also, it is an interpreted language that translates code. As a result, it has become more versatile than any other scripting languages.

People find it easier to write Python programs than other scripting languages. Because the syntax is a bit easier. Also, the code is shorter to use in the programs.

Why do people consider Python to be a scripting language? The answer is pretty simple. It translates source code. People are often confused because of the blurred lines between programming and scripting languages. But technically, Python is a lot easier to understand.

Is Python A Scripting Language – Why Python Programming Is So Popular Today?

Is Python A Scripting Language – Why Python Programming Is So Popular Today?

Python is very simple. It’s one of the main reasons behind its massive popularity. It offers robust development and simple multiprocessing. Apart from being a programming language, Python is also a scripting language. Therefore, more apps can utilize it. Python primarily works as a programming language. However, it can be also used as a scripting language at the same time. As a result, it has become more appealing to a wider audience.

Python is a development language. You can utilize it in different industries. Tech companies use it in automation technology, web scraping, machine learning, image processing, and AI They equally use Python in both scripting and development.

Is Python A Scripting Language – The World of Python

Python works well as both a scripting language and a programming language. It provides a versatile solution. It has everything to meet the needs of developers and programmers. You should seriously consider investing time and energy into Python. Because it’s beneficial in many ways.

If you want to work in AI and Machine Learning, you need to have a solid knowledge of Python. Also, it’s very useful for developing web applications and analytics solutions.

Python is simple and powerful. It enables you to develop web applications with significantly less effort and time. Also, it can make you better at programming. Whether you’re a beginner or an experienced programmer, Python has everything to meet your needs.

Interpreted vs Compiled Programming Languages

An interpreted programming language has been designed to directly execute source code. It doesn’t require compiling a program into machine-language instructions. An interpreter translates statements into a series of one or more subroutines. Once the process is done, it translates them into another language, like machine code. 

In compiled programming languages, a compiler program translates high-level programming language code into a lower-level language code for execution. For example, C or Java programs need to be compiled first before execution. Have you heard about Eclipse for Java and GCC for C and C++? They are all well-known compilers.

5 Best Scripting Languages

1. Python

5 Best Scripting Languages - Python
Source: Python.org website

Python is one of the most popular programming languages on the planet. People love to use it. Thanks to the clear and concise syntax. Also, coding in Python doesn’t require you to write a lot of code. You can create powerful programs with just a few lines.

Python is free and open source. Therefore, you don’t have to spend any money to use it. Python supports structured, object-oriented, and functional programming paradigms. Also, it supports an extensive Standard Library. Overall, it’s incredibly powerful and versatile.

Code Example

Here is a Python code example. It loops through integers between 0 and 5 to print them out.

count = 0
while count < 6:
   print(count)
      count += 1

Unlike other programming languages, Python doesn’t use curly brackets. Also, semicolons are optional. Therefore, you can easily read and write code.

Read: A Beginner’s Guide To Python Tools

2. JavaScript/ECMAScript

5 Best Scripting Languages - ECMA / JavaScript
Source: https://www.ecma-international.org

JavaScript is an implementation of the ECMA-262 standard. It defines the ECMAScript (ES) general-purpose scripting language. That means JavaScript is a dialect of the ECMAScript language. Hence, it doesn’t have a standalone specification. However, it utilizes the same syntax as ECMAScript.

In JavaScript, functions are treated as variables. It allows you to reuse existing objects as prototypes. It supports prototype-based object-oriented programming.

Code Example

let total = 0, count = 1;

while (count <= 10) {
    total += count;
    count += 1;
}

console.log(total);
// 55

3. Groovy

5 Best Scripting Languages - Groovy
Source: https://groovy-lang.org

Groovy is an object-oriented language. It extends the java.lang.Object superclass. Groovy is written for the Java Virtual Machine (JVM). You can use it both as a scripting and a programming language. Groovy is open source. Hence, you can use it for free.

Similar to Java, you can use Groovy as a general-purpose programming language.

4. Bash

5 Best Scripting Languages - GNU BASH
Source: https://www.gnu.org/software/bash

You may have known Bash as a command-line interpreter (shell) for the GNU operating system. For example, Linux is a GNU operating system that uses the Linux kernel. The kernel is the core part of the OS. It’s the first program that the operating system loads.

Also, Bash is the name of a scripting language. It is written by Brian Fox for the GNU Project. It was first released in 1989.

You can use Bash to perform a variety of functions. For example, you can utilize it for executing commands. Also, it enables you to carry out a variety of tasks, creating, moving, or deleting folders and files. Most people require using a graphical user interface to perform these tasks. But you don’t need to use the GUI with Bash.

5. VBA

5 Best Scripting Languages - VBA
Source: https://learn.microsoft.com/en-us/office/vba/api/overview/library-reference

VBA stands for Visual Basic for Applications. It’s an implementation of the Visual Basic 6 programming language. Microsoft created it for MS Office applications. VBA enables developers to automate repetitive tasks. Also, it lets you conveniently add new functionalities. Besides, it allows you to interact with the end users of documents.

Conclusion

Is Python a scripting language? Definitely yes. But it’s also a programming language. As a result, it has become incredibly powerful and versatile. You can use Python to develop feature-rich web applications and powerful Machine Learning solutions. Therefore, you should seriously consider learning it.

PyScripter is a powerful Python IDE built on Delphi. It offers several amazing features, including the remote engine, remote debugger, and integrated unit testing. Try it now for free. 

FAQ

Is Python a programming or scripting language?

Python works as both a programming and a scripting language. Python is considered to be a scripting language because it is interpreted. However, Python is widely used in application development. Therefore, it is also considered to be a high-level programming language.

The post Is Python a Scripting Language or a Programming Language? first appeared on Python GUI.

]]>
https://pythongui.org/is-python-a-scripting-language-or-a-programming-language/feed/ 0 8925
Embrace The Power Of Brand New Python 3.11 Features https://pythongui.org/embrace-the-power-of-brand-new-python-3-11-features/ https://pythongui.org/embrace-the-power-of-brand-new-python-3-11-features/#respond Mon, 28 Nov 2022 11:00:00 +0000 https://pythongui.org/?p=8628 Python is a high-level, interactive, interpreted, and object-oriented scripting language that programmers, particularly data scientists, use worldwide. New versions of Python are released every year, with the final release occurring at the end of the...

The post Embrace The Power Of Brand New Python 3.11 Features first appeared on Python GUI.

]]>
Python is a high-level, interactive, interpreted, and object-oriented scripting language that programmers, particularly data scientists, use worldwide. New versions of Python are released every year, with the final release occurring at the end of the year after a feature-locked beta release in the year’s first half. Python 3.11 is the latest version of Python at the time of writing.

Python 3.11 has been under development for over seventeen months and was recently published in October 2022. It is now ready for widespread usage. Moreover, with this new version comes many new features that make it even better. The documentation for Python 3.11 contains a detailed list of all the changes and enhancements that are included in this version. In this post, we’ll examine the most interesting and useful new features that Python 3.11 offers and finally take a look at everyone’s’ favorite free python compiler and IDE: PyScripter.

Is code execution faster in this update?

Embrace the Power of Brand New Python 3.11 Features - a laptop showing some Python code

Out of all the improvements that have been made to Python 3.11, the specializing adaptive interpreter is perhaps the most significant addition to its performance improvements.

Because the type of an object rarely changes, the interpreter now tries to analyze running code and replace generic bytecodes with type-specific ones. For example, binary operations like addition and subtraction can be replaced with specialized versions for integers, floats, and strings.

Python function calls in Python 3.11 also have less overhead. Stack frames for function calls are now designed to use less memory and to be more efficient.

According to the official Python benchmark suite, Python 3.11 is approximately 1.25 times faster than Python 3.10. However, it is important to note that this speedup is an aggregate measure. Some things move much faster, while others move only slightly faster or the same. Still, the best part about these enhancements is that they are free, as no code changes are required for Python programs to benefit from Python 3.11’s speedups.

Has the syntax for asynchronous tasks changed?

Embrace the Power of Brand New Python 3.11 Features - has the syntax for async operations changed?

Python’s asynchronous programming support has evolved over time. It all began with the introduction of generators in Python 2. Then, Python 3.4 introduced the asyncio library, and Python 3.5 introduced the async and await keywords. The development has continued in subsequent releases, with many minor enhancements to Python’s asynchronous capabilities.

Task groups are the latest addition and provide a cleaner syntax for running and monitoring asynchronous tasks.

The traditional method for running multiple asynchronous tasks with asyncio has been to first create them with create_task() and then await them with gather(). This gets the job done but is a pain to work with. To address the issues associated with child tasks, Python 3.11 introduces asyncio task groups. When you use gather() to organize your asynchronous tasks, part of your code will typically look like this:

tasks = []
for p in params:
    tasks.append(asyncio.create_task(run_some_task(p)))
await asyncio.gather(*tasks)

Before passing them to gather(), you manually track all of your tasks in a list. By awaiting on gather(), you ensure that each task is completed before proceeding.

With task groups, the equivalent code is simpler. Instead of gather(), you use a context manager to specify when tasks should be awaited:

async with asyncio.TaskGroup() as group:
    for p in params:
        group.create_task(run_some_task(p))

You create a TaskGroup object named group in this example, and use its .create_task() method to create new tasks.

Do you get more information as a Pythoneer?

Embrace the Power of Brand New Python 3.11 Features - Embrace the Power of Brand New Python 3.11 Features

Are tracebacks more informative in Python 3.11?

Python is a popular beginner programming language because of its readable syntax and other user-friendly features. However, interpreting the tracebacks displayed whenever Python encounters an error is a challenge for all, especially for those new to Python.

Traceback enhancement is one of Python 3.11’s most anticipated features and improves your developer experience. For example, decorative annotations are added to the tracebacks to help you quickly interpret an error message.

Let us take a closer look at an example of enhanced tracebacks. Start by adding the following code to a file named log.py:

import math
def log(number):
    return math.log(number)

print(log(0))

The math.log() method returns the natural log of a number. However, because log 0 is undefined, your code will raise an error when you run it:

Traceback (most recent call last):
  File "/home/User/log.py", line 5, in <module>
    print(log(0)))
          ^^^^^^
  File "/home/User/log.py", line 3, in log
    return math.log(number)
           ^^^^^^^^^^^^^^^^

Note that the ^ and ~ symbols are embedded in the traceback and are used to guide attention to the part of the code that is causing an error.

Having this extra assistance in spotting errors is beneficial. If your code is more complex, annotated tracebacks become even more powerful. These may be able to convey information that the traceback alone could not previously.

To better appreciate the power of the improved tracebacks, let’s build a small parser that parses information about some individuals. For example, assume you have a file named people.json with the following content:

[
    {"name": {"first": "Ali"}},
    {
        "name": {"first": "Gauri", "last": "Kumar"},
        "birth": {"year": 1968, "month": 2, "day": 9},
        "death": {"year": 2019, "month": 1, "day": 31}
    },
    {
        "name": {"first": "Ayesha", "last": "Ahmad"},
        "birth": {"year": 2000, "month": 10, "day": 1},
        "death": null
    },
    {
        "name": {"first": "Harsh", "last": "Dutt"},
        "birth": {"year": 1981},
        "death": {"month": 1, "day": 31}
    }
]

It should be noted that the information available about these people is quite erratic. For example, while the information about Gauri Kumar is complete, Harsh Dutt's birth date, month, and death year are missing. In addition, the file only contains Ali's first name.

Now, let us create a class that can wrap this information up. We will start by reading the information from the people.json file we have created above. Let’s create a people.py file with the below code:

import json
import pathlib

people = json.loads(
    pathlib.Path("people.json").read_text(encoding="utf-8")
)

The pathlib package is used to read the JSON file, and json package is used to parse the data into a Python list of dictionaries. Following that, we’ll use a dataclass to store information about each programmer:

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    lifetime: tuple[int, int]

    @classmethod
    def from_dict(cls, info):
        return cls(
            name=f"{info['name']['first']} {info['name']['last']}",
            lifetime=f"{info['birth']['year']} to {info['death']['year']}",
        )

Each individual will be given a name and a lifetime attribute. You also include a handy constructor that can initialize a Person object based on the information and structure in your JSON file. We can now go through our code and look for any errors. Run your program with the -i flag in the terminal to open Python’s interactive REPL, which includes all variables, classes, and functions:

python -i people.py

Let’s see what happens when we have complete information about a person:

Person.from_dict(people[1])

We will get the following output:

Person(name='Gauri Kumar', lifetime=('1968 to 2019'))

Gauri's information is complete, so you can encapsulate her into a Person object with details like her full name and life span.

Try converting Ali to see the new traceback in action:

Person.from_dict(people[0])

Output:

Traceback (most recent call last):
  File "/home/Users/people.py", line 18, in from_dict
    name=f"{info['name']['first']} {info['name']['last']}",
                                    ~~~~~~~~~~~~^^^^^^^^
KeyError: 'last'

Because last is missing, you get a KeyError. While you may recall that last is a subfield within the name, the annotations make this clear immediately.

What happens with Ayesha? You only have information about her birth:

Person.from_dict(people[2])

Output:

Traceback (most recent call last):
  File "/home/User/people.py", line 19, in from_dict
    life_span=f"{info["birth"]["year"]} to {info["death"]["year"]}",
                                            ~~~~~~~~~~~~~^^^^^^^^
TypeError: 'NoneType' object is not subscriptable

A TypeError is thrown in this case. You’ve probably seen 'NoneType' type errors before. They are notoriously difficult to debug as it is not always clear which object is unexpectedly None. However, as you can see from the annotation, info["death"] in this example is None.

These tracebacks make debugging in Python 3.11 easier than in previous versions, boosting your productivity as a Python developer.

Is the error-handling mechanism enhanced in Python 3.11?

Python’s error-handling mechanism has received many new features in Python 3.11.

Now, Python can handle multiple exceptions that can be raised and handled using the new except* syntax and the all-new ExceptionGroup exception type. This enables the elegant handling of problems when many errors can be raised simultaneously, such as when dealing with concurrent or asynchronous methods or when dealing with multiple failures when you retry an action.

Furthermore, exceptions now have no cost to a program unless they are really raised. This means that the default path for a try/except block is a lot quicker and consumes less memory. In addition, the amount of time required to catch an exception has been lowered by about 10%.

This means that exceptions can be enriched with contextual notes that remain separate from the text of the exception itself.

Let’s look at an example:

try:
    raise TypeError('Bad type!')
except Exception as e:
    e.add_note('Add some contextual information')
    raise

When this error occurs:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: Bad type!
Add some contextual information

What kind of typing improvements should you expect in Python 3.11?

Embrace the Power of Brand New Python 3.11 Features - What Kind of Typing Improvements Should You Expect?

Python’s type-hinting features, which have grown dramatically with each iteration since Python 3.5, make larger codebases easier to maintain and analyze.

Let’s go over the several new type-hinting additions made in Python 3.11:

Self Type

Class methods in the previous versions of Python required verbose and obtuse annotations to be useful. Python 3.11’s all new typing.Self lets you simply annotate the return values of a class method as Self. With this, you get predictable and useful results from whatever analysis tool you may want to use.

Arbitrary String Literal Type

Previously, there was no method to declare that a given variable needed to be a string literal using type annotations (a string defined in source code). The new typing.LiteralString annotation corrects this. Using the new annotation, linters may determine whether a variable is a string defined in the source or a new string made entirely of source-defined strings.

Variadic Generics

Python 3.11 introduces TypeVarTuple, sometimes known as “variadic generics,” which allows you to define a placeholder for a succession of types given as a tuple. This would be especially handy in libraries like NumPy, where you could check for problems like whether a supplied array was the correct shape ahead of time.

So this new feature will come in handy to all Data Science enthusiasts.

What is TOML?

Embrace the Power of Brand New Python 3.11 Features - what is TOML?

TOML, which stands for Tom’s Obvious Minimal Language, is a configuration file format. It is supposed to translate unambiguously to a dictionary and be easy to read and write due to straightforward semantics that strive to be “minimal.” Its specification is open-source and receives additions from the community.

Does Python 3.11 allow TOML configuration parsing?

TOML was created to be simple for humans to read and simple for machines to parse.

TOML is used as a configuration format in Python (the preferred format for setting the metadata for packages and projects), however you cannot read TOML files as it is not available as a standard library module.

Python 3.11 introduces tomllib to address this issue, as tomllib is now part of the standard library. In addition, this new module adds support for parsing TOML files by adding to the existing and quite popular tomlib third-party library.

The following is an example of a TOML file named units.toml:

# addresses.toml
[home]
street = "123 Tornado Alley Suite 16"
city = "New Jersey"
state = "NY"

[office] 
street = "11 Broadway"
city = "New York City"
state = "NY"

[school]
street = "203 Oak Street"
city = "Maryland"
state = "NY"

The file contains several sections with headlines in square brackets. Each such section is called a table in TOML, and its headline is called a key. Tables contain key-value pairs and can be nested such that values are new tables.

The example above shows that each table has the same structure, with three keys: street, city, and state. Of course, values can have different types, but in this example, we use only strings. Now, let’s use tomlib package to read a TOML file. Let’s create a Python file test_toml.py:

import tomllib
with open("units.toml", mode="rb") as file:
    info = tomllib.load(file)
 
print(info)

Output:

{'home': {'street': '123 Tornado Alley Suite 16', 'city': 'New Jersey', 'state': 'NY'},  
'office': {'street': '11 Broadway', 'city': 'New York City', 'state': 'NY'},  
'school': {'street': '203 Oak Street', 'city': 'Maryland', 'state': 'NY'}}

For using tomllib.load(), you must pass in a file object that is opened in binary mode. This is done by specifying mode= "rb".

Moreover, rather than reading the file with open() context manager, you can parse a string with tomllib.loads(). Now comment out the above code and copy paste the below code to test_toml.py file:

import tomllib
import pathlib
units = tomllib.loads(
    pathlib.Path("units.toml").read_text(encoding="utf-8")
)
print(units)

Output:

{'home': {'street': '123 Tornado Alley Suite 16', 'city': 'New Jersey', 'state': 'NY'}, 
'office': {'street': '11 Broadway', 'city': 'New York City', 'state': 'NY'}, 
'school': {'street': '203 Oak Street', 'city': 'Maryland', 'state': 'NY'}}

In this example, pathlib is used to read units.toml into a string, which is then parsed with loads(). Therefore, TOML documents should be saved in UTF-8 format. To ensure that your code runs consistently across platforms, you should explicitly specify the encoding.

Should you install Python 3.11?

Embrace the Power of Brand New Python 3.11 Features - Should You Install Python 3.11?

The most significant gains with Python 3.11 are improved error messages and faster code execution, both of which improve the developer experience. These are excellent motivations to improve the environment that you use for local development as soon as possible. This is also the least risky type of upgrade, as any bugs you encounter should have a minor impact. The increased speed is another compelling reason to update your production environment.

However, when upgrading, it is critical to consider improved syntax. You can’t use syntax like TaskGroup() or except* in your code if you’re maintaining a library that supports older versions of Python. The good news is that your library will still be faster for anyone using Python 3.11.

Does PyScripter support the latest Python update?

Embrace the Power of Brand New Python 3.11 Features. Does PyScripter Support Python's New Update?

Well done on getting through this article! A new release of Python is always caused for celebration and acknowledgment of all the effort poured into the language by volunteers from around the world.

This tutorial has new features and improvements, better error messages and handling, faster code execution, task groups, typing features, native TOML support, and much more.

If you have programmed in Python, you must have heard of PyScripter. PyScripter is significantly faster and more responsive than bloated text editors or other Python cross-platform IDEs.

It has a built-in Python interpreter that offers call hints and code completion. This program allows you to run scripts without saving them and keeps track of your command history. For debugging Python code, this IDE also has a remote Python debugger. As a result, it’s possible to see variables, the watch window, and the call stack.

PyScripter’s features include brace highlighting, code folding, code completion, and syntax checking as you type. Furthermore, the use of Python source code tools simplifies programming for programmers. PyScripter also allows you to drag and drop files from Explorer into this IDE, which could save you time.

Since PyScripter is one of the best IDEs for coding in Python, the question naturally arises whether or not this feature-packed IDE supports Python 3.11. And the answer is that it will soon, with PyScripter’s next update, hopefully!

In the meantime, why don’t you master your Python skills in PyScripter, so that once its update is released, you can use Python 3.11 to the fullest? Click here to get some great free Python tools and get started.

Embrace the Power of Brand New Python 3.11 Features - get a free Python ebook

The post Embrace The Power Of Brand New Python 3.11 Features first appeared on Python GUI.

]]>
https://pythongui.org/embrace-the-power-of-brand-new-python-3-11-features/feed/ 0 8628
How To Exit A Python Script https://pythongui.org/how-to-exit-a-python-script/ https://pythongui.org/how-to-exit-a-python-script/#respond Mon, 21 Nov 2022 11:00:00 +0000 https://pythongui.org/?p=8758 Python is one of the most versatile programming languages on the planet. You can use it to develop a wide range of solutions. Examples include web applications, Machine Learning, Artificial Intelligence, and Data Science. Also,...

The post How To Exit A Python Script first appeared on Python GUI.

]]>
Python is one of the most versatile programming languages on the planet. You can use it to develop a wide range of solutions. Examples include web applications, Machine Learning, Artificial Intelligence, and Data Science. Also, Python is the most used programming language. Thanks to user-friendly syntax and powerful features. It’s very easy to use. You can exit a Python script whenever you want. But how can you do it? In this article, you will know how to exit a Python script. You will find different ways to easily exit program in Python. Let’s dive in.

How to exit a Python script using the quit() function

How To Exit Python Script Using the quit() Function

You can exit a Python program by using the built-in quit() function. It’s very easy to use. It doesn’t require you to import any external libraries.

quit() has a very simple syntax. Let’s take a look at it:

quit()

When the system comes up against the quit() function, it completely concludes the execution of the program.

The quit() function works only if the site module is imported. Therefore, you shouldn’t use it in production code. Because it is not suitable for use in the application code for the intended audience in a real-world situation. You should use the quit() function only in the interpreter. It raises the SystemExit exception.

Read: How To Run A Python Script?

To understand the quit() function, create a Python file and add the following script:

for value in range(0,10):

     # If the value becomes 6 then the program prints quit 
     # message and terminates via quit()

    if value == 6:
     # Prints the quit message
        print(quit)
        quit()

    # Values get printed till the program terminates
    print(value)

Now, run the code. You will see this output:

0
1
2
3
4
5

How to exit a Python Script using the sys.exit() function

How To Exit A Python Script Using the sys.exit() Function

You can import the sys module to your Python code. It provides various variables and functions. You can utilize them to manipulate different pieces of the Python runtime environment.

The sys.exit() function is an in-built function of the sys module. You can use it to exit the Python program.

The sys.exit function accepts an optional argument. You can utilize it to output an error message. Its default value is 0, which indicates successful termination.

You can use sys.exit() function at any time to exit the execution process. You won’t face any issues.

Read: This Is How To Check Python Code

To use the method, you have to import sys. Then you need to call the exit() method on the sys object.

You can utilize the sys.exit() function in your Python program in the following way:

import sys
a = 5
if a != 12:
    sys.exit("Values don't match unfortunately")  
else:
    print("They match")

You will get this output:

Values don’t match unfortunately

How to exit a Python script using the exit() function

How To Exit A Python Script Using the exit() Function

exit() function is another great option. It enables you to effortlessly end your Python program.

exit() is an alternative to the quit() function. It can make the code a bit more user-friendly. However, you should use it only in the interpreter.

You can utilize the exit() function in your Python program in the following way:

for a in range(1,5):
    print(a+2)
    exit()

You will get this output:

3

As you can see, sys.exit() is very easy to use. That’s why it has become one of the most popular methods to terminate a Python program.

You can implement both exit() and quit() functions only when you import the site module. However, they cannot be used in the production and operational codes.

How to exit a Python script using the KeyboardInterrupt command

How To Exit A Python Script - a person sitting cross legged on a couch with a laptop on their knees

Is your Python program running in the console? Try pressing CTRL + C on Windows or CTRL + Z on Unix. You will find that an exception has been raised in the main thread. It’s called KeyboardInterrupt.

What happens if the Python program doesn’t catch the exception? It will exit the script. You need to utilize except: for catching this exception. It may prevent Python program from exiting.

If KeyboardInterrupt doesn’t work for you, then you can consider using the SIGBREAK signal. You just need to press CTRL + PAUSE/BREAK on Windows.

In Linux/Unix, you can find the PID of the Python process by using this command:

ps -ef|grep python

To kill the python process, you need to utilize the kill -9 command.

Example:
If the PID of the Python process is 6243, you can kill it by utilizing this command:

kill -9 6243

If you are using Windows, you can use the taskkill command to end the process. Also, there are alternative ways. For example, you can open task manager, find python.exe, and end the process.

Read: A Beginner’s Guide To Python Tools

How to exit a Python script using Raise SystemExit

 

How To Exit A Python Script - a close-up of a laptop screen using a bokke blur

The main functionality of the raise keyword is to raise an exception. It lets you define the kind of error you want to raise.

The SystemExit function is inherited from BaseException. It is designed to avoid getting caught by the code that catches all exceptions.

SystemExit is nothing but an exception. It is raised by some of the exit functions in Python code.

The quit() and sys.exit() functions can raise the SystemExit exception. It will terminate the Python program.

Here is an example of raising the SystemExit function in Python:

import time
try:
    x=0
while 1==1:
    x=x+2
    print(x)
    time.sleep(1)
except KeyboardInterrupt:
    print("Raising SystemExit")
    raise SystemExit

Output:

2
4
6
^C
Raising SystemExit

How to exit a Python script using the os._exit() function

How To Exit A Python Script a person editing a Python script on a laptop. Maybe they are trying to work out how to make the Python script exit?

The os module is a part of Python’s standard utility modules. It provides functions for conveniently interacting with the operating system. It provides a portable way of utilizing operating system-reliant functionality.

You can utilize the os._exit() method to exit the process with the specified status. There is no need to call cleanup handlers or flushing stdio buffers.

You can utilize the os._exit() method after importing the os module in your Python code.

It is generally used in the child process after the os.fork() system call occurs.

Here is an example:

import os
pid = os.fork()
if pid > 0:
    print("nThis is the parent process")
    info = os.waitpid(pid, 0)
    if os.WIFEXITED(info[1]) :
        code = os.WEXITSTATUS(info[1])
        print("Child's exit code:", code)
else:
    print("Now in the child process")
    print("The Process ID is:", os.getpid())
    print("Child is now exiting")
os._exit(os.EX_OK)

Output:

This is the parent process
Now in the child process
The Process ID is: 294
The Child will now exit
Child’s exit code: 0

Conclusion

In this post, you have learned different ways of exiting Python scripts. All of them are very simple. Hence, you can effortlessly implement the methods. Most people prefer to use the sys.exit() function. Because you cannot utilize the exit() and quit() functions in production code. For special use cases, you can use os._exit(). It enables you to immediately exit your Python program.

FAQ

How do you exit a Python script in the terminal?

If you are using Linux and macOS, simply press Ctrl + D. The interpreter will instantly end. Pressing Enter isn’t necessary.

How do I exit Python Main?

You can use sys. exit(). It enables you to exit from the middle of the main function.

How do I exit a Python window?

To terminate an interactive Python session, you need to call the exit() function. Alternatively, you can press Ctrl + Z.

What is the sys module?

The sys module in Python provides various functions and variables. You can utilize them to manipulate different parts of the Python runtime environment. It provides access to the variables and functions that interact strongly with the interpreter. It allows you to operate on the interpreter.

The post How To Exit A Python Script first appeared on Python GUI.

]]>
https://pythongui.org/how-to-exit-a-python-script/feed/ 0 8758
How To Add Python Testing Tools Into Pandas Machine Learning Code https://pythongui.org/how-to-add-python-testing-tools-into-pandas-machine-learning-code/ https://pythongui.org/how-to-add-python-testing-tools-into-pandas-machine-learning-code/#respond Wed, 16 Nov 2022 11:00:00 +0000 https://pythongui.org/?p=8670 Testing your code is critical throughout the software or machine learning system development life cycle. Following this, selecting – and employing the appropriate Python testing tools should be an essential part of writing high-quality machine...

The post How To Add Python Testing Tools Into Pandas Machine Learning Code first appeared on Python GUI.

]]>
Testing your code is critical throughout the software or machine learning system development life cycle. Following this, selecting – and employing the appropriate Python testing tools should be an essential part of writing high-quality machine learning apps.

Unlike other tech stacks, pandas does not have a strong testing culture. The majority of pandas developers never write tests. However, if you want to write production-grade code, this is not the case. Good software engineering practices result in more stable data pipelines.

This post explains how to test pandas code with the built-in test helper methods (pandas.testing) and with the additional tools like beavis and Datatest that give more readable error messages and advanced testing features.

If you are looking for more articles about pandas and how to build a nice GUI for them, read them here:

If you are looking for a way to test numpy, read it here:

For more advanced topics in Python, please read the following articles:

Why is pandas testing important?

pandas testing is important, based on the need to extend TDD’s idea of testing for software correctness with the idea of testing for the meaningfulness of analysis, correctness and validity of input data, & correctness of interpretation (TDDA: Test-driven data analysis) [1].

When you’re ready to start writing production-grade code, you should seriously consider writing tests. Good software engineering practices result in more stable data pipelines [4].

Do pandas have a built-in test helper?

pandas provide us with a built-in test helper, called pandas.testing.

The following are all available functions provided by pandas.testing [2]:

Assertion functions

For example: 

testing.assert_frame_equal(left, right[, ...]),

testing.assert_series_equal(left, right[, ...]),

testing.assert_index_equal(left, right[, ...]), etc.

Exceptions and warnings

For example:

errors.AbstractMethodError(class_instance[, ...]),

errors.AccessorRegistrationWarning,

errors.AttributeConflictWarning, etc.

Bug report function

show_versions([as_json])

Test suite runner

test([extra_args])

What does the built-in pandas.testing do?

Using the built-in pandas.testing functions, we can write faster test cases [3].

Writing tests for end-to-end ML pipelines can be extremely beneficial in situations where [3]:

  • Certain assumptions about the data are made.
  • Certain assumptions are made regarding the outcome of a computation.

Unit testing can be used to ensure that the assumptions being made are still valid and that no side effects (change to the variable, environment, runtime, etc., regardless of whether it was intended or not) are being generated [3].

pandas provides several helpful functions that can make unit testing easier. These can be found in the pandas.testing module.

DataFrame tests 1: Column equality assertions

Let’s write a function that inserts a startswith_s column into a DataFrame and returns True if a string begins with the letter “s“:

import pandas as pd

def startswith_s(df, input_col, output_col):
    df[output_col] = df[input_col].str.startswith("s")

df = pd.DataFrame({"col1": ["sap", "hi"], "col2": [3, 4]})

The created data frame, inside PyScripter IDE:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 1

Let’s write a unit test that runs the startswith_s function and checks that it returns the expected result. We’ll begin with the pd.testing.assert_series_equal method.

In simple terms, if this test is correctly passed, it will assert a new equality column that describes whether the word started with s or not.

startswith_s(df, "col1", "col1_startswith_s")
expected = pd.Series([True, False], name="col1_startswith_s")
pd.testing.assert_series_equal(df["col1_startswith_s"], expected)

Here is the new data frame result, after testing:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 2

DataFrame tests 2: Checking entire DataFrame equality

You may want to compare the equality of two entire DataFrames rather than just individual columns.

Here’s how to use the pandas.testing.assert_frame_equal function to compare DataFrame equality:

import pandas as pd

df1 = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
df2 = pd.DataFrame({'col1': [5, 2], 'col2': [3, 4]})

pd.testing.assert_frame_equal(df1, df2)

The testing output on PyScripter IDE:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 3

How to test pandas with beavis?

We will compare the testing results with pandas.testing vs beavis in this section. 

beavis is testing helper functions for pandas and Dask. The test helpers are inspired by chispa and spark-fast-tests, two popular spark test helper libraries.

Why beavis? Because the beavis error messages are more descriptive compared to the built-in pandas errors.

How to install beavis?

You can get beavis using the pip command to your command prompt:

pip install beavis

pandas.testing vs beavis

pandas.testing error messages

The following is the code example to compare two data frames using pandas.testing:

import pandas as pd

df = pd.DataFrame({"col1": [1041, 1, 8, 5], "col2": [6, 3, 8, 7]})
pd.testing.assert_series_equal(df["col1"], df["col2"])

Here is the built-in pandas.testing error message when comparing series that are not equal.

Spyder output:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 4

PyScripter output:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 5

Because the columns aren’t aligned, it’s difficult to tell which ones are mismatched.

beavis error messages

The following is the code example to compare two data frames using beavis:

import beavis
import pandas as pd

df = pd.DataFrame({"col1": [1041, 3, 8, 5], "col2": [6, 3, 8, 7]})
beavis.assert_pd_column_equality(df, "col1", "col2")

The beavis error message, which aligns rows and highlights mismatches in red, is shown below.

Spyder IDE results:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 6

Output from the PyScripter IDE:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 7

This descriptive error message makes debugging errors and maintaining flow easier. But unfortunately, there might be some bugs on Spyder and PyScripter, so it didn’t show well (on Spyder: The mismatched output on the first row didn’t highlight as red, on PyScripter: All the output-colored red, and the matched outputs on the second and third row are showing strange output).

How to test pandas with datatest?

datatest is a test-driven data-wrangling and data-validation tool. 

datatest also helps to speed up and formalize data-wrangling and data-validation tasks. It was designed to work with badly formatted data by detecting and describing validation failures.

datatest validates pandas objects (DataFrame, Series, and Index) in the same way that it validates built-in types.

This demo uses a DataFrame to load and inspect data from a CSV file (movies.csv). The CSV file uses the following format:

How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 8

How to install datatest?

You can get datatest using the pip command to your command prompt:

pip install datatest

Using datatest with pytest-style tests

The test_movies_df.py script demonstrates pytest-style tests:

import pytest
import pandas as pd
import datatest as dt

@pytest.fixture(scope='module')
@dt.working_directory(__file__)
def df():
    return pd.read_csv('movies.csv')

@pytest.mark.mandatory
def test_columns(df):
    dt.validate(
        df.columns,
        {'title', 'rating', 'year', 'runtime'},
    )

def test_title(df):
    dt.validate.regex(df['title'], r'^[A-Z]')

def test_rating(df):
    dt.validate.superset(
        df['rating'],
        {'G', 'PG', 'PG-13', 'R', 'NC-17', 'Not Rated'},
    )

def test_year(df):
    dt.validate(df['year'], int)

def test_runtime(df):
    dt.validate(df['runtime'], int)

Use the following command to run the tests:

pytest test_movies_df.py
 How To Add Python Testing Tools Into Pandas Machine Learning Code- testing machine learning pandas output 9

Using datatest with unittest-style tests

The test_movies_df_unit.py script demonstrates unittest-style tests:

import pandas as pd
import datatest as dt

def setUpModule():
    global df
    with dt.working_directory(__file__):
        df = pd.read_csv('movies.csv')

class TestMovies(dt.DataTestCase):
    @dt.mandatory
    def test_columns(self):
        self.assertValid(
            df.columns,
            {'title', 'rating', 'year', 'runtime'},
        )

    def test_title(self):
        self.assertValidRegex(df['title'], r'^[A-Z]')

    def test_rating(self):
        self.assertValidSuperset(
            df['rating'],
            {'G', 'PG', 'PG-13', 'R', 'NC-17', 'Not Rated'},
        )

    def test_year(self):
        self.assertValid(df['year'], int)

    def test_runtime(self):
        self.assertValid(df['runtime'], int)

Use the following command to run the tests:

python -m datatest test_movies_df_unit.py
How To Add Python Testing Tools Into Pandas Machine Learning Code - testing machine learning pandas output 10

What the above tests just did?

The code above are done the following test:

1. Define a test fixture

Create a test fixture that reads the CSV file and loads it into a DataFrame.

2. Check column names

Check whether the data includes the expected column names or not.

The set of values in df.columns must match the required set for this validation. datatest treats the df.columns attribute as an Index object, just like any other sequence of values.

This test is designated as mandatory because it is a prerequisite that must be met before any of the other tests can be passed. When a mandatory test fails, the test suite comes to a halt and no further tests are run.

3. Check ‘title’ values

Check if the values in the title column begin with an upper-case letter.

This validation checks that each value in the df['title'] matches the regular expression ^[A-Z].

4. Check ‘rating’ values

Check that the values in the rating column correspond to one of the permitted codes.

This validation ensures that the values in df['rating'] are also present in the specified set.

5. Check ‘year’ and ‘runtime’ types

Check if the values in the year and runtime columns are integers.


Click here to get started with PyScripter, a free, feature-rich, and lightweight Python IDE.

Download RAD Studio to create more powerful Python GUI Windows Apps in 5x less time.

Check out Python4Delphi, which makes it simple to create Python GUIs for Windows using Delphi.

Also, look into DelphiVCL, which makes it simple to create Windows GUIs with Python.


References & further readings

[1] Radcliffe, N. J. (2018).

Introduction to pandas, testing and test-driven data analysis. Europython 2018. Stochastic Solutions Limited & Department of Mathematics, University of Edinburgh. 

[2] pandas Documentation. (2023).

pandas Testing API References. pandas. PyData. NumFOCUS, Inc. pandas.pydata.org/docs/reference/testing.html

[3] Srinivas, R. (2022).

Unit Tests with Pandas in Python. Python in Plain English. python.plainenglish.io/unit-tests-with-pandas-bf4c596baeda

[4] mrpowers. (2021).

Testing Pandas Code. MungingData. mungingdata.com/pandas/unit-testing-pandas

[5] Datatest Documentation. (2014-2021).

Datatest: Test driven data-wrangling and data validation. National Committee for an Effective Congress, et al. datatest.readthedocs.io/en/stable

The post How To Add Python Testing Tools Into Pandas Machine Learning Code first appeared on Python GUI.

]]>
https://pythongui.org/how-to-add-python-testing-tools-into-pandas-machine-learning-code/feed/ 0 8670
Python Profilers: Learn The Basics Of A Profiler For Python https://pythongui.org/python-profilers-learn-the-basics-of-a-profiler-for-python/ https://pythongui.org/python-profilers-learn-the-basics-of-a-profiler-for-python/#respond Mon, 14 Nov 2022 11:00:00 +0000 https://pythongui.org/?p=8717 Python profiling tools enable you to understand how fast your code executes. Also, they help you identify the bottlenecks. They play a major role in optimizing your program. It gives you several advantages. For instance,...

The post Python Profilers: Learn The Basics Of A Profiler For Python first appeared on Python GUI.

]]>
Python profiling tools enable you to understand how fast your code executes. Also, they help you identify the bottlenecks. They play a major role in optimizing your program. It gives you several advantages. For instance, the change in business needs may require you to run code faster. With Python profilers, you can identify the parts of code that are causing sluggish performance. In this article, you will find different ways to profile your Python code. Let’s dive in.

Python Profilers: Learn The Basics Of A Profiler For Python. What are Python profilers?

What are Python profilers?

Python profilers are tools that help you to figure out how the time is spent on the program. It enables you to identify parts that are slowing down the performance. For instance, Application Performance Monitoring (APM) is one of the top profiling tools. You can use it to profile the entire life cycle of transactions for the web application. Hence, you can determine the bottlenecks in your code.

Python Profilers: Learn The Basics Of A Profiler For Python - a close up of a developer with red hair looking at a screenful of code

Python Profilers – How can I profile my Python code?

Python Profilers – Use timeit in Command-Line for Profiling Python Code

Python has a module, called timeit. It enables you to time small code snippets. It utilizes platform-specific time functions. As a result, you will get the most accurate timings.

Let’s take a look at an example. Start the terminal on your PC. Then run the following commands:

python -m timeit -s "[ord(x) for x in 'abcdfghi']"
100000000 loops, best of 3: 0.0115 usec per loop
python -m timeit -s "[chr(int(x)) for x in '123456789']"
100000000 loops, best of 3: 0.0119 usec per loop

Here, you are calling Python on the command line. Then you are passing the “-m” option to look up and use the timeit module as the main program. Next, you pass the “-s” option to tell the module to run the setup once. The command runs the code s 3 times. It returns the best average of the runs.

The -s option is usually used to import the libraries. For instance, you can utilize it to compare the square root function from Python’s math module from NumPy. Here is the code:

python -m timeit '[x**0.5 for x in range(1000)]'
python -m timeit -s 'from math import sqrt' '[sqrt(x) for x in range(1000)]'
python -m timeit -s 'from numpy import sqrt' '[sqrt(x) for x in range(1000)]'

Now, let’s write a silly function. You can time it from the command line.

# simple_func.py
def my_function():
    try:
        1 / 0
    except ZeroDivisionError:
        pass

The function will cause an error. However, it is promptly ignored.

Now, you have to run this command:

python -m timeit "import simple_func; simple_func.my_function()"
1000000 loops, best of 3: 1.77 usec per loop

Here, you are importing and calling the function. Next, you will learn to use timeit inside an actual Python script.

Read: 5 Real-Life Lessons About The Best IDE for Python

Python Profilers – Import timeit for Testing

You can easily use the timeit module inside your code. Here is an example:

# simple_func2.py
def my_function():
    try:
        1 / 0
    except ZeroDivisionError:
        pass
 
if __name__ == "__main__":
    import timeit
    setup = "from __main__ import my_function"
    print(timeit.timeit("my_function()", setup=setup))

Python Profilers – Use a Decorator

You can consider writing your own timer. However, it may not be as accurate as using timeit.

Let’s write the custom decorator:

import random
import time

def timerfunc(func):
    """
    A timer decorator
    """
    def function_timer(*args, **kwargs):
        """
        A nested function for timing other functions
        """
        start = time.time()
        value = func(*args, **kwargs)
        end = time.time()
        runtime = end - start
        msg = "The runtime for {func} took {time} seconds to complete"
        print(msg.format(func=func.__name__,
                         time=runtime))
        return value
    return function_timer


@timerfunc
def long_runner():
    for x in range(5):
        sleep_time = random.choice(range(1,5))
        time.sleep(sleep_time)

if __name__ == '__main__':
    long_runner()

Here, you are importing the random and time modules from Python’s standard library. Then you are creating your decorator function. It accepts a function. Also, it has another function inside. Before calling the passed-in function, the nested function will grab the time. Next, it waits for the function to return and grabs the end time. Then you will know the time the function took to run. You can print it out. The last two statements return the result of the function call and the function itself.

Python Profilers – Create a Timing Context Manager

You can consider using context managers. It will enable you to time small pieces of code. Let’s create the timer context manager class. Here is the code:

import random
import time

class MyTimer():

    def __init__(self):
        self.start = time.time()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        end = time.time()
        runtime = end - self.start
        msg = 'The function took {time} seconds to complete'
        print(msg.format(time=runtime))


def long_runner():
    for x in range(5):
        sleep_time = random.choice(range(1,5))
        time.sleep(sleep_time)


if __name__ == '__main__':
    with MyTimer():
        long_runner()

Python Profilers – Using cProfile

Python features built-in code profilers. They are known as the profile module and the cProfile module. The first one is pure Python. It will add a lot of overhead to anything you profile. That’s why you should go with cProfile. It has a similar interface. However, it is significantly faster.

Read: What is the best Python editor?

Let’s look at an example:

>>> import cProfile
>>> cProfile.run("[x for x in range(1500)]")
         4 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<listcomp>)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.001    0.001    0.001    0.001 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

What do these columns mean? Let’s find it out.

  • ncalls – It’s the number of calls made.
  • tottime – It refers to the total time spent in the given function.
  • percall – It refers to the quotient of tottime divided by ncalls
  • cumtime – It is the cumulative time spent in this function, along with all subfunctions. For recursive functions, you will find it to be very accurate
  • The second percall column – It refers to the quotient of cumtime divided by primitive calls
  • filename:lineno(function) – It provides the respective data of each function

You can call cProfile on the command line in almost the same way as the timeit module. However, there is a difference. You have to pass a Python script, rather than a snippet. Here’s an example call:

python -m cProfile test.py

Python Profilers – Use line_profiler

You can use a 3rd party project, called line_profiler. It enables you to profile the time each line takes to execute. The installation process is very simple. You just need to use pip. Here is the command that you need to utilize:

pip install line_profiler

To use line_profiler, you will need some code to profile. You just need to utilize this command:

kernprof -l silly_functions.py

You will see this output

Wrote profile results to silly_functions.py.lprof

Now, let’s write the script:

# silly_functions.py
import time

@profile
def fast_function():
    print("I'm a fast function!")

@profile
def slow_function():
    time.sleep(2)
    print("I'm a slow function")

if __name__ == '__main__':
    fast_function()
    slow_function()

Now, you have to run this command:

python -m line_profiler silly_functions.py.lprof

You will see this output:

I'm a fast function!
I'm a slow function
Wrote profile results to silly_functions.py.lprof
Timer unit: 1e-06 s

Total time: 3.4e-05 s
File: silly_functions.py
Function: fast_function at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def fast_function():
     5         1           34     34.0    100.0      print("I'm a fast function!")

Total time: 2.001 s
File: silly_functions.py
Function: slow_function at line 7

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     7                                           @profile
     8                                           def slow_function():
     9         1      2000942 2000942.0    100.0      time.sleep(2)
    10         1           59     59.0      0.0      print("I'm a slow function")

Python Profilers – Use memory_profiler

memory_profiler is an amazing 3rd party profiling package. You can use it to monitor memory consumption in a process. Also, you can use it for the line-by-line analysis of your code.

Read: 6 Best GUI in Python Frameworks

To install memory_profiler, you need to use pip:

pip install memory_profiler

Once the installation is done, you have to run a few lines of code against it. Here’s a simple example:

# memo_prof.py 
@profile
def mem_func():
    lots_of_numbers = list(range(1500))
    x = ['letters'] * (5 ** 10)
    del lots_of_numbers
    return None

if __name__ == '__main__':
    mem_func()

Now, you can run the code by using this command:

python -m memory_profiler memo_prof.py 
Filename: memo_prof.py

Line #    Mem usage    Increment   Line Contents
================================================
     1   16.672 MiB    0.000 MiB   @profile
     2                             def mem_func():
     3   16.707 MiB    0.035 MiB       lots_of_numbers = list(range(1500))
     4   91.215 MiB   74.508 MiB       x = ['letters'] * (5 ** 10)
     5   91.215 MiB    0.000 MiB       del lots_of_numbers
     6   91.215 MiB    0.000 MiB       return None

Python Profilers – Use profilehooks

Profilehooks is a collection of decorators. It is designed for profiling functions. To install profilehooks, you have to run this command:

pip install profilehooks

Next, you have to write the script:

# memo_prof.py 
@profile
def mem_func():
    lots_of_numbers = list(range(1500))
    x = ['letters'] * (5 ** 10)
    del lots_of_numbers
    return None

if __name__ == '__main__':
    mem_func()

Now, let’s run the code. You will see this output:

*** PROFILER RESULTS ***
mem_func (profhooks.py:5)
function called 1 times
	2 function calls in 0.045 seconds

   Ordered by: cumulative time, internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.045    0.045    0.000    0.045 prohooks.py:5(mem_func)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        0    0.000             0.000          profile:0(profiler)
Python Profilers: Learn The Basics Of A Profiler For Python - an overhead view of a laptop with a Python book next to it

Python Profilers – Additional Resources

The profiler of Python’s standard library is very powerful. However, there are plenty of other options to choose from. For example, you can consider using the Python Call Graph module. It visualizes how functions call each other using the GraphViz tool.

Also, you can dig into the compiled code by using Valgrind.

However, you may have to recompile the Python interpreter to enable debugging support.

Conclusion

In this article, you have learned to use timeit and cProfile modules to time and profile your code. Also, you have learned about using the decorator and the context manager. Finally, you explore different 3rd party packages, including line_profiler, memory_profilerand profilehooks. Now, you are ready to use Python profilers. Therefore, you can easily find the bottlenecks in your code.

PyScripter is a powerful Python IDE built on Delphi. It offers several amazing features, including the remote engine, remote debugger, and integrated unit testing. Try it now for free. 

FAQ

What is the Python standard library?

The Python Standard Library is a collection of script modules accessible to a Python program. It enables you to simplify the programming process. Also, it eliminates the need to rewrite commonly used commands.

How can I optimize the memory usage in my Python program?

You can optimize memory usage using profilers. It enables you to find memory leaks. Hence, you can efficiently optimize your Python programs.

What are function calls?

Function calls are expressions that pass control and arguments to a function.

What is a profiler in programming?

A profiler is a performance analysis tool. It measures the frequency and duration of function calls.

What is debugging in Python?

Debugging is the process of detecting and removing existing and potential errors. It enables you to flawlessly run your Python program.

The post Python Profilers: Learn The Basics Of A Profiler For Python first appeared on Python GUI.

]]>
https://pythongui.org/python-profilers-learn-the-basics-of-a-profiler-for-python/feed/ 0 8717
How To Build A TODO TUI Application With Textual https://pythongui.org/how-to-build-a-todo-tui-application-with-textual/ https://pythongui.org/how-to-build-a-todo-tui-application-with-textual/#respond Mon, 07 Nov 2022 11:00:00 +0000 https://pythongui.org/?p=8558 Did you know it’s possible to build a rich UI that runs completely in the terminal? Even some experienced Python developers avoid using the terminal in favor of Graphical User Interfaces (GUIs). But, today, many...

The post How To Build A TODO TUI Application With Textual first appeared on Python GUI.

]]>
Did you know it’s possible to build a rich UI that runs completely in the terminal? Even some experienced Python developers avoid using the terminal in favor of Graphical User Interfaces (GUIs). But, today, many developer tools use a Terminal User Interface (TUI) since they often spend a lot of time working in the terminal. Not only are there programs and tools, but there are also several games that run entirely in the terminal.

So, in this article, we will first develop a good understanding of TUIs and then move on to creating an interesting TUI using PyScripter to manage to-do lists.

What is a TUI?

How To Build A TODO TUI Application With Textual - an image of a laptop showing some Python code

A TUI, short for Text User Interface or Terminal User Interface, uses the terminal’s advanced features as the basis for a kind of GUI, generally occupying the full area of the terminal. It uses escape codes or proprietary console commands (the latter on Windows, the former on most other things) to take control of the entire console window and display a user interface. TUIs Usually handle input via the keyboard, but some modern systems also use mouse input.

Thus, a TUI allows users to interact with a program via the terminal. The terminal does not interact via commands, although many TUI programs also accept commands.

Why is Textual Popular For Making TUIs?

Textual is a Python framework for creating interactive applications that run in your terminal. It mainly adds interactivity to Rich with a Python API inspired by modern web development.

On modern terminal software, Textual apps offer more than 16 million colors, mouse support, and smooth, flicker-free animation. Furthermore, a powerful layout engine and reusable components make it possible to build apps that rival the desktop and web experience.

Currently, Textual runs on Linux, macOS, and Windows. This framework requires Python 3.7 or above.

How to Build a ToDo List TUI in Python?

How To Build A TODO TUI Application With Textual- an image of a laptop on someone's knee with a code editor open on the screen

Let us now move to the main part of this tutorial and start building a to-do list in Python. But first there are some requirements that you need to install.

What Are the Requirements For This TUI Tutorial?

For this tutorial you will need Python 3.9+ installed on your computer. You will also need to install an IDE a feature-packed IDE like PyScripter.

Then, you can install Textual via PyPI.

If you intend to simply run Textual apps, then install textual and textual_inputs using the following command:

pip install textual, textual_inputs

However, if you plan to develop Textual apps, you should install textual[dev]. This is because the [dev] part installs a few extra dependencies for development.

pip install "textual[dev]"

Moreover, to make our to-do list more appealing will be using Rich. The Rich API will help us add color and style to our terminal output. In addition, Rich can also render attractive tables, progress bars, markdown, syntax highlighted source code, tracebacks, and other features right out of the box.

After installing Textual, you can install Rich using the following PyPI command:

pip install rich

How to Create a Basic TUI in Textual?

Let’s start this tutorial by creating a simple TUI in Textual, and then we will build upon this to create a TUI that serves our purpose.

How To Build A TODO TUI Application With Textual - example screenshot of TUI use

The following code builds a TUI with a text box Text that takes in some text from the user and displays it in the Output panel when the enter key is pressed. It has a simple Header and Footer where the Footer has a button q that can be clicked using the mouse to exit the program.

import rich.box
from rich.panel import Panel
from textual.app import App
from textual.widgets import Footer, Header, Static
from textual_inputs import TextInput

class SimpleForm(App):
    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)

    async def on_load(self) -> None:
        # Bind the q button to quit.
        await self.bind("q", "quit", "Quit")

        # Bind the enter key to the action_submit function.
        await self.bind("enter", "submit", "Submit")

    async def on_mount(self) -> None:
        # Placing Header and Footer at the top and bottom
        await self.view.dock(Header(), edge="top")
        await self.view.dock(Footer(), edge="bottom")

        # Creates a Text Input that allows you to type text
        self.text = TextInput(
            name="Text",
            placeholder="enter your Text...",
            title="Text",
        )

        # Creates a Panel that displays your text.
        self.output = Static(
            renderable=Panel(
                "", title="Output", border_style="blue", box=rich.box.SQUARE
            )
        )

        # Defining the Placement for the output panel and text.
        await self.view.dock(self.output, edge="left", size=40)
        await self.view.dock(self.text, edge="top")

    async def action_submit(self) -> None:
        # Retrieve the value from the Input text box.
        val = self.text.value

        # Format and update the value in the output panel
        await self.output.update(
            Panel(val, title="Output", border_style="blue", box=rich.box.SQUARE)
        )

        # Empty the text box for the next input.
        self.text.value = ""

# Running our form here...
if __name__ == "__main__":
    SimpleForm.run(title="Simple TUI", log="textual.log")

Running this code will give you the following output in the terminal:

How To Build A TODO TUI Application With Textual - screen 1

If we press enter, our text will appear on the output panel:

How To Build A TODO TUI Application With Textual- screen 2

If you cannot follow the program above, do not fear as we walk you through it step by step as we build a more complex To-do list over this code.

How To Create An Instance of Our to-do List?

We will start by importing several libraries and functions to create our TUI:

import rich.box
from rich.panel import Panel
from textual.app import App
from textual.reactive import Reactive
from textual.widgets import Footer, Header, Static
from textual_inputs import TextInput

formatted = ""

Above, we created a global variable formatted that helps us keep track of tasks in our to-do list by storing all our tasks in a string format.

Next, we define a class named ToDoForm that inherits from App imported from the textual.app. This will serve as the primary class to help us run our TUI to-do list. We also define a constructor that calls the parent class’s constructor, which will help us instantiate our TUI to-do list.

class ToDoForm(App):
    def __init__(self, **kwargs) -> None:
        """
        Constructor helps initialize the main ToDo list.
        """
        super().__init__(**kwargs)
How To Build A TODO TUI Application With Textual - example code of rich.box

We can now move on and start creating the user interface for our TUI.

How Do We Create a User Interface For Our TUI?

To create a user interface, we define an async function on_mount() that will format our TUI user interface. We define the function as a class method called when we instantiate our ToDoForm object.

async def on_mount(self) -> None:
        # Placing Header and Footer at the top and bottom
        await self.view.dock(Header(), edge="top")
        await self.view.dock(Footer(), edge="bottom")

        # Creates a Text Input that allows you to type text
        self.todo = TextInput(
            name="Text",
            placeholder="enter your Text...",
            title="Text",
        )

        self.file = TextInput(
            name="File Import",
            placeholder="enter your ToDo File Name...",
            title="File Import",
        )

        # Creates a Panel that displays your text.
        self.output = Static(
            renderable=Panel(
                "", title="Output", border_style="blue", box=rich.box.SQUARE
            )
        )

        # Defining the Placement for the output panel and text.
        await self.view.dock(self.output, edge="left", size=40)
        await self.view.dock(self.text, edge="top")

We start by first placing a Header and Footer on our TUI. This is done by using self.view.dock(), adding an instance of either a Header or Footer as a parameter and specifying its placement in the optional edge argument. Here we define the Header to be at the top and the Footer to be at the bottom.

Next, we define a text input that will help us append tasks to our TUI to-do list. We do this by creating an instance of the TextInput object and assigning it to a variable self.todo. We then specify its title, name, and placeholder.

Note: The title is what will be displayed on top of the TextInput text box.

The self.todo will receive inputs from the user, which we will later use to add items to our tasks in formatted.

Similarly, we create another TextInput instance named self.file that we will use to take file names as input and add their contents to our to-do list.

Finally, to output our to-do list, we instantiate a Static object, and within it, a Panel. We then assign it to a variable named self.output. This will serve as the output of our TUI. We then define the placement of our text input and output panel by using the self.view.dock() and specify its placement using edge. For our output panel, we also use another size argument that helps us define a custom size for our panel.

How To Build A TODO TUI Application With Textual - code example 4

But the question arises, how can we use these variables to add values to our to-do list?

How To Create Functions to Add Entries to Our to-do list?

To add entries to our to-do list, we create async functions that will use the inputs provided in the self.todo and self.file objects, and then add them to our to-do list.

First, we define an async function action_submit() that will use the self.todo text box.

async def action_submit(self) -> None:
        """
        Adds the Todo entries to the Panel when an enter is pressed.
        This function also saves the ToDo entries into a ToDos.txt file, 
        whenever it is called.
        """
        global formatted

        # Retrieve the value from the Input text box.
        do = self.todo.value

        # Format and update the value in the ToDo panel
        formatted += "-" + do + "n"
        await self.output.update(
            Panel(formatted, title="ToDo List", border_style="blue", box=rich.box.SQUARE)
        )

        # Empty the text box for the next ToDo.
        self.todo.value = ""

        # Write the ToDo into a ToDo.txt file.
        with open("ToDos.txt", "w") as f:
            f.write(formatted)

The function simply uses the .value attribute of the TextInput object to retrieve the value in the self.todo text box. It then formats the input by removing a hyphen and then adds it to self.output list using the .update() method.

Finally, the function empties the text box by setting the value of self.todo.value to an empty string before writing the contents of the to-do list into a file named “ToDo.txt.

Next, we define a function action_read() that reads the file provided in the text box of self.file, and writes its contents into our to-do list.

async def action_read(self) -> None:
        """
        Reads the file that you have provided in your "File Import" textbox.
        This function then diplays all your ToDos defined in your file on
        the Todo Panel.
        """
        global formatted

        # Read the file with n separated inputs.
        try:
            with open(self.file.value, "r") as f:
                formatted = f.read() + "n"
            
            # Display the contents of the File in the ToDo Panel.
            await self.output.update(
                Panel(formatted, title="ToDo List", border_style="blue", box=rich.box.SQUARE)
            )
        except:
            # If no File found Print Error.
            print("Invalid or no filename given!")

Like the action_submit() function, we first read the contents provided in the self.file text box using the .value attribute. If a file has been provided, the function reads the file’s contents, parses and formats it, then appends the items in the file to our to-do list. If no file has been provided, the function simply prints an error.

How To Build A TODO TUI Application With Textual - another code example

How Can We Add Bindings to Our TUI?

Now that we’ve defined our functions, we can call them by pressing some keys on our keyboard. This is done through key bindings.

Textual allows us to create key bindings for our TUI easily. This can be done using the .bind() method, which takes three arguments. The first argument specifies the key that we will bind, the second argument specifies the action to bind to, and the final argument is optional and provides a short description of the action.

For our application, we will bind three keys:

  1. The “q” key binding will help us quit our TUI.
  2. The “enter” key binding will help us submit entires to our to-do list.
  3. Finally, pressing the “ctrl+r” key binding will allow us to read specific files that we specify in the self.file text box.

To create our key bindings, we create an async function on_load() that runs when we create an instance of our TUI:

async def on_load(self) -> None:

        # Bind the q button to quit.
        await self.bind("q", "quit", "Quit")

        # Bind the enter key to the action_submit function.
        await self.bind("enter", "submit", "Submit")

        # Bind the r key to the action_read function.
        await self.bind("r", "read", "Read")

How Do We Run The Code We Have Created?

Now all that’s left is to create an instance of our ToDoForm and run it. Here is what our final code looks like:

import rich.box
from rich.panel import Panel
from textual.app import App
from textual.widgets import Footer, Header, Static
from textual_inputs import TextInput

formatted = ""

class ToDoForm(App):
    def __init__(self, **kwargs) -> None:
        """
        Constructor helps initialize the main ToDo list.
        """
        super().__init__(**kwargs)

    async def on_load(self) -> None:
        """
        On loading of our ToDo, we bind some keyboard keys to
        certain actions.
        """
        # Bind the q button to quit.
        await self.bind("q", "quit", "Quit")

        # Bind the enter key to the action_submit function.
        await self.bind("enter", "submit", "Submit")

        # Bind the (control + r) key to the action_read function.
        await self.bind("ctrl+r", "read", "Read")

    async def on_mount(self) -> None:
        """
        Initialization function that helps create the main Todo list.
        """
        # Placing a Normal Header and Footer at the top and bottom
        # of the Todo form.
        await self.view.dock(Header(), edge="top")
        await self.view.dock(Footer(), edge="bottom")

        # Creates a Text Input that allows you to add your next Todo.
        self.todo = TextInput(
            name="ToDo",
            placeholder="enter your next ToDo...",
            title="ToDo",
        )

        # Creates a TextInput that allows you to import a file.
        self.file = TextInput(
            name="File Import",
            placeholder="enter your ToDo File Name...",
            title="File Import",
        )

        # Creates a Panel that displays all your Todos.
        self.output = Static(
            renderable=Panel(
                "", title="ToDo List", border_style="blue", box=rich.box.SQUARE
            )
        )

        # Defining the Placement for the output and two textboxes.
        await self.view.dock(self.output, edge="left", size=40)
        await self.view.dock(self.todo, self.file, edge="top")

    async def action_read(self) -> None:
        """
        Reads the file that you have provided in your "File Import" textbox.
        This function then diplays all your ToDos defined in your file on
        the Todo Panel.
        """
        global formatted

        # Read the file with n separated inputs.
        try:
            with open(self.file.value, "r") as f:
                formatted = f.read() + "n"

            # Display the contents of the File in the ToDo Panel.
            await self.output.update(
                Panel(
                    formatted, title="ToDo List", border_style="blue",
                    box=rich.box.SQUARE
                )
            )
        except:
            # If no File found Print Error.
            print("Invalid or no filename given!")

    async def action_submit(self) -> None:
        """
        Adds the Todo entries to the Panel when an enter is pressed.
        This function also saves the ToDo entries into a ToDos.txt file, 
        whenever it is called.
        """
        global formatted

        # Retrieve the value from the Input text box.
        do = self.todo.value

        # Format and update the value in the ToDo panel
        formatted += "-" + do + "n"
        await self.output.update(
            Panel(formatted, title="ToDo List", border_style="blue", box=rich.box.SQUARE)
        )

        # Empty the text box for the next ToDo.
        self.todo.value = ""

        # Write the ToDo into a ToDo.txt file.
        with open("ToDos.txt", "w") as f:
            f.write(formatted)

# Running our ToDo form here...
if __name__ == "__main__":
    ToDoForm.run(title="ToDo List Creator", log="textual.log")
How To Build A TODO TUI Application With Textual- a screenshot of the todo list generator TUI

Let’s say you wanted to add some tasks to your to-do list. You can write it down in the ToDo text box:

How To Build A TODO TUI Application With Textual - a screenshot of the todo list generator TUI - 2

If you press enter, it will be added to your to-do list.

How To Build A TODO TUI Application With Textual - a screenshot of the todo list generator TUI - 3

This creates a file, “ToDo.txt” in the same directory.

Let us now create a text file named “tasks.txt” inside the application directory and define some tasks inside it. First, we will add three tasks to the file, with each task beginning with a hyphen:

How To Build A TODO TUI Application With Textual - example UI

With the code running, add the file’s name to the TUI, then press “ctrl+r” together. This adds the tasks to your to-do list:

How To Build A TODO TUI Application With Textual- screenshot of adding tasks

Let’s add more tasks to your to-do list:

How To Build A TODO TUI Application With Textual - adding the tasks

All this content has been appended to the text file, “ToDo.txt“:

How To Build A TODO TUI Application With Textual - GUI 5

Congratulations on reaching the end of this tutorial. You may have noticed that we have been using PyScripter throughout this project. This is because PyScripter is one of the best tools that you can have to organize your code and understand it better. So, if you are starting with Python, PyScripter should be part of your starter kit.

Why Should You Use PyScripter to Create TUIs?

How To Build A TODO TUI Application With Textual- the Embarcadero Python tools download page

Embarcadero sponsors PyScripter, a popular, free, and open-source Python IDE. This IDE has all the features you’d expect from a modern Python IDE while remaining lightweight and fast. PyScripter is natively compiled for Windows, allowing it to use as little memory as possible while providing maximum performance. It also has full Python debugging capabilities, both locally and remotely. Another noteworthy feature of this IDE is its integration with Python tools like PyLint, TabNanny, Profile, etc. It can also run or debug files directly from memory.

PyScripter includes all the features you’d expect from a professional IDE, such as brace highlighting, code folding, code completion, and syntax checking as you type. It also has features you’d expect to find in a legitimate native app, such as the ability to drag and drop files into the PyScripter IDE. These features work in tandem to save time and make the development process simple and enjoyable.

PyScripter includes a Python interpreter with call indications and code completion. This program lets you run scripts without saving them and keeps a record of your command history. This IDE also includes a remote Python debugger for debugging Python code. As a result, variables, the watch window, and the call stack are visible. Additional debugging tools built into PyScripter include conditional breakpoints and thread debugging. Furthermore, PyScripter has debugger indications to help you debug your files without saving them, as well as the ability to destroy them.

Thus, PyScripter is a fantastic IDE seeking to create a Python IDE that can compete with other languages’ traditional Windows-based IDEs. It is lightweight, versatile, and extendable with a lot of features.

Furthermore, since it was built from the ground up for Windows, it is substantially faster and more responsive than cumbersome text editors, making it perfect for making TUIs.

Are You Ready to Build Your Own TUI?

How To Build A TODO TUI Application With Textual- an image of a person about to download the free PyScripter tool

In this tutorial, you have learned several useful things about Python!

Textual is a TUI framework for Python inspired by modern web development. It has a very active repository on GitHub. This awesome framework is built on Rich and is currently a work in progress, but usable by programmers who don’t mind some API instability between updates.

You can conveniently build complex and simple TUIs with Textual in PyScripter. This IDE will make the entire process very seamless and enjoyable for you.

Now that you know PyScripter’s countless features and how Textual works, go ahead and create your own TUIs in everyone’s favorite IDE!

What Are the FAQs On This Topic?

How To Build A TODO TUI Application With Textual- another person on the PyScripter download page

What are some use cases of TUIs?

TUIs can be used to make programs like stopwatches, calculators, code and other file viewers, basic games, and to-do lists (as shown in this article).

There are several other possibilities. The only limit is your imagination!

Which other TUI libraries are available in Python?

Pytermgui, picotui, and pyTermTk are other frameworks and libraries that can be used to create interactive and attractive TUIs in Python.

What is the difference between CLI, GUI, and TUI?

GUI means Graphical User interface. You must have heard this word most commonly. It is the GUI that has enabled the common user to use computers. A GUI application is an application that can be run with a mouse, touchpad, or touchscreen.

The CLI is a command line program that accepts text input to perform a certain task. Any application you can use via commands in the terminal falls into this category.

TUI, i.e., Terminal User Interface, falls between GUI and CLI. It can also be called a kind of text-based GUI. Before the arrival of the GUI, everything used to run on the command line; then, the terminal user interface provided a kind of GUI on the command line. TUI programs can be run via a mouse or keyboard.

What is Python4Delphi?

In short, P4D offers a selection of real-world apps that can be modified to your individual needs and used in Python GUI.

Consider integrating Delphi’s GUI and desktop app development power with Python in your applications to give world-class solutions to your clients’ needs. Python4Delphi is the answer to your problems.

Python for Delphi (P4D) is a free Delphi and Lazarus component library that wraps the Python DLL. They make it simple to run Python scripts while allowing for new Python modules and types. The best feature of P4D is that it simplifies the use of Python as a scripting language. It also includes numerous customizable demos and tutorials that are ready to use in the development of real-world apps.

The post How To Build A TODO TUI Application With Textual first appeared on Python GUI.

]]>
https://pythongui.org/how-to-build-a-todo-tui-application-with-textual/feed/ 0 8558
Recommended Read: Mixing Python and Delphi Made Easy https://pythongui.org/recommended-read-mixing-python-and-delphi-made-easy/ https://pythongui.org/recommended-read-mixing-python-and-delphi-made-easy/#respond Sun, 06 Nov 2022 14:04:18 +0000 https://pythongui.org/?p=8666 “Mixing Python and Delphi Made Easy” is a highly recommended read from developer Simon Booth. Here’s the introduction: A Marriage of Convenience The recent release of a suite of Delphi components allows you to Embed...

The post Recommended Read: Mixing Python and Delphi Made Easy first appeared on Python GUI.

]]>
“Mixing Python and Delphi Made Easy” is a highly recommended read from developer Simon Booth. Here’s the introduction:

A Marriage of Convenience

The recent release of a suite of Delphi components allows you to Embed a full Python Environment in a Delphi Application. It may not be obvious why you’d want to do this in the first place. To Delphi developers, the mere mention of Python will most likely immediately make them want to come up with a way to re-write the Python bit in Delphi. To Python developers, the idea of any other language may seem pointless. There is, however, something tangible to be gained for developers of either preference.

For Delphi developers, the ability to add AI facilities to their projects is the most obvious benefit. As most Machine Learning libraries are written in C/C++ and then exposed for use via Python wrappers the ability to ‘talk Python’ from Delphi instantly opens up a huge range of highly advanced libraries to which you have zero native access. While the Python layer is involved its perceived lack of speed is irrelevant as Python is merely allowing access to a fast C/C++ library so the overhead is minimal.

For Python developers, the main interface to your code is usually command-line in nature unless you use Tkinter, PyQT, or some other GUI library. However you decide to control your Python application if you plan on distributing your project for the use of others then the end user will, by necessity, need to install Python and a load of PIP/Conda packages just to get it working (there are exe compilers of course). With Delphi and the P4D components, you can add a pretty interface (it can even just issue command lines to your Python if you want) that is provided as one file. An embedded Python system is then built and populated with any packages you need the first time the application runs.

Read the Complete Article Here

The post Recommended Read: Mixing Python and Delphi Made Easy first appeared on Python GUI.

]]>
https://pythongui.org/recommended-read-mixing-python-and-delphi-made-easy/feed/ 0 8666
7 Easy Steps To Learning Python Scripting https://pythongui.org/7-easy-steps-to-learning-python-scripting/ https://pythongui.org/7-easy-steps-to-learning-python-scripting/#respond Fri, 04 Nov 2022 10:00:00 +0000 https://pythongui.org/?p=8531 Python is one of the most popular programming languages. Knowing how to create software that can be employed in everyday tasks was previously not a necessity. Python is an excellent tool that helps you get...

The post 7 Easy Steps To Learning Python Scripting first appeared on Python GUI.

]]>
Python is one of the most popular programming languages. Knowing how to create software that can be employed in everyday tasks was previously not a necessity. Python is an excellent tool that helps you get a good job and improves the skills necessary for a successful career. Writing programs has become much easier since Python became a popular programming language. But despite the many benefits, learning Python presents many challenges. Here is the easiest way to gain Python scripting knowledge and kickstart your journey.

What Is Scripting?

Scripting is tightly related to programming. In fact, there is little difference other than the language used and the purpose of the code. Scripting, more specifically, refers to code which makes it easier and more efficient to perform advanced tasks at an operating-system level. This can be, for example, batch-processing a large set of files, automating tasks, or using a tool to monitor the status of computer hardware.

Introduction To Scripting In Python

Python was originally meant to be a scripting language, i.e., to extend the capabilities of bash, sed, awk, perl and more. A common trait shared between scripting languages is that they have a simplified syntax and they are executed interactively, meaning that the code does not need to be compiled, but commands are given sequentially.

The python interpreter processes the code entered by the user one line at a time. It can do some sanity checks and supports exception handling when there is a programming error. Python has evolved significantly since the days when it was created back in the early 90s. Nowadays, it is the go-to language used in scientific computing.

How To Start With Python Scripting?

While taking a Python course is a good idea, it does not need to be the time and place to write your first Python script. In fact, there are countless tutorials and free resources online, from creating your first “Hello world” program to advanced topics such as data science and machine learning.

One of the simplest examples of a program is to print the string “Hello world”. This only takes one line of Python code:

print("Hello world!")

There is no need to specify string formatting, or import any packages or define variables. You can copy the line above and paste it in a text file. Then you can open the command line on Unix systems, the command prompt on Windows or an IDE where you can execute your Python script.

On a Linux or a Mac terminal, you need to call the Python interpreter and provide the file name so that it can be executed. Alternatively, you can add

#!/bin/env python

to be the first line of your script. If you make this file executable, you can start it without calling the interpreter explicitly. In the screenshot below, I first show the content of the script, then I make it executable using the chmod command, and then I execute it. The alternative way is to call the Python interpreter and give the name and path to the script to it. The output is identical.

7 Easy Steps To Learning Python Scripting - a screenshot of a simple command line interaction

The same is done in PyScripter, a Python-specific IDE offering all features that a Python programmer needs.

7 Easy Steps To Learning Python Scripting - a hello world program in PyScripter

How To Run A Python Script?

Python scripts can either be run from the command line or inside an integrated development environment (IDE). There are many options for an IDE, but some of the reliable code editors include Visual studio code and PyScripter. While any text editor would do as a starting point, we highly recommend that you start using professional tools from the very beginning.

Click here to start your scripting journey using PyScripter

What Are The 7 Easy Steps To Learning Python Scripting?

1. Decide Why You Want to Learn Python Programming

One possible reason is that it’s cool! And it truly is fun to learn how programming works and how to write code. You may also have much bigger dreams and goals such as Python scripting for web development or even your very own data science project.

Python comes with many built-in functions and packages. There are various modules to save you time – there is no need to reinvent the wheel. Python is more versatile than other languages, and knowing how to code is a huge benefit when looking for a better job.

2. Learn Basic Python Syntax

As I mentioned, you can start off by looking up some online tutorials on Python scripting for absolute beginners. We have written plenty of blog articles about it, so make sure you check them out.

If you want to go one step further, you can build a GUI Python currency converter.

The opportunities are endless once you grasp the basic concepts. Python syntax is intuitive and logical. This allows you to obtain results and proceed with your project much faster than if you were to study a more complicated programming language.

The sys module is a particularly interesting one since it allows your script to interact with the operating system. Also, it can process command-line arguments, which gives more flexibility when executing Python code for repetitive tasks.

3. Create Simple Programs Using Data Types and Control Structures

Data types and control structures are the first programming concepts that you need to learn if you have no prior experience with other programming languages. Basically, you need to open a code editor and start typing your script. The Python language has two major versions, of which the older version 2 is now deprecated. You should definitely start with Python version 3. Plan your code structure, be clear about what kind of input you are going to give to the script and what is the desired output.

4. Run Incremental Checks on Your Code

As a newbie, you will inevitably make lots of programming mistakes, but that is normal, and it should not discourage you. You learn best by trying. One useful tip is that you should start by writing short pieces of code and running them until you are sure that each component works. If you write a huge script, it becomes much harder to pinpoint the errors.

5. Learn How to Troubleshoot Your Code

The Python programming language comes with error handling, however, there are debugging tools to handle less obvious programming mistakes. In PyScripter, you can go to Run -> Debug, and you will be able to trace the execution of your code. You can make a step-by-step analysis of each operation and find out easily what is the problematic part of your code.

Sometimes, there are logical errors in the code structure. The code syntax is correct, and the debugger does not show any hints of errors. In these cases, it is useful to print out intermediate steps that will act as sanity checks. For example, I intended to calculate the sum of u1 and v2, but instead, I typed u1 and u2. The code is technically correct, but the output is incorrect.

6. Make a schedule for learning Python and follow it through

Like with anything, learning Python scripting takes time and effort. You need to be consistent and bravely spend time on it before you can repeat the rewards. Add sloths in your timetable that you will dedicate to Python. And why not create a Python program that will remind you when you need to start practising? You just need to write the basic script file and schedule the py file either via the Windows Scheduled Tasks or as a cron job on Unix systems.

7. Step Out of Your Comfort Zone

Be brave and try a big project even if you know nothing about the field. How about learning how artificial intelligence works? Maybe you have only heard the term, but why not become an AI expert? Try out something new.

7 Easy Steps To Learning Python Scripting - a person in ripped jeans with their arms outstretched sitting cross legged on the floor with a laptop on their lap

How Can Pythongui.org Help Your Python Experience?

You should always continue learning; even pros don’t know everything. Practice is the key to success. Check out our posts and start learning Python scripting today using the best IDE, PyScripter.

Download PyScripter for free here.

The post 7 Easy Steps To Learning Python Scripting first appeared on Python GUI.

]]>
https://pythongui.org/7-easy-steps-to-learning-python-scripting/feed/ 0 8531
How To Create A FastAPI Server And Python GUI Client App To Manage Employees https://pythongui.org/how-to-create-a-fastapi-server-and-python-gui-client-app-to-manage-employees/ https://pythongui.org/how-to-create-a-fastapi-server-and-python-gui-client-app-to-manage-employees/#respond Tue, 25 Oct 2022 23:12:53 +0000 https://pythongui.org/?p=8442 Flask and FastAPI are popular Python micro-frameworks for building small-scale data science and machine learning-based websites or applications. Even though FastAPI is a relatively new framework, many developers use it in their new projects. In...

The post How To Create A FastAPI Server And Python GUI Client App To Manage Employees first appeared on Python GUI.

]]>
Flask and FastAPI are popular Python micro-frameworks for building small-scale data science and machine learning-based websites or applications. Even though FastAPI is a relatively new framework, many developers use it in their new projects. In this post, we will first discuss the reason for FastAPI’s popularity, followed by building a simple API using FastAPI in everyone’s favorite Python IDE: PyScripter. Then we will create a GUI in Delphi FMX that consumes this API. So, let’s get started!

Why is FastAPI Preferred to Make APIs?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees. An image of a laptop with some code on it.

FastAPI is a modern API development framework based on the Asynchronous Server Gateway Interface (ASGI) web server Uvicorn. Though it is new, you can also mount Web Server Gateway Interface (WSGI) applications using appropriate middleware. It is currently being used by many companies, among the most notable include Uber, Microsoft, Explosion AI, and others.

FastAPI easily supports concurrency and provides a simple and easy-to-use dependency injection system. Another advantage to consider is built-in data validation.

Most importantly, if we were to name one quality by which FastAPI beats Flask, it’s the excellent performance. FastAPI is known as one of the fastest Python web frameworks. Only Starlette and Uvicorn, which FastAPI is built upon, are faster. The superior performance of FastAPI is made possible by ASGI, enabling it to support concurrency and asynchronous code. This is accomplished by using async def syntax to declare the endpoints.

How Can We Build a Simple Employee Management System with FastAPI?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees -- a laptop showing the FastAPI homepage

This tutorial aims to teach you the basics of FastAPI with PythonGUI. So, we will create a REST API in PyScripter that serves as an employee management system.

What Are the Requirements for This FastAPI and Python GUI Tutorial?

You will require an IDE like PyScripter, Python3.9, and its FastAPI (with Uvicorn) as well as the DelphiFMX libraries.

After you have Python set up on your system, you can install FastAPI and Uvicorn using pip:

pip install fastapi uvicorn

If you followed the above steps correctly, you will now have a working instance of FastAPI and Uvicorn installed on your PC and are ready to learn how to use them. We will use the FastAPI framework to build our API, while Uvicorn will act as the server that will serve requests based on the API you build.

Similarly, to install DelphiFMX:

pip install delphifmx

How to Create a FastAPI Instance?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the PyScripter screen

Now, we will create a simple FastAPI app and run it with a server using Uvicorn.

from fastapi import FastAPI

app = FastAPI()

The code above is added to a file named main.py. In this case, the app variable is an instance of the FastAPI class. This will serve as the primary point of contact when developing your API.

This code defines your application but will not run if you call it directly with Python. A server program is required to run it. Uvicorn was already installed in the preceding steps and will be our server. But the question arises: where would all our data be stored, and how would it be managed?

What is User Model and How to Create a Database With Python?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - a class for the user DB showing in PyScripter

First, import BaseModel from pydantic and use it to create subclasses that define the schema, or data shapes, that you want to receive.

Next, you will declare your data model as a class inheriting from BaseModel, with all attributes being standard Python types:

from typing import List
from pydantic import BaseModel

class User(BaseModel):
    id: int
    firstName: str
    lastName: str
    gender: str
    role: str

Note: When a model attribute has a default value, it is not required.

Pydantic handles all data validation under the hood, so you get all the benefits and know you’re in good hands. For example, with pydantic, you can use the same type declarations with str, float, bool, and many other complex data types.

Now let’s create a database of users using the BaseModel, and populate it with some initial employees:

db: List[User] = [
    User(
        id=1, 
        firstName="Alina",
        lastName="Rahid",
        gender="F",
        role="Cashier" 
    ),
    User(
        id=2,
        firstName="Ahmed",
        lastName="Ali",
        gender="M",
        role="Admin"
    )
]

How to Create an Endpoint In Python For Our Employee Management System?

Now, we are making a simple endpoint, "users", that allow GET and POST calls so that one can get all the employee records or add an employee to the existing record:

@app.get("/users")
def fetchUsers():
    return db

@app.post("/users")
def addUser(user: User):
    db.append(user)
    return {"id": user.id}

This may seem a bit confusing at first, but rest assured, we will explain it in detail below. But another suggestion is to work in PyScripter as it offers the best syntax highlighting, which can help you organize and understand your code better. Furthermore, its integrated debugger can help you fix broken code quickly. So, if you’re a beginner in Python, PyScripter should be part of your starter kit.

How to Use the HTTP GET Method In Python?

The @app.get("/users") tells FastAPI that the function right below is in charge of handling requests that go to the path /users using a get operation. This is a path operation decorator or a path operation decorator. If you want to learn more about decorators, read the Python Decorators Primer.

FastAPI will invoke this function whenever it receives a GET request to the specified URL (/users).

With this, you can return lists, dictionaries, or single values as strings, integers, etc. Moreover, you can also return pydantic models, which is what we’re doing here.

How to Use the HTTP POST Method In Python?

In a function, you can declare the type of a path parameter using standard Python type hints. Declaring the path parameter’s type will provide editor support within your function, such as error checks and completion.

So, the final code looks like this:

from fastapi import FastAPI
from typing import List
from pydantic import BaseModel
import uvicorn

class User(BaseModel):
    id: int
    firstName: str
    lastName: str
    gender: str
    role: str

app = FastAPI()

db: List[User] = [
    User(
        id=1, 
        firstName="Alina",
        lastName="Rahid",
        gender="F",
        role="Cashier" 
    ),
    User(
        id=2,
        firstName="Ahmed",
        lastName="Ali",
        gender="M",
        role="Admin"
    )
]

@app.get("/users")
def fetchUsers():
    return db

@app.post("/users")
def addUser(user: User):
    db.append(user)
    return {"id": user.id}

How to Run the FastAPI Server For Our Python GUI Employee Management System?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - a PyScripter screen with the basemodel code showing in it

Now, you are all set to run your server and interact with the database using the API!

Add the following line to your main.py, and your API will be served via uvicorn on port 8000:

uvicorn.run(app, port=8000, host="127.0.0.1")

Then, normally execute the code in your python file.

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - PyScripter in action

The app will, by default, run on the localhost, i.e., http://127.0.0.1:8000. Overall, the output you get from running the command above shows the URL where your app is being served on your local machine. You can use the parameter reload=True in  uvicorn.run so that the server will reload automatically when you update your application code.

On a side note, an alternative way to run the server in through the following command in the terminal:

uvicorn main:app --reload

How to Make an HTTP GET Request In Python?

To get all the employee information, we will call the fetchUsers method. For this, you can go to http://127.0.0.1:8000/users.

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - a JSON result

How to Make an HTTP POSTRequest In Python?

Adding an employee instance to your existing records is comparatively tricky. But don’t worry; we’ve got you covered. The easiest way to make a POST request would be through the Swagger UI (In some later articles, we may discuss how to build REST clients, so keep a look out!)

What Are Swagger Docs?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the fastAPI get/post values

When you visit http://127.0.0.1:8000/docs in your browser, you will see an automatic, interactive API documentation. Here we have an option to make a POST call to the user endpoint.

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the request body

Once we execute this request, we will get a response:

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the response from the server

Here, we can see that the response is the employee’s id that has just been added, i.e., 3 in this case.

Swagger can also be used to make the GET request for the same endpoint. So let’s go ahead and execute it to check whether our records have been updated with the third employee.

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - making sure our records were updated

And it worked!

How to Create a REST Client in Python?

The HTTP protocol sends a client request to the web server, retrieving specific data and information if the transaction is legitimate. You could examine the server’s answer using many methods in the python request package.

Firstly, import the requests module to your code top. Then, for a GET request, we have to use the requests module get method to fetch all the data on the google server in a text form.

import requests

BASE = "http://127.0.0.1:8000/"

response = requests.get(BASE + "users")
response = response.json()

print(response)

A similar approach can be taken for making a POST request and getting the corresponding API response. Overall, one tip that cannot be emphasized enough is to use PyScripter for all your Python development. FastAPI and PyScripter produce a strong combination that will allow you to build APIs efficiently and can help boost your salary.

Why is PyScripter the Best IDE for Using FastAPI?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the PyScripter IDE page

PyScripter began as a simple integrated development environment (IDE) to supplement the excellent Python for Delphi (P4D) components by providing a reliable scripting solution for Delphi applications. It has a more modern UI and is faster than some other IDEs because it is written in a compiled language. It also has numerous features that make it an excellent Python development environment.

This fantastic IDE aims to create a Python IDE that can compete with traditional Windows-based IDEs for other languages. PyScripter is a fantastic program. With many features, it is lightweight, versatile, and extendable. Furthermore, compared to other text editors and general-purpose IDEs, it is significantly faster and more responsive because it was built from scratch with Windows in mind, making it a perfect match for Python GUI programming and application.

How Can We Build a Python GUI That Consumes This API?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - a laptop showing the DelphiVCL and DelphiFMX dowload pages

Let’s take our work a step further and use the amazing Python4Delphi’s DelphiFMX library to build a simple GUI that makes GET and POST requests to the API we have just created.

What is DelphiFMX?

DelphiFMX is a Python module that is natively compiled and powered by the Python4Delphi library. It is freely redistributable and provides Python developers access to the FireMonkey GUI framework for GUI development in Windows, macOS, Linux, and Android.

Embarcadero Delphi’s FireMonkey is a graphical user interface framework for native cross-platform application development that uses hardware-accelerated rendering using the GPU via DirectX or OpenGL. In addition, it has a robust styling system, is user-extensible, and does not require Delphi or any previous knowledge of Object Pascal.

How to Create a Simple Python GUI Application?

The code below creates a simple DelphiFMX application, a window (with name “Hello Delphi FMX”), and simply gives a greeting:

from delphifmx import *

Application.Initialize()
Application.Title = "Hello Delphi FMX"
Application.MainForm = Form(Application)
Application.MainForm.SetProps(Caption = "Hello World")
msg = Label(Application.MainForm)
msg.SetProps(Parent = Application.MainForm,
    Text = "Hello Python from Delphi FMX",
    Position = Position(PointF(20, 20)),
    Width = 200)
Application.MainForm.Show()
Application.Run() # This is the main loop
Application.MainForm.Destroy()
How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the example shown running

This code is taken from the GitHub repository of Python DelphiFMX. Several other sample codes in this repository will help you, master Python GUIs.

How to Enhance This Python GUI For Our Use Case?

Our code will be using two libraries:

import requests
from delphifmx import *

It is better to save your base URL (where the API is being served) as a global variable, BASE:

BASE = "http://127.0.0.1:8000/"
How To Create A FastAPI Server And Python GUI Client App To Manage Employees - image of the import requests

Now, we will define a class EmployeeManager that will define our main form:

class EmployeeManager(Form):

    def __init__(self, owner):
        “““ Initialization function, that initializes the form window and assigns different attributes to different parts of the form.”””
        # Initializing the main Wwindow and setting its name as “Employee Management”
        self.SetProps(Caption = "Employee Management", OnShow = self.__form_show, OnClose = self.__form_close)

        # Creating a Label called fName that will display the String “First Name: ” next to our input box.
        self.fName = Label(self)
        self.fName.SetProps(Parent = self, Text = "First Name: ", Position = Position(PointF(20, 20)))

        # Creating a Label called lName that will display the String “Last Name: ” next to our input box.
        self.lName = Label(self)
        self.lName.SetProps(Parent = self, Text = "Last Name: ", Position = Position(PointF(20, 45)))

        # Creating a Label called gender that will display the String “Gender: ” next to our input box.
        self.gender = Label(self)
        self.gender.SetProps(Parent = self, Text = "Gender: ", Position = Position(PointF(20, 70)))

        # Creating a Label called role that will display the String “Role: ” next to our input box.
        self.role = Label(self)
        self.role.SetProps(Parent = self, Text = "Role: ", Position = Position(PointF(20, 95)))

        # Creating a Label called id that will display the String “ID: ” next to our input box.
        self.id = Label(self)
        self.id.SetProps(Parent = self, Text = "ID: ", Position = Position(PointF(20, 120)))

        # Creating a TextBox named editFName that will allow us to add the First Name of our employees to the form.
        self.editFName = Edit(self)
        self.editFName.SetProps(Parent = self, Position = Position(PointF(80,20)), Height = 15)

        # Creating a TextBox named editLName that will allow us to add the Last Name of our employees to the form.
        self.editLName = Edit(self)
        self.editLName.SetProps(Parent = self, Position = Position(PointF(80,45)), Height = 15)

        # Creating a TextBox named editGender that will allow us to add the gender of our employees to the form.
        self.editGender = Edit(self)
        self.editGender.SetProps(Parent = self, Position = Position(PointF(80,70)), Height = 15)

        # Creating a TextBox named editRole that will allow us to add the Role of our employees to the form.
        self.editRole = Edit(self)
        self.editRole.SetProps(Parent = self, Position = Position(PointF(80,95)), Height = 15)

        # Creating a TextBox named editId that will allow us to add the id of our employees to the form.
        self.editId = Edit(self)
        self.editId.SetProps(Parent = self, Position = Position(PointF(80,120)), Height = 15)

        # Creating a Button named addEmployee that, when clicked, adds the entries in the textboxes to the database. The Button also displays some text specified in the “Text” parameter.
        self.addEmployee = Button(self)
        self.addEmployee.SetProps(Parent = self, Text = "Add Employee", Position = Position(PointF(250, 115)), Width = 90, OnClick = self.__button_click_add)

        # Creating a Button named “view” that, when clicked, displays all of the employees in our Database. It also displays some text specified in the “Text” parameter.
        self.view = Button(self)
        self.view.SetProps(Parent = self, Text = "View Employees", Position = Position(PointF(350, 115)), Width = 100, OnClick = self.__button_click_view)

        # Creating a ListBox named “list” that displays all of the employees in our Database.
        self.list = ListBox(self)
        self.list.SetProps(Parent = self, Position = Position(PointF(20, 140)), Width = 450, Height = 150)

    def __form_show(self, sender):
         “““This function initializes the dimensions of the form, and helps us show the form.”””
        self.SetProps(Width = 500, Height = 350)

    def __form_close(self, sender, action):
        “““ Function helps close the form by defining an action.”””
        action = "caFree"

    def __button_click_add(self, sender):
        “““ This Function, parses over all the text boxes on the form, creates JSON named “myobj,” send the JSON to the database, and finally adds it to our list object.”””

        # Initializing a JSON with all the employee details from the form.
        myobj = {"id":int(self.editId.text), "firstName":self.editFName.text,"lastName":self.editLName.text,"gender":self.editGender.text,"role":self.editRole.text}

        # Posting the JSON using FASTApi to our Database.
        x = requests.post(BASE+"users", json = myobj)

        # Adding the new Employee to our Database.
        self.list.items.add(x.text)
        self.list.items.add("Your Entry was successfully added!")
   
        # Resetting the text boxes as empty.
        self.editFName.text = self.editLName.text = self.editGender.text = self.editRole.text = self.editId.text = ""

    def __button_click_view(self, sender):
        “““ This function, when called, uses a FASTApi GET request to get a lists all the employees in the organization. It then displays said employees to the list box for display.”””

        # Getting all the employees from the database.
        response = requests.get(BASE + "users")

        # Storing the Employees into a JSON
        response = response.json()
        
        # Iterating over all the employees and adding them to the list box for display.
        self.list.items.text = ""
        for employee in response:
            self.list.items.add(employee)

Here, we are creating a simple form with five labels, First Name, Last Name, Gender, Role, and ID, using the Label method of delphifmx. Then we create editable text boxes corresponding to each of these five labels using Edit method. Next, we define two buttons, “Add Employee” and “View Employees” that call the __button_click_add and __button_click_view methods of our class, respectively, when clicked.

The __button_click_view method uses requests to make GET requests while the __button_click_view method uses the library to make POST requests. Responses to both these requests are printed for the user in the ListBox object names list.

Lastly, we will define our main method that initializes the form defined earlier:

def main():
    Application.Initialize()
    Application.Title = "Employee Management Using Delphi FMX"
    Application.MainForm = EmployeeManager(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

Adding the following lines will initiate the app whenever this Python code file is run:

if __name__ == '__main__':
    main()

Running the code will give us this GUI:

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - GUI1

Note, your server must be running via Uvicorn for the GUI to be completely functional. Now, let’s see everything we have done in action!

Clicking the “View Employees” button will show the two initial employees in the list box of the GUI. Now let’s add an employee via the GUI.

We should even be able to add a new employee. Below, we can see that the POST response (id of the added employee) is visible in the list box.

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - GUI 2

Let’s go ahead and even confirm that the employee records are updated. We will click the “View Employees” button to make the GET request.

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - testing the returned data

Congratulations on successfully reaching the end of this tutorial!

What Have We Learned From This Python GUI and FastAPI Tutorial?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the PyScripter download page shown on a laptop

In this tutorial, we learned a great deal about FastAPI and how you can use it to create your first production-ready API. We also looked at some best coding practices while providing the best developer experience possible with a great PythonGUI.

You learned how to receive JSON data in your API requests using pydantic and API best practices like validation and documentation while building APIs with FastAPI.

Designing a user interface does not have to be difficult. Pip packages provide access to a variety of Python tools. DelphiFMX is a powerful tool with numerous capabilities and customization options. Because of its inherent support for hardware acceleration, it is highly recommended for Windows developers. If you want to dive deeper into Python GUI’s offerings, you can download Python GUI’s getting started e-book.

Moreover, the true potential of these modules can only be availed through PyScipter. Why don’t you follow this tutorial right now in PyScripter? If you already have, then you’re ready to create your own highly performant APIs using your favorite IDE

What Are Some FAQs Relating to FastAPI and PythonGUI?

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - the PyScripter help shown on a laptop

What is DelphiFMX?

Delphi’s FireMonkey framework is Embarcadero’s Python module for developing graphical user interfaces (GUIs) for Windows, macOS, Linux, and Android.

This GUI framework is primarily used to develop GUIs for native cross-platform application development. For hardware-accelerated rendering, it uses the GPU via DirectX or OpenGL. In addition, it has a robust styling system and is user-extensible.

What is DelphiVCL?

The Visual Component Library (VCL) is a key part of Delphi’s state-of-the-art user interface support. It contains most native Windows controls and controls with additional features and functionality.

What is FastAPI?

FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints.

Which IDE should I use for Python Scripting?

Several IDEs exist for Python coding, including IDLE, Sublime Text, VS Code, PyCharm, and Atom. But as of yet, PyScripter seems to be the best Python IDE in the business and is loved by all Python developers.

How To Create A FastAPI Server And Python GUI Client App To Manage Employees - get a free Python GUI ebook

The post How To Create A FastAPI Server And Python GUI Client App To Manage Employees first appeared on Python GUI.

]]>
https://pythongui.org/how-to-create-a-fastapi-server-and-python-gui-client-app-to-manage-employees/feed/ 0 8442
How To Run A Python Script? https://pythongui.org/how-to-run-a-python-script/ https://pythongui.org/how-to-run-a-python-script/#respond Mon, 24 Oct 2022 10:00:00 +0000 https://pythongui.org/?p=8479 Are you a beginner in Python programming? The very first thing that you need to learn is to run a Python script. It will enable you to understand whether the code will work or not....

The post How To Run A Python Script? first appeared on Python GUI.

]]>
Are you a beginner in Python programming? The very first thing that you need to learn is to run a Python script. It will enable you to understand whether the code will work or not. Hence, you can efficiently handle the issues. There are different ways of running a Python script, but what are they? In this post we will tell you all you need to know on how to run a Python script. Let’s dive in.

How To Run A Python Script? The Python logo

How to run a Python script – what is Python, its basics, and how to get started with Python?

Python is the most popular programming language on the planet. It comes with a significantly easy syntax. As a result, anyone can quickly get familiar with it. Also, Python is widely used in web development, data science, and machine learning (ML) and AI projects. Hence, there is no shortage of jobs for talented developers.

You can consider Python as both a scripting and programming language. It can work both as a compiler and an interactive interpreter. A standard Python compiler can compile the lines of textual program code into binary bytecodes. Then the Python runtime can interpret the bytecode, just like Java and C runtimes do.

However, there is a historical relationship between general-purpose programming languages and scripting languages. Therefore, it will be more appropriate to consider Python as a general-purpose programming language rather than a specific purpose like Logo or TCL.

To get started with Python, you need to understand the syntax. Also, you have to learn all the basic concepts, including classes, functions, object-oriented programming, etc. Besides, you will need a tool to run a python script.

How To Run A Python Script? A close-up of a Python script

Scripts vs. Modules: What’s the difference?

In computing, a script is a simple program stored in a plain text file. It contains a logical sequence of orders or a batch-processing file. It enables you to sequentially execute the command.

A module is also a plain text file. However, it contains Python code. You can import the code or use it from another Python file.

Therefore, there is a subtle difference between a module and a script. Scripts are designed to be executed. On the other hand, modules are designed to be imported.

How to run a python script – what do you need to run a Python script?

To run a Python script, you need to ensure the following things:

  • Check if you have already installed Python on your PC. Simply run this code in the command prompt:
    python --version 

    If it’s not installed, go to the Python website to get the latest version of Python.

  • Download and install a high-performance code editor or IDE, like PyScripter.
  • Make sure to add Python to your system variable path. It will enable you to call it from the command line.

Read: 5 Real-Life Lessons About The Best IDE For Python

How to run a Python script – what’s the Python interpreter?

The Python interpreter is an application for running Python scripts. It works on the Read-Eval-Print-Loop (REPL) environment. Hence, it can read and evaluate the commands. Also, it can print the result, loop back, and repeat the process.

How To Run A Python Script? A keyboard

How to run a Python script – how to interactively run Python code?

You can run Python code through an interactive session. To start it, open the command line. Then you can write the code and hit enter to run it.

Let’s take an example of interactively running Python code on Windows. Simply open the terminal. Then add these lines:

C:Users2021>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

The last line shows these characters: >>>. That means you have entered into the interactive mode.

Now, you can write and run Python code the way you like. For example:

>>> print('Hello World!')
Hello World!
>>> 10+2
12
>>>

How to run a Python script – how does the interpreter run Python scripts?

The interpreter runs Python scripts by following the Python Execution Model. Here are the steps:

  1. First, the interpreter sequentially processes the statements of your script.
  2. Then it compiles the source code to bytecode
  3. Finally, it ships off the code for execution.

In the last step, Python Virtual Machine (PVM) comes into play. The PVM is the runtime engine of Python. It sequentially runs your bytecode.

How to run a Python script – how do I execute Python code from the command line?

By using the Python interactive session, you can write and run a lot of code. However, you lose everything as soon as you close the session. That’s why you should write Python programs in plain text files with the .py extension. You can easily create the files in a plain text editor, like Notepad.

Let’s create a test script. Open your favorite text editor. Then create a new file. Next, write the following code:

print('Hello World!')

Now, save the file with the name hello.py. You can run this Python script in different ways. Let’s find them out.

Using the “python” command

It is very easy to run Python scripts with the Python command. Simply follow these steps:

1. Open the command line. and type this line:

$ python hello.py

2. Hit the enter button. You will see this output:

Hello World! 

That’s it! You have managed to run your very first Python script.

Redirecting the Output

Redirecting the output is another great way. It allows you to save the script output for later analysis. You can do it by using this command:

$ python hello.py > output.txt

The command will redirect the output of hello.py to the output.txt file. The whole process is known as stream redirection. You can utilize it in both Windows and Unix-like systems.

Running modules with the -m option

The -m option allows you to run Python modules. It searches sys.path for the module name. It runs its content as main. Here is an example:

$ python -m hello
Hello World!

Using the script filename

Also, you can run the Python scripts by simply entering the file name. Here is an example to do it on Windows:

C:Ehsanul> hello.py
Hello World!

How to run a Python script – how to interactively run a Python script?

There are various ways for interactively running a Python script. Let’s find them out.

How to run a Python script – using “import”

Import in Python is analogous to #include in C or C++. You can import a module to load its content. Hence, you can conveniently access and use it later. By using import, the Python code in one module gets access to the code in another module.

Here is an example:

import first_script
Hello World!

How to run a Python script – using importlib

importlib is a module. It provides the implementation of the import statement in Python source code. importlib contains the import_module. It can execute any module or script by imitating the import operation.

Here is an example:

import importlib
importlib.import_module('first_script')
Hello World!
<module 'first_script' from 'UsersLocalPython37first_script.py'>

Now, let’s take a look at another example that utilizes the importlib.reload() function. It is useful for modifying and testing changes without exiting the current session.

import first_script #First import
Hello World!
import first_script
import importlib #Second import does nothing
importlib.reload(first_script)
Hello World!
<module 'first_script' from 'UsersLocalPython37first_script.py'>

Here, you are re-importing the module. Because you cannot use import to run it for the second time. You can try using import after the first time. But it won’t do anything.

Keep in mind that you can only use a module object as the argument of reload(). But you can’t use a string. It will lead you to a TypeError.

Let’s try using a string as the argument of reload().

importlib.reload(first_script)

You will see this TypeError:

Traceback (most recent call last):
...
...
  raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module

How to run a Python script – using runpy.run_module() and runpy.run_path()

runpy is a module of the Python Standard Library. It is used to locate and run Python modules without importing them first.

run_module() is a function in runpy. It can execute modules without importing them. Here is an example:

import runpy
runpy.run_module(mod_name='first_script')
Hello World!
{'__name__': 'first_script',
    ...
'_': None}}

Keep in mind that the first argument of the run_module() must contain a string.

Similarly, runpy contains another function, called run_path(). It enables you to run a module by providing a location.

Let’s take a look at an example:

import runpy
runpy.run_path(file_path='first_script.py')
Hello World!
{'__name__': '<run_path>',
    ...
'_': None}}

Here, you are specifying a file path by using runpy.run_path() function.

Both the runpy.run_module() and runpy.run() functions return the global dictionary of the executed module.

How to run a Python script – run Python script using exec()

You can utilize the built-in function exec() to run Python scripts. It is used for dynamic Python code execution.

Let’s take a look at an example:

exec(open('first_script.py').read())
Hello World!

Here, you are opening a Python file and reading its script.

How to run a Python script – run Python script using py_compile

The py_compile is a module. It provides a function to generate a byte-code file from a source file. It behaves like the import statement.

Let’s take a look at an example:

import py_compile
py_compile.compile('first_script.py' 
'__pycache__first_script.cpython-37.pyc' 

Here, you are using py_compile. compile() method to generate a byte code from first_script.py file.

The py_compile generates a new subdirectory, named “__pycache__”. Inside the subdirectory, the first_script.cpython-37.pyc file will be created. When you open it, you will see the output of the Python script.

How to run your Python script with an IDE or a text editor?

An integrated development environment (IDE) is software for building applications. It combines common developer tools into a single GUI. Hence, you can conveniently create applications.

There are plenty of IDEs available. For example, you can use Python IDLE. It is the default IDE of the standard Python Distribution. You can use it to write, debug, modify, and run your modules and scripts. Also, you can consider using other IDEs like PyCharm and Eclipse.

However, the best option is PyScripter. It is a feature-rich IDE. Also, it’s open-source. Hence, you don’t have to spend any money to use the IDE.

To run a Python script from your IDE or text editor, you need to create a project. Then you need to add your .py file to it. Also, you can simply create a new file with the IDE. Once you are done, run the file. If everything is OK, you will see the appropriate output.

Read: What Is The Best Python Editor In 2022?

Can I use browser-based IDEs to run a Python script?

Python is the most popular programming language on the planet. But unlike other languages, like JavaScript, it can’t be run in the browser.

How do I use a file manager to run Python scripts?

It’s very easy to run a Python script using File Manager. Simply double-click on its icon. It will start to run. The method might not be used in the development stage. But once you release the code, you are very likely to run it by double-clicking on the icon.

However, you need to meet some conditions to use the method. They depend on your operating system.

For instance, in Windows operating system, the .py and .pyw extensions are associated with the python.exe and pythonw.exe programs. Hence, you can double-click on them to run the scripts.

How to run your Python script using the built-in Python idle?

The way of executing a file in IDLE is very simple. Simply press the F5 key on your keyboard. The Python script will start to run. Alternatively, you can go to the menu bar and select Run > Run Module.

How to run a Python script as a module in another Python file?

There are multiple ways to make one Python file run another. Let’s find them out.

How to run a Python script – use a Python script like a module

How about importing the file you want to run? You can run its functions in another Python file. For instance, you need to import file1.py into file2.py. You have put all the files in the same folder. Inside file1.py, you have to add this line:

import file2

Now, you can call any function inside file2.py. For instance, you can call my_function() in this way:

file2.my_func()

How to run a Python script – use the “exec” command

You can use the exec command to run the Python script as a module in another file.

Here is an example:

execfile('file.py')

Here, you are executing the file.py file in the interpreter.

How to run a Python script – use the “os.system” command

You can utilize the os.system command to spawn a new process.

Here is an example:

os.system('python my_file.py')

Why is Pyscripter one of the best ways to run a Python script?

PyScripter is free and open source. Hence, you don’t have to spend any penny to use it. Also, PyScripter lets you choose your preferred Python version. You just need to utilize command-line parameters. Besides, it provides full support for encoded Python source. Hence, PyScripter is considered to be one of the best tools to run a Python script.

PyScripter is a powerful Python IDE built on Delphi. It offers several amazing features, including the remote engine, remote debugger, and integrated unit testing. Try it now for free. 

FAQ

How do I run a Python script or code?

Simply open the command line. Next, type in the word python. Then insert the path to your script, just like this: python hello.py. Finally, press the Enter key. Your Python script will begin to run.

How do I run a .PY file in CMD?

Open Command Prompt. Then type “python” and your file name, like this: python hi.py. Once you are done, hit the Enter key. If everything is OK, your Python will start to run in CMD.

How do you run a .PY file on Windows?

On the latest version of Windows, you can run Python scripts by typing the Python file name in the command prompt. For example, you can run the hello.py file by entering this line: C:ehsanul> hello.py.

How do I run a Python script line by line?

You can run a Python code line by line by utilizing the Python interpreter. You can start it by installing the Python language on your PC. Then you have to launch the Command Prompt and type python.

How do I run Python in the terminal?

To run Python in the terminal, open the command line and type in python. Next, hit the Enter key. Python will begin to run in the terminal.

The post How To Run A Python Script? first appeared on Python GUI.

]]>
https://pythongui.org/how-to-run-a-python-script/feed/ 0 8479
How To Add Python Testing Tools Into Machine Learning Code: Testing NumPy https://pythongui.org/how-to-add-python-testing-tools-into-machine-learning-code-testing-numpy/ https://pythongui.org/how-to-add-python-testing-tools-into-machine-learning-code-testing-numpy/#respond Mon, 17 Oct 2022 10:00:00 +0000 https://pythongui.org/?p=8399 Testing your code is critical throughout the software development life cycle. If follows from this that selecting – and employing – the appropriate Python testing tools should be an essential part of writing high-quality code....

The post How To Add Python Testing Tools Into Machine Learning Code: Testing NumPy first appeared on Python GUI.

]]>
Testing your code is critical throughout the software development life cycle. If follows from this that selecting – and employing – the appropriate Python testing tools should be an essential part of writing high-quality code.

Writing code tests and running them in parallel with the development of the actual core program is now considered best practice. Unfortunately, this kind of testing mechanism is often skipped by beginners. Testing, when used wisely, can help you define your code’s intent more precisely and create a more decoupled architecture. If you don’t test your Python code BEFORE it reaches your end users, you risk losing their trust if the program contains bugs, or, even worse, completely destroys your app’s reputation so that no one wants to use it. In this highly connected world, reputation plays a big part in potential success.

For more introduction to testing with Python, please read our article about Python’s built-in unit testing framework here:

 

A summary of Test Driven Development (TDD)

Testing is so important to good software development that it has its own software development methodology; Test Driven Development (TDD).

Robert C. Martin [2] proposed three TDD rules:

  1. Writing production code is not permitted unless it is necessary to fix a failing unit test.
  2. You are not permitted to write more of a unit test than is required to fail, and compilation failures are considered failures.
  3. You may not write any more production code than is required to pass the one failing unit test.

The central concept of TDD is that we base our software development on a set of unit tests that we have written at the outset of coding, making unit testing the heart of the TDD software development process. This ensures that you have a test for every component you develop.

TDD is also biased toward smaller tests, which means more specific tests that test fewer components at a time. This helps with error detection, and smaller tests are also easier to read and understand because there are fewer components at work in a single run.

It does not imply that you must use TDD in your projects. However, you may consider that as a method of developing your code and the tests at the same time.

 

What role does testing play in machine learning?

In Machine Learning testing, the programmer enters input and observes the machine’s behavior and logic.

As a result, the goal of testing machine learning is to ensure that the machine’s logic remains consistent. Even after multiple calls to the program, the logic should not change.

Machine Learning is tested by supplying new or previously unseen data from a sample/distribution. As a result, generalization refers to a model’s ability to adapt to unknown data/scenarios (drawn from the same distribution as the one used to create the model).

 

What’s different about testing machine learning systems?

Here are the schematic differences between testing software vs testing machine learning system: 

Traditional software systems

testing machine learning code python 1
The scheme of traditional software systems. Source: Reference [3].

In traditional software systems, humans write the logic that interacts with data to produce the desired behavior. Our software tests help ensure that the written logic corresponds to the expected behavior.

Machine Learning software systems

testing machine learning code python 2
The scheme of Machine Learning software systems. Source: Reference [3].

However, in machine learning systems, humans provide desired behavior as examples during training, and the model optimization process produces the system’s logic.

Traditional software testing workflow

testing machine learning code python 3
A typical workflow for software development. Source: Reference [3].

Machine Learning system testing workflow

testing machine learning code python 4
A typical workflow for machine learning model development. Source: Reference [3].
testing machine learning code python 5
A proposed workflow for developing high-quality models. Source: Reference [3].

Machine learning systems are more difficult to test because the logic of the system is not explicitly written. However, automated testing remains an important tool for creating high-quality software systems. These tests can generate a behavioral report of trained models, which can be used as a systematic approach to error analysis.

 

What exactly is NumPy?

NumPy is a well-known Python library for scientific computing. NumPy stands for “Numerical Python.” NumPy is the foundational Python package for array computing.

The operations in NumPy are divided into three main groups: Fourier Transform and Shape Manipulation, Mathematical and Logical Operations, and Linear Algebra and Random Number Generation. NumPy is written in C and Python to make it as fast as possible.

In addition to its obvious scientific applications, NumPy can be used as an efficient multi-dimensional container of generic data. It is possible to define arbitrary data types. This enables NumPy to easily and quickly integrate with a wide range of databases.

 

How do I get the NumPy library?

You can get NumPy using the pip command to your command prompt:

pip install numpy

Or, if you use Anaconda Environment, you can install NumPy with:

conda install numpy

 

NumPy testing guidelines

Run the tests from inside the Python script or IDE

NumPy can be tested in several ways. It can, for example, be run from within Python or an IDE:

import numpy

numpy.test(label='slow')
testing numpy python 1
The NumPy testing outputs inside PyScripter IDE.

Run testing from the command prompt

Requirements 

The following are the required libraries to perform NumPy testing in your command prompt:

pytest

You can get pytest using the pip command to your command prompt:

pip install pytest

Or, if you use Anaconda Environment, you can install NumPy with conda install:

conda install -c anaconda pytest
hypothesis

Install with pip:

pip install hypothesis

Install with conda:

conda install -c conda-forge hypothesis

Here is a basic example of Python testing using NumPy

After installing NumPy, pytest, and hypothesis properly, tests can then be run easily with the following command:

python -c "import numpy; numpy.test()"

Excerpt of the output:

testing numpy python 2
testing numpy python 3

 

numpy.testing examples

In this section, we will show you several examples of numpy.testing, or NumPy’s test support.

numpy.testing.assert_allclose

Description

If two objects are not equal within the specified tolerance, an AssertionError is raised.

allclose(actual, desired, rtol, atol) is the equivalent test (note that allclose has different default values). The difference between actual and desired is compared to atol + rtol * abs (desired).

Parameters

actual: array_like. The array was obtained.

desired: array_like. Array desired.

rtol: float, optional. Relative tolerance.

atol: float, optional. Absolute tolerance.

equal_nan: bool, optional. NaNs will compare equally if True.

err_msg: str, optional. The error message is to be printed in case of failure.

verbose: bool, optional. If True, the values that conflict are appended to the error message.

Raises

AssertionError. If the actual and desired values do not match the specified precision.

No output is expected if the test passes.

An example of using PyScripter for Python unit tests with NumPy

Code example:

import numpy as np

x = [1e-5, 1e-3, 1e-1]
y = np.arccos(np.cos(x))
np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)

I set the x to not equal the rtol value to get the failed output:

import numpy as np

x = [1e-7, 1e-3, 1e-1]
y = np.arccos(np.cos(x))
np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)

Example of failed output in PyScripter IDE:

testing numpy python 4

numpy.testing. assert_array_almost_equal_nulp

Description

Compare two arrays relatively to their spacing.

This is a relatively robust method for comparing two arrays with variable amplitudes.

Parameters

x, y: array_like. Input arrays.

nulp: int, optional. The maximum number of units in the last place for tolerance (see Notes in Reference [5]). The default value is 1.

Returns

None

Raises

AssertionError. If the spacing between x and y for one or more elements is larger than nulp.

Here’s another Python testing example

Code example:

import numpy as np

x = np.array([1., 1e-10, 1e-20])
eps = np.finfo(x.dtype).eps
np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

Example of failed output in PyScripter IDE:

import numpy as np

x = np.array([1., 1e-10, 1e-20])
eps = np.finfo(x.dtype).eps
np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
testing numpy python 5

numpy.testing.run_module_suite

Description

Run a test module.

Equivalent to calling $ nosetests <argv> <file_to_run> from the command line

Parameters

file_to_run: str, optional. The path to the test module, or None. Run the module from which this function is called by default.

argv: list of strings. Arguments are to be passed to the nose test runner. argv[0] is ignored. All command line arguments accepted by nosetests will work. If the value is None, sys.argv is used.

Here is an example of Python testing using PyScripter

Code example (example of the failed output in PyScripter IDE):

import numpy as np

np.testing.run_module_suite(file_to_run="numpy/tests/test_numpy_version.py")

The code above will run all the test routines in ‘test_numpy_version.py’:

testing numpy python 6

Click here to start using PyScripter, a free, feature-rich, and lightweight IDE for Python developers.

Download RAD Studio to build more powerful Python GUI Windows Apps 5x Faster with Less Code.

Check out Python4Delphi which easily allows you to build Python GUIs for Windows using Delphi.

Also, check out DelphiVCL which easily allows you to build GUIs for Windows using Python.


References & further readings

[1] NumPy Developers. (2008-2022).

Test Support (numpy.testing). NumPy documentation. numpy.org/doc/stable/reference/routines.testing. html

[2] Martin, R. C. (2009).

The three laws of TDD. Robert C. Martin “Uncle Bob” personal website. butunclebob.com/ArticleS.UncleBob. TheThreeRulesOfTdd

[3] Jordan, J. (2020).

Effective testing for machine learning systems. Jeremy Jordan personal website. jeremyjordan.me/testing-ml

[4] NumPy Developers. (2008-2022).

Testing Guidelines. NumPy documentation. numpy.org/doc/stable/reference/testing.html

[5] NumPy Developers. (2008-2022).

numpy.testing.assert_array_almost_equal_nulp. NumPy documentation. numpy.org/doc/stable/reference/generated/ numpy.testing.assert_array_almost_equal_nulp.html

The post How To Add Python Testing Tools Into Machine Learning Code: Testing NumPy first appeared on Python GUI.

]]>
https://pythongui.org/how-to-add-python-testing-tools-into-machine-learning-code-testing-numpy/feed/ 0 8399
Python Programming Jobs That Have High Paying Salary https://pythongui.org/python-programming-jobs-that-have-high-paying-salary/ https://pythongui.org/python-programming-jobs-that-have-high-paying-salary/#respond Wed, 12 Oct 2022 10:00:00 +0000 https://pythongui.org/?p=8385 Python is one of the most popular programming languages on the planet. It is very easy to learn and use. Also, it has a broad, diverse range of powerful libraries and offers highly scalable code....

The post Python Programming Jobs That Have High Paying Salary first appeared on Python GUI.

]]>
Python is one of the most popular programming languages on the planet. It is very easy to learn and use. Also, it has a broad, diverse range of powerful libraries and offers highly scalable code. Combining the best Python coding software with Python’s great features allows even novice programmers to very quickly get to the point of creating really great professional-quality solutions. Today, the Python programming language is not only used in web development and SEO. It is also widely used in emerging fields, like data science, machine learning, artificial intelligence, Fintech, IoT, and big-data analytics. Therefore, Python programmers have a huge future with more and more employers looking to deploy Python solutions in-house and elsewhere to help meet their operational goals and provide solutions to business needs. But which Python programming jobs offer high-paying salaries? In this post, you will find all the details. Note that throughout we have listed likely salary amounts in US dollars based on our own research at the time of publication and current publicly available data. The rates for other countries and territories of course varies widely but the scale shown gives you some indication of the kind of value employers place on each of the various types of Python programming job.

baaeeb18-ea0a-425c-89fe-506c3123a64e-2237148

Why is Python one of the best software programming languages to learn for getting high-paying jobs?

Development teams around the world are utilizing Python for advanced projects. For example, it has established itself as the best programming language for developing Machine Learning and AI solutions. These are the hottest areas of the technology world right now. Companies are willing to pay a huge amount of salary for developing specific solutions. Also, it seems a clear trend that the number of Python jobs will continue to increase in the coming years. Therefore, Python is the best software programming language to learn right now not only because of how easy it is to learn but also for great job availability and generous salary compensation.

What are the high-paying Python programming jobs?

The highest-paying Python programming jobs are:

High-Paying Python Programming Jobs - Python Architect

High-paying Python programming jobs – Python Architect

Salary range: $132,000-$176,500 per year

Python Architect is a high-paying Python programming job. It involves handling both the front end and back end of the project. Hence, the job is quite similar to that of a full stack Python developer. To get this job, you must have a robust working knowledge of Python. Also, you will need to know front-end technologies, like ReactJS or AngularJS. Besides, you need to be familiar with a variety of libraries, including Numpy and Pandas.

High-Paying Python Programming Jobs - Python Consultant

High-paying Python programming jobs – Python Consultant

Salary range: $79,500-$176,000 per year

Python consultants use data manipulation and analysis to generate key insights. They present results and suggestions to clients. Also, Python consultants develop predictive models and provide design assistance. It is one of the high-paying Python engineering jobs. An entry-level Python consultant can earn $79,500 per year. However, experienced professionals can expect to earn up to $176,000.

High-Paying Python Programming Jobs - Python Web Developer

High-paying Python programming jobs – Python Web Developer

Salary range: $70,000-$142,500 per year

Python web developers create web apps using Python. Also, they often use other programming languages in combination with Python. For example, Python web developers frequently use JavaScript to create different elements. On the other hand, they may also use other programming languages to write code for server-side application logic depending on the solution’s requirements. The Python code enables them to connect elements with servers and databases and facilitate data collection, collation and presentation. The typical Python web developer’s salary starts at $70,000 per year. However, as you gain experience, you can earn as high as $142,5000 a year. Therefore, being an experienced Python Web Developer is one of the high-paying Python programming jobs.

High-Paying Python Programming Jobs - Python Django Developer

High-paying Python programming jobs – Python Django Developer

Salary range: $103,500-$134,500 per year

As a Python Django developer, you develop back-end components for web applications based on the hugely popular Django framework. Then you integrate them with the front end. For this job, you need to be well-versed in Python programming language. Also, it’s important to have strong troubleshooting skills. You also need to efficiently debug applications. The salary range of the Python Django developer is $103,500-$134,500 per year. Django is really popular with non-technical companies to provide web app functionality. These companies often do not need a full-time developer but do need regular development and maintenance of their Django-based apps. As a result, there are also a significant number of temporary or recurring contract positions available for Python developers who have experience working with Django which help enhance your income. This all combines to mean that being a Django Python developer can often be one of the highest-paying Python programming jobs.

High-Paying Python Programming Jobs - Python Software Developer

High-paying Python programming jobs – Python Software Developer

Salary range: $96,000-$129,000 per year

The role of a Python Developer is to design, code and deploy web development projects. Also, you need to implement security solutions and integrate applications with third-party services. Typically, you have to work on the server side or back end. However, you need to know front-end technologies too. It is one of the high-paying Python programming jobs on the market. The salary range is $96,000-$129,000 per year.

b3a36f2a-65e7-459d-bbc3-b8e7fe007ddf-5233776

What is the Python programming job salary range in terms of experience? 

The amount you can expect as a Python programming job salary varies in terms of experience working on development projects. Let’s find out the details.

Entry-level Python developer salary 

The average entry-level Python developer salary is around $59,888 – $111,605 per year. This kind of role is typical open to either a developer with little or no development experience at all. Some employers also would consider internships which may be on the lower pay scale (or in rare cases unpaid) in return for “on the job” education in Python application development. Internships can also allow an entry-level Python developer to gain experience which can enhance their ability to get higher-paid Python jobs.

Junior Python developer salary 

Junior Python developers earn an average salary of $117,940 per year. A Junior Python developer is often a person who has recently left education or has some limited professional or unpaid experience in software development with Python. The expectation is that the Junior can write Python code and has a working knowledge of Python but is not sufficiently experienced in the language or software development in general to write programs without some additional help from senior developers.

Senior Python developer salary 

The average salary of a senior Python developer is $132,789-145,923 per year. A Senior Python developer is expected to be well experienced in writing Python code. Typically, in larger organizations, a Senior Python Developer may have more junior developers working with them. The Senior Python Developer would usually be expected to act as mentor to more junior or less experienced staff. They would also be expected to offer technical guidance on Python development and advice on broader subjects such as best practices on coding and project management.

c078b605-9f4c-45aa-a8e7-c47cdf573ebe-6684949

What is the average Python programming job salary in the United States of America?

According to Glassdoor, the average salary of a Python developer in the U.S. is $96,890. However, the range varies in terms of locations. Let’s find the average Python programming job salaries in the United States in some of the high-paying locations:

  • Python programmer salary in New York (NY): $132,598/year
  • Python developer salary in California: $138,466/year
  • Python programmer salary in San Francisco: $143,476/year
  • Python developer salary in Virginia: $108,649/year

What is the average Python developer salary in the UK and India?

On average, a Python developer earns £67,540/year in the UK at the time of publication. In India, it is INR 427,293 per annum.

Do I need to have a Bachelor’s degree in Computer Science to get a Python programming job?

No, you don’t need to have a Bachelor’s degree in Computer Science. People have managed to find high-paying developer jobs without any university education. Generally, competition for jobs can be intense and candidates with formal qualifications in disciplines related to software development will be preferred over others. A provable record of work on Python projects, especially over a number of years, can mean that employers are less concerned about degrees. It’s not uncommon for an employer to prefer someone who has practical experience of Python programming over any sort of qualification. My personal advice is if you think you can do the job, gather together as much evidence as possible and apply anyway.

What are the best tools for Python programming jobs?

Developers utilize a variety of tools for Python programming jobs. However, the best one is PyScripter. It is a lightweight and feature-rich IDE. It allows you to conveniently work on Python programming projects.

Why is PyScripter the best Python programming tool?

  • Free and open-source IDE
  • Supports Python version switching on-the-fly via command-line parameters
  • Provides integrated unit testing and regular expression testing support
  • Offers full support for encoded Python source
  • Supports remote development using SSH

Should I use PyScripter in 2022?

PyScripter comes with several useful features. For instance, it supports the code completion option. Hence, you can conveniently code your solution. Also, PyScripter supports the split-screen feature. As a result, you can split the workspace and code side by side. On top of that, it allows you to work with Jupyter Notebook files. Hence, it is suitable for Data Science projects. For all these reasons, you should definitely use PyScripter in 2022 and beyond.

PyScripter is a powerful Python IDE built on Delphi. It offers several amazing features, including the remote engine, remote debugger, and integrated unit testing. Try it now for free. 

FAQ

What kind of job can I get with Python?

With Python, you can get a variety of jobs, including Python Developer, Data Scientist, and Machine Learning Engineer.

How much do Python coders make?

A Python programmer roughly makes $54 per hour. At the entry-level, a Python Developer earns $92,500 per annum. However, the salary can reach $130,000 at the senior level. Top Python coders make $150,000 or more.

Is being a Python programmer a good career choice?

Yes, being a Python programmer is a great career choice. The language is widely used in emerging fields, including Data Science, Machine Learning, and Artificial Intelligence. Also, developers use it for building high-performance web apps. In every sector of industry, Python programmers are in great demand.

Can I learn Python at 45 and get a job?

Of course, you can learn Python at 45! If you possess the necessary technical knowledge and skills, you can get a Python programming job at any age. There are many employment opportunities in this area. Therefore, nobody will care about your age. Besides, you have the choice to pursue freelancing. Hence, there is no shortage of opportunities for skilled Python developers. You should also note that in most countries it’s illegal to discriminate against candidates based on age, gender, physical abilities, and other similar factors. Many companies use formal application processes which ensure that your age cannot be taken into account during the application process.

The post Python Programming Jobs That Have High Paying Salary first appeared on Python GUI.

]]>
https://pythongui.org/python-programming-jobs-that-have-high-paying-salary/feed/ 0 8385
Python Development Tools: Your Python Starter Kit https://pythongui.org/python-development-tools-your-python-starter-kit/ https://pythongui.org/python-development-tools-your-python-starter-kit/#respond Mon, 10 Oct 2022 10:00:00 +0000 https://pythongui.org/?p=8356 All good software developers must use the right tools. Devs typically write their code using an IDE. A developer will likely undertake several projects simultaneously, so it’s helpful to have an efficient way of organizing...

The post Python Development Tools: Your Python Starter Kit first appeared on Python GUI.

]]>
All good software developers must use the right tools. Devs typically write their code using an IDE. A developer will likely undertake several projects simultaneously, so it’s helpful to have an efficient way of organizing these projects. Currently, Python is widely used worldwide. Depending upon the purpose and system requirement, your project will have various tools available.

Where is Python used?

Python is one of the most universal programming languages, and it can be used in data science, scientific computing, machine learning, web development, for creating complex codes to execute multiple operations on servers, or just for simple scripts.

Python Development Tools: Your Python Starter Kit - a person staring at a large computer display with two laptops open on the desk

What Python development tools do you recommend?

Python is an open-source programming language that runs on all major operating systems (Linux, Mac, Windows), and its easy syntax makes it a popular choice among beginners. Python programmers should use an integrated development environment (IDE) to speed up their workflow. We have reviewed the 10 most popular GUIs together with their pros and cons in this article:

Or if you want to start right away, just download PyScripter, our favorite integrated development environment and start coding.

What features should an IDE offer?

With so many options available, it might be confusing how to choose an IDE that fits all your needs. Must-have features of a good IDE include

  • Syntax highlighting
  • Code completion
  • A project explorer
  • A Python interpreter
  • A debugger

Modern features include

  • Integration with Python development tools such as PyLint, TabNanny and Profile
  • Easy switch between different Python versions
  • Unit testing
  • Remote work

You can find all the above features in PyScripter.

Python Development Tools: Your Python Starter Kit. The PyScripter download page open on a laptop.

Some GUIs are able to handle not just Python but also other powerful programming languages such as C or Java, for example, Visual Studio code. However, we recommend using a tool that is specific to the programming language you intend to use.

What Python packages should I install and how?

There are some universal Python packages that are used in many Python projects, while others are only written with a limited application in mind. Mathematical functions are found in the numpy library, data scientists often employ pandas as the frontend to read in data and analyse it. More specific math routines for data analysis are found in the package scipy. Popular machine learning packages are TensorFlow and PyTorch.

The traditional way to install packages is via a smart tool called pip which is invoked from the command line. However, advanced IDEs such as PyScripter offer a built-in call to pip, so that you never need to leave the IDE window when you are missing a package. You simply need to head over to Tools -> Tools -> Install Packages with pip.

A Miniconda or an Anaconda installation comes bundled with all kinds of packages. That makes it easier to just start writing code, but most likely all the Python packages that come along are something you will never need. You can decide for yourself whether you would like to install by hand or get all at once.

How to evaluate the performance of my code?

There are various ways to evaluate how efficient code is. The simplest way is to just print the time via the datetime package, however, this is a very outdated approach. Nowadays, there are specialized profiling tools that perform a deep analysis of the code. They report CPU and memory usage, and identify bottlenecks.

Python Development Tools: Your Python Starter Kit - a screenshot of a Python program being profiled in PyScripter

How to debug code?

Debugging is a critical part of coding. Everybody makes mistakes, but sometimes they are not so obvious. The script crashes and it leaves the programmer confused. Coding should not be like that. That is why there are useful debugging tools that you need to know if you want to learn Python coding properly.

The Python programming language is interpreted, which is in contrast to other traditional languages such as C and Fortran which need to be compiled. The compiler does some checks while building an executable, whereas, the Python interpreter tends to recognise only syntax errors. It cannot take any flags specifying the computer architecture or code optimisation level.

What are some useful Python projects that I can try?

If you have have familiarized yourself with the basics, you can try creating some simple and efficient tool for Python automation. You will be surprised at how useful these can be since Python is one of the most versatile multi-purpose programming languages. You can extract data, for example, by parsing html documents, or edit an Excel sheet without even opening it in MS Excel. Python code can send emails, for example.

If you want to jump straight into the deep, you can try performing machine learning algorithms. There are open-source data sets online that data science researchers have shared with the world for free. Just make a quick Google search and you will find many examples and tutorials. Maybe you will create a cool artificial intelligence tool using Python data science libraries?

Can I make a graphical interface in Python?

Absolutely. There are many useful Python tools for creating a graphical user interface (GUI). You can check out the list of Python packages that we have reviewed recently. Also, we have a practical example for building a Python GUI currency converter. You can start by watching the videos in the following article and write test scripts to see which tool offers what you need.

Frequently asked questions

Which tool is best for Python development?

If you want to be a better Python developer, you should learn how to code efficiently. There is no need to reinvent the wheel. Just download Python and an IDE such as PyScripter and start coding.

Is Python a software development tool?

Not quite. Python is a programming language. There are various software developer tools that may come with a code editor, a debugger and an interpreter.

What tools do I need to learn Python?

You should start by installing an integrated development environment. There are various options. Most IDEs offer the basic tools python developers need on a daily basis. Some come with advanced features. For more information,

Is Jupyter an IDE?

Jupyter is an alternative to traditional IDEs that runs in various and multiple browsers. It is a Python code editor and runs a Python kernel, so that you can execute your scripts, but there are no debugging tools. Also, you cannot build GUI programs via the browser notebook. However, it allows you to learn Python online.

Can Notepad++ run Python?

No. Notepad++ is a text editor. It supports code syntax highlighting, but it cannot run a Python program.

To conclude

Python is a language that suits not only software engineers but any enthusiast who wants to know more about programming. There are countless Python modules, so that you do not need to write everything from scratch. The nice thing about a Python script or program is that it can be run on multiple platforms. And remember that practice makes perfect. The most useful Python tools are those that make your coding life easier, so you should test out various options and see what feels best.

Start learning Python today in PyScripter. Click here to download it.

The post Python Development Tools: Your Python Starter Kit first appeared on Python GUI.

]]>
https://pythongui.org/python-development-tools-your-python-starter-kit/feed/ 0 8356
Top 7 Web Scraping Tools – Python For Data Scientists https://pythongui.org/top-7-web-scraping-tools-python-for-data-scientists/ https://pythongui.org/top-7-web-scraping-tools-python-for-data-scientists/#respond Fri, 07 Oct 2022 14:00:00 +0000 https://pythongui.org/?p=8339 Machine learning powers modern technological marvels like speech recognition and driverless cars. However, for a data scientist to create such a model would require a significant data amount of data. That’s where web scraping Python...

The post Top 7 Web Scraping Tools – Python For Data Scientists first appeared on Python GUI.

]]>
Machine learning powers modern technological marvels like speech recognition and driverless cars. However, for a data scientist to create such a model would require a significant data amount of data. That’s where web scraping Python comes in. It’s definitely worth taking time to find the best web scraping tools Python has to offer since it’s an area Python really excels at.

Web scraping now encompasses data scraping methods for obtaining information from websites. This copying technique gathers and duplicates publicly accessible web data, usually into a single local database or spreadsheet for quick access or analysis. Use web data for machine learning tasks, analysis and even for competing with and outperforming rivals. Developers can create web crawlers that effectively scrape data from the web using any robust programming language, especially Python. Python is a fantastic choice for programmers to create web scrapers because it comes with native libraries made just for web scraping. So, in this article, we will loop at the top 7 best web scraping tools Python, for web scraping applications.

Which are the most commonly used web scraping libraries?

Top 7 Web Scraping Tools - Python For Data Scientists. A computer showing the Beautiful Soup download page

Beautiful Soup is one of the Python web scraping libraries that can extract data from XML documents and parse HTML files. It’s creation was primarily for tasks like screen scraping. This library offers straightforward methods and Pythonic idioms to navigate, search within, and modify a parse tree. With the use of this tool, documents are automatically converted from UTF-8 to Unicode upon receipt.

In addition, encoding detection is a valuable feature of BeautifulSoup that can produce better results for genuine HTML sites that do not fully disclose their encoding.

What makes Scrapy a good tool for web scraping?

Top 7 Web Scraping Tools - Python For Data Scientists. The Scrapy home page.

Scrapy is an open-source and collaborative framework that allows users to extract the information they require from websites. Scrapy is a quick, high-level web crawling and scraping framework for Python written in Python. Also, it can be applied to various tasks, including data mining, monitoring, and automated testing. In addition, it serves as a framework for application developers to create web crawler Python that mines websites for data and to scrape data from a website and Scrapy uses classes called “Spiders,” defined by the user.

What is LXML?

Top 7 Web Scraping Tools - Python For Data Scientists. The lxml page.

LXML is a Python library that uses The libxml2 and libxslt C libraries. It is regarded as one of the most feature-rich and user-friendly Python libraries for processing XML and HTML. Moreover, it is exceptional in that it largely complements but outperforms the well-known ElementTree API by combining the speed and XML functionality of these libraries with the simplicity of a native Python API.

The Python LXML package offers a performance advantage over the competition and even fairly large XML files can be read and written in negligible amounts of time.

What is MechanicalSoup?

Top 7 Web Scraping Tools - Python For Data Scientists. A laptop showing the user is on the Mechanical Soup home page.

The developer of MechanicalSoup is M Hickford, a fan of the Mechanize library. Python’s MechanicalSoup library allows you to automate website interaction. This library automatically sends and stores cookies, navigates through redirects, clicks on links, and fills out forms. Built on the powerful Python libraries Requests (for HTTP sessions) and BeautifulSoup, MechanicalSoup offers a comparable API (for document navigation).

MechanicalSoup intends to mimic how humans interact with web browsers. Among the possible applications are:

  • Interacting with non-API-provided websites
  • You’re putting your new web page or website to the test.
  • Interface for browsing

However, because it does not support python 3, this tool did not undergo maintenance for a while but is now publicly available for Python versions 3.6+.

Which is the most simple Python web scraping library?

Top 7 Web Scraping Tools - Python For Data Scientists. A laptop with a small wooden artist's posing mannequin next to it.

Requests is another Python library that sends different HTTP requests, including GET, POST, and others. Its motto is “HTTP for Humans” because it is simple and user-friendly.

Python’s Requests is the only non-GMO HTTP library currently on the market. Moreover, with Requests, there is no need to manually add query strings to your URLs or form-encode your POST data because it enables users to send HTTP/1.1 requests. In addition, it supports numerous features, including HTTP(S) proxy support, automatic decompression, automatic content decoding, SSL verification in the style of a browser, and much more. Requests runs on PyPy and formally supports Python 2.7, 3.4, and 3.7.

What is Selenium?

Top 7 Web Scraping Tools - Python For Data Scientists. A laptop showing the Selenium homepage.

Selenium Python is a free, web-based automation tool that offers a straightforward API for creating functional or acceptance tests with Selenium WebDriver. Selenium is essentially a collection of various software tools each of which uniquely supports test automation. And the entire toolkit produces a comprehensive set of testing functions tailored to the requirements of testing web applications and creating apps with Python.

Furthermore, a user can easily access all Selenium WebDriver functionalities with the help of the Selenium Python API.

What is Urllib?

Top 7 Web Scraping Tools - Python For Data Scientists. A laptop with urllib handling models page on it.

Open URL’s via urlib package in Python. Also, it includes several modules for working with URLs, including urllib.request for opening and reading HTTP URLs and urllib. The error module defines exception classes for exceptions raised by urllib.request, urllib.redirect, and urllib.redirect2. In components and urllib, the parse module defines a standard interface for breaking up Uniform Resource Locator (URL) strings. Furthermore, the RobotFileParser is a single class provided by robotparser that answers questions about whether or not a specific user agent can fetch a URL on the web page of a website that published the robots.txt file. It is a simple, easy-to-use Python library that can prove very powerful if you decide to use its true potential.

Are you ready to use the best Python web scraping tool?

Top 7 Web Scraping Tools - Python For Data Scientists. A laptop in the middle of downloading PyScripter.

In this tutorial we discussed the various Python open-source libraries for website data scraping. We hope you can now create scrapers ranging from simple to complex that can crawl an infinite number of web pages. And you can also delve deeper into these libraries to hone your web scraping skills. In today’s world, data is a critical component of decision-making, and knowing how to collect data will put you ahead of the competition.

One Pro Tip is to use a good IDE like Pyscripter when starting your web scraping journey. Because PyScripter has a modern UI; however, only the Microsoft Windows operating system. Although, it is available in a compiled language and has a wide range of capabilities, it is the ideal Python programming environment and is faster than many other IDEs.

Moreover, it includes many features, including brace highlighting, code folding, code completion, and syntax checking while you type, making it the best Python editor on the market. Additionally, Python source code tools make it easier for programmers to write code. Finally, a time-saving feature of PyScripter is the ability to drag and drop files from Explorer into this IDE.

This outstanding IDE aims to create a Python IDE that can compete with other languages’ traditional Windows-based IDEs. PyScripter is a top-notch program. It is lightweight, adaptable, and expandable, among other qualities.

This amazing IDE will make web scraping a lot more efficient for you. So, click here and kickstart your web scraping journey today!

What are the FAQs about Python web scraping tools?

What Are FAQs about Python Web Scraping Tools?

Is Python good for web scraping?

Python is widely considered one of the best languages for web scraping and many web scraping tools on the market are built using it.

How do you scrape a website in Python?

To extract data using a Python web scraper, you must first perform the following steps:

  1. Locate the URL you want to scrape
  2. Examining the Page
  3. Locate the information you want to extract
  4. Make the code
  5. Execute the code to obtain the data
  6. Save the data in the appropriate format

Which tool is best for web scraping?

Beautiful Soup is the best amongst all the Python libraries for web scraping.

Which is better, Scrapy or BeautifulSoup?

The performance of Scrapy can be said to be faster than Beautiful Soup due to the built-in support for generating feed exports in multiple formats and choosing and extracting data from various sources. In addition, the Multithreading method can make working with Beautiful Soup faster. But because Beautiful Soup has a better learning curve, more people use it.

Is it legal to scrape a website?

Scraping publicly accessible data is legal, so scraping publicly accessible web pages is also allowed.

The post Top 7 Web Scraping Tools – Python For Data Scientists first appeared on Python GUI.

]]>
https://pythongui.org/top-7-web-scraping-tools-python-for-data-scientists/feed/ 0 8339
How To Plot A Line Graph In Python https://pythongui.org/how-to-plot-a-line-graph-in-python/ https://pythongui.org/how-to-plot-a-line-graph-in-python/#respond Thu, 29 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8320 The line graph is very useful for visualizing continuously changing data. It helps you to compare how several things change over the years relative to each other. Hence, you can easily uncover key insights from...

The post How To Plot A Line Graph In Python first appeared on Python GUI.

]]>
The line graph is very useful for visualizing continuously changing data. It helps you to compare how several things change over the years relative to each other. Hence, you can easily uncover key insights from the dataset and make important decisions. To create a line graph, you will need the best Python charting library, like Matplotlib. Also, you need a user-friendly visualization tool. There are plenty of data visualization tools for Python. But which is truly the best option? In this tutorial, you will know how to plot a line graph in Python with the best data visualization tool on the market. Let’s dive in.

What is the best data visualization tool to create a graph in Python?

The best data visualization tool for plotting a line graph in Python is PyScripter. It is fast, powerful, and feature-rich. Also, PyScripter is very user-friendly. It allows you to easily install the required visualization libraries. Hence, you can use PyScripter to effortlessly create line charts.

How can I create a line chart or graph in Python with PyScripter?

You can plot a line graph in Python by using Matplotlib. It is one of the best Python data visualization libraries available online. PyScripter allows you to easily install it. Here are the steps:

How to install Matplotlib using PyScripter?

1. Go to Tools > Tools > Install packages with pip.

How To Plot A Line Graph In Python - how to install the right packages

2. Then enter matplotlib and click OK.

How To Plot A Line Graph In Python - installing Matplotlib

3. Next, matplotlib and other required libraries, including Numpy, will begin to install. The whole process takes just a few minutes. Once the installation is done, you can start using PyScripter to plot a line graph in Python.

How can I create a simple line plot or graph in Python?

1. First, you have to import matplotlib and numpy libraries.

import matplotlib.pyplot as plt
import numpy as np

2. Then you have to add this code:

x = np.linspace(-1, 1, 50)
print(x)
y = 2*x + 1

3. Finally, you can plot and display the line graph by using these lines:

plt.plot(x, y)
plt.show()

Overall, the code will look like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
print(x)
y = 2*x + 1

plt.plot(x, y)
plt.show()

4. Now, click on the green button to run the code. You will get this output:

How To Plot A Line Graph In Python - a line graph

How do I plot a line graph in Python with labels?

Labels are integral to any chart. They show the relationship between the axes and the data plots. The chart has an x label, y label, and title.

To plot a line graph in Python with labels, you have to follow these steps:

1. First, import matplotlib and numpy libraries.

import matplotlib.pyplot as plt
import numpy as np

2. Then you have to insert this code:

x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

3. Next, you can plot and display the line graph by using these lines:

plt.figure()
plt.plot(x, y1) 

4. Then you have to specify the label of the x-axis and y-axis. Also, you have to specify the title of the line chart.

plt.xlabel("I am x")
plt.ylabel("I am y")
plt.title("With Labels")

5. Finally, you can display the line graph.

plt.show()

Overall, the code will look like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

plt.figure()
plt.plot(x, y1)  

plt.xlabel("I am x")
plt.ylabel("I am y")
plt.title("With Labels")

plt.show()

Once you run the code, you will get this output:

How To Plot A Line Graph In Python another line graph

As you can see, the line graph has labels on both the x-axis and y-axis. Also, it has a title.

How can I create a curved line graph in Python?

You can use the plot() method to create different types of line charts. For example, you can utilize it to make a curved line. Here are the steps:

1. First, you have to import matplotlib and numpy libraries.

import matplotlib.pyplot as plt
import numpy as np

2. Then you have to add this code:

x = np.linspace(-1, 1, 50)
y = 2**x + 1

3. Finally, you can plot and display the line graph by using these lines:

plt.plot(x, y)  
plt.show()

Overall, the code will look like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
y = 2**x + 1

plt.plot(x, y)  
plt.show()

Now, run the code. You will see this output:

How To Plot A Line Graph In Python - a gentle parabolic line curve

How can I create multiple lines on a graph in Python?

With Python, you can easily plot more than one line. You just need to call additional plot(x,y) functions. Simply follow these steps:

1. First, import matplotlib and numpy libraries.

import matplotlib.pyplot as plt
import numpy as np

2. Then insert these lines:

x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

3. Finally, you can plot and display multiple lines by using this code:

plt.figure(num = 3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, 
         color='red',   
         linewidth=1.0,  
         linestyle='--' 
        )

plt.show()

Overall, the code will look like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

plt.figure(num = 3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, 
         color='red',   
         linewidth=1.0,  
         linestyle='--' 
        )

plt.show()

The output will look like this:

How To Plot A Line Graph In Python - a line graph with a straight dotted line and a solid curbed line

How can I create a dotted line graph in Python?

With Python, you can create lines in the form of dots. To do it, you have to utilize the scatter(x,y) method. Here are the steps:

1. First, you have to import matplotlib and numpy libraries.

import matplotlib.pyplot as plt
import numpy as np

2. Then you need to insert this code:

n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(X, Y)

3. Next, you have to call plt.scatter() method.

plt.scatter(np.arange(5), np.arange(5))

4. Finally, you can display the dotted line with this code:

plt.xticks(())
plt.yticks(())

plt.show()

Overall, the code will look like this:

import matplotlib.pyplot as plt
import numpy as np

n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(X, Y)

plt.scatter(np.arange(5), np.arange(5))

plt.xticks(())
plt.yticks(())

plt.show()

You will get this output:

How To Plot A Line Graph In Python. Dots

How can I create line ticks for my graph in Python?

With Python, you can easily change the ticks on the plot. You can set them on any axis. Also, you can change their color. Simply follow these steps:

1. First, import matplotlib and numpy libraries.

import matplotlib.pyplot as plt
import numpy as np

2. Then you need to add these lines:

x = np.linspace(-1, 1, 50)
y = 2*x - 1

plt.figure(figsize=(12, 8)) 
plt.plot(x, y, color='r', linewidth=10.0, alpha=0.5)

ax = plt.gca()

3. Next, you have to set the positions of spines and ticks. Also, you can set your preferred color.

ax.spines['right'].set_color('blue')
ax.spines['top'].set_color('red')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

4. Finally, you can show the line plot with ticks by using this code:

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='y', edgecolor='none', alpha=0.7))

plt.show()

Overall, the code will look like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
y = 2*x - 1

plt.figure(figsize=(12, 8)) 
plt.plot(x, y, color='r', linewidth=10.0, alpha=0.5)

ax = plt.gca()

ax.spines['right'].set_color('blue')
ax.spines['top'].set_color('red')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='y', edgecolor='none', alpha=0.7))

plt.show()

You will see this output:

How To Plot A Line Graph In Python - a different style of Python graph

As you can see, the line style looks different from the previous examples. Because you have specified your preferred line color.

Read: 6 Best Python GUI Frameworks

Should I use PyScripter in 2022?

PyScripter is a fast and powerful IDE. It offers several amazing features, including the syntax highlighting editor, integrated Python interpreter, and remote Python debugger. Also, PyScripter is very easy to use. It allows you to quickly install required libraries. Hence, you can effortlessly plot a line graph in Python with PyScripter. Besides, the IDE enables you to externally run Python scripts. It is highly configurable. Therefore, you should definitely consider using PyScripter in 2022 and beyond.

PyScripter is an open-source and feature-rich lightweight Python IDE. It offers several amazing features, including the remote Python debugger and integrated unit testing. Download PyScripter now for free.

FAQ about creating a graph in Python

How do I plot a line in Matplotlib?

You have to use the generic plot() function from the PyPlot instance to plot a line plot in Matplotlib. You can plot as many lines as you want. Simply add the points for the x-axis and y-axis for each line in the same plt. plot() function.

Can I plot a graph in Python?

Yes, you can plot graphs in Python. You have to use a data visualization library, such as Matplotlib, Seaborn, Bokeh, etc. Also, you need to utilize the best data visualization tool, like PyScripter.

Which method is used to generate a line chart or graph in Python?

To create a line chart in Python, you have to use the plot(x,y) method.


Do you want to create great-looking Python GUIs with the best FREE Python GUI frameworks and Python IDE? Click here to find out more about how to download Python tools to take your apps to the next level.

The post How To Plot A Line Graph In Python first appeared on Python GUI.

]]>
https://pythongui.org/how-to-plot-a-line-graph-in-python/feed/ 0 8320
10 Python Data Visualization Libraries To Win Over Your Insights https://pythongui.org/10-python-data-visualization-libraries-to-win-over-your-insights/ https://pythongui.org/10-python-data-visualization-libraries-to-win-over-your-insights/#respond Fri, 23 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8307 A decent Python GUI has a far more effective purpose than ‘just looking pretty’. For the average person, assuming they have no unmitigated visual disabilities, data is much more easily understood when it is presented...

The post 10 Python Data Visualization Libraries To Win Over Your Insights first appeared on Python GUI.

]]>
A decent Python GUI has a far more effective purpose than ‘just looking pretty’. For the average person, assuming they have no unmitigated visual disabilities, data is much more easily understood when it is presented in the form of a chart or graph. People wants the facts and figures to tell a story, to inform them. to enrich their knowledge and good visualizations help illustrate the elements and facilitate their comprehension. Data science often works with structured or unstructured data that can make human analysis difficult. Our understanding of the data is greatly enhanced by visualizations. Our brains are exceptionally good at detecting patterns and absorbing abstract information when it’s in the form of an image. We process graphically presented data much more quickly than text.

Why is it necessary to create data visualizations?

Python is the go-to language for data scientists, and there are plenty of options available for data analysis, including various data visualization libraries. Large data sets are cumbersome to go through by hand. Still, it is critical to verify that any missing data entries are corrected or excluded.

Visual analysis of entire datasets helps with getting a feeling for the task at hand, which is important for choosing the right data analysis model. Correct data is also very important in machine learning and data analytics since any deviation may lead to a poor model, and ultimately the whole project may fail.

10 Python Data Visualization Libraries To Win Over Your Insights - data visualizations example

What Python data visualization libraries are available?

In a recent post, we covered the top 5 graph tools for Python. There are plenty of practical examples to get you started with visual data analysis.

One of the first Python plotting libraries the newbie programmer meets is matplotlib. It is robust and has a variety of options for customization; however, it can be complicated. Creating data visualizations is made easier with modern Python packages such as

  1. matplotlib
  2. pandas
  3. seaborn
  4. Plotnine (ggplot)
  5. Plotly
  6. Bokeh
  7. Altair
  8. geoplotlib
  9. pygal
  10. Gleam

An important interactive data visualization designs are Jupyter notebooks. They provide the means of interacting with the plots created using many of the above Python libraries.

What kind of plotting methods are there?

The type of plot is determined by the type of data. Some data sets are best represented as bar charts or as scatter plots. In other cases, it is necessary to make error charts to see, for example, deviations or measurement errors. Other more specific cases require complex data visualizations, such as statistical analyses displayed on box charts and plots on geographical maps.

10 Python Data Visualization Libraries To Win Over Your Insights - a density distribution plot using Seaborn

How to visualize data with simple plots?

Nearly all python data visualization libraries are capable of creating simple plots of numerical data. Going to the next level is simple with some libraries than others. But most importantly, calling some Python libraries inside Jupyter notebooks makes it possible to generate interactive visualizations and even web apps.

What is matplotlib?

Matplotlib is the standard Python data visualization library, and there are countless examples online on how to present your data in a clear way.

Cons: matplotlib is old, and as such, it can be cumbersome at times. Sometimes seemingly simple things require plenty of coding or tweaking.

What is pandas?

Pandas runs a matplotlib-based engine to create plots, though the commands the user needs to enter are simplified. Most Python software engineers are familiar with pandas data structures. Still, any special additions that are present in matplotlib can be added to a pandas plot.

Cons: pandas can be slow with very large data sets.

What is seaborn?

Seaborn is a modern library that extends the functionality of matplotlib and pandas. There is a wide variety of plots to create with just a few lines of code.

Cons: None really.

Creating a scatter plot coloured by species only takes one line.

sns.set_style("whitegrid")
sns.scatterplot(data=iris, x = "sepal_length", y = "petal_length", hue = 'species')
plt.show()

Creating a histogram is equally simple.

sns.set_style("whitegrid")
iris["sepal_length"].plot(kind = "hist", label = "sepal_length")
iris["sepal_width"].plot(kind = "hist", label = "sepal_width")

plt.legend()
plt.show()
10 Python Data Visualization Libraries To Win Over Your Insights - a histogram using Python and Seaborn

What is Plotnine (ggplot)?

With its simple commands and easy integration with pandas data frames, plotnine (also known as ggplot among the users of the R programming language) is among the easy Python data visualization libraries to get started with. There is detailed documentation to get familiar with its features.

Cons: Plotnine lacks some complex features present in matplotlib-based packages. It takes a slightly different approach than other data visualization libraries when defining graphs. At first, this might be confusing to experienced data analysts.

What is Plotly?

Plotly is a hugely popular Python data visualization package. Excellent for interactive web applications due to its integration with the Javascript library with the same name. Plots are easy to share with others online.

Cons: Plots are displayed via the browser rather than the traditional way of defining a file name and exporting the picture. Also, pandas integration is not functioning as smoothly as with the previously mentioned Python libraries. This makes it suitable for smaller datasets but not really for creating statistical graphics, for example, in machine learning.

10 Python Data Visualization Libraries To Win Over Your Insights - a Plotly example

What is Bokeh?

Bokeh can create excellent dynamic and interactive graphs. Plots can be exported in various formats.

Cons: While it is easy to make data plots like a bar graph or a line chart, Bokeh still lacks the options to create advanced representations like using matplotlib-based libraries. The documentation could also be better.

What is Altair?

Even though Altair is not based on matplotlib, it can be easily used inside Jupyter notebooks and IDEs such as PyScripter. The plots it creates are actually JSON objects, and the output charts can actually be saved in HTML format.

Cons: It lacks some types of plots used in other common data visualization tools, though it generally handles routine plotting successfully.

What is geoplotlib?

Geoplotlib is a Python visualization library specifically meant for geographical data and creating maps. It can generate elegant interactive graphs using data from Open Street Map. For example, it is possible to plot population data by country or city as dot density maps.

Cons: It is not suitable for general-purpose plots and lacks data visualization components for line charts with a trend line or bar plots, for example, as it is specialised for plotting geographical data only.

Below is a plot obtained with the example code from the GitHub repository of geoplotlib called taxi.py. It plots data from taxis in China in animated form. Here, I am showing one of the frames.

10 Python Data Visualization Libraries To Win Over Your Insights - geoplotlib example over a map

What is Pygal?

Pygal is a Python charting library that can be used for interactive web-based data visualizations.

Cons: Compared to other libraries for data visualization in Python, Pygal can be a bit clumsy when using many data points.

What is Gleam?

Gleam is an excellent data visualization library for interactive web apps created by using only Python scripts.

Cons: Hardly any. It certainly deserves more attention.

How to create interactive data visualizations in Python?

Interactive plots can be among the best ways of displaying data since a better overview of the data set is achieved with just several mouse clicks. These plots are typically executed in a browser so that the user can drag sliders, zoom in and out, and more. Interactive web applications can be hosted on a server, so the end user does not have to know any programming to understand the data.

Interactive charts are also critical for real-time data analysis. It is highly impractical to have to re-run a Python script by hand just to see how the oncoming data looks like. Many Python libraries can be run inside a notebook with a few exceptions. Some of the above mentioned packages such as Plotly and Altair open the chart in a new browser window.

What is the best tool to write and test Python data visualizations?

There are many Python data visualization libraries to make data analysis easy, efficient and productive. We recommend looking for examples and trying them out to make sure that you find the tools that fit your needs best.

By far the best available tool for writing, debugging and testing Python code is PyScripter. PyScripter is super-fast and easy to use. It comes with advanced features like a unit test wizard which will generate tests for your code to ensure everything works as expected. The best part is it’s free!

You can start testing the examples in this post by downloading PyScripter now – an excellent IDE to suit the needs of software engineers working with Python.

The post 10 Python Data Visualization Libraries To Win Over Your Insights first appeared on Python GUI.

]]>
https://pythongui.org/10-python-data-visualization-libraries-to-win-over-your-insights/feed/ 0 8307
Top 6 Best Python Testing Frameworks [Updated 2022 List] https://pythongui.org/top-6-best-python-testing-frameworks-updated-2022-list/ https://pythongui.org/top-6-best-python-testing-frameworks-updated-2022-list/#respond Mon, 19 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8273 Python has really started to capture the imagination of developers worldwide in the past few years. It is steadily climbing the rankings and is presently third best, after Java and C, according to the Tiobe...

The post Top 6 Best Python Testing Frameworks [Updated 2022 List] first appeared on Python GUI.

]]>
Python has really started to capture the imagination of developers worldwide in the past few years. It is steadily climbing the rankings and is presently third best, after Java and C, according to the Tiobe index. The easy syntax of Python code along with the vast quantity of libraries available for almost any need has made it a very firm favorite for all sorts of development. But with that broad adoption comes the need for Python to be ready for serious, commercial code quality and the best way to ensure you use one of the Python testing frameworks to both validate the logic of your coding as well as trap the more difficult logic errors which can creep in.

Python’s adaptability makes it ideal for a wide range of commercial use cases, but testing your code is crucial before publishing any Python-based products to a wider arena. This post will discuss what we mean by formal Python testing and walk you through the top six Python testing tools. By the conclusion, you’ll be able to identify the ideal testing framework for your project.

What is automated testing using Python?

Top 6 Best Python Testing Frameworks [Updated 2022 List] A screen showing a a Python page

Automated testing is the practice of writing programs, scripts or macros which either test programs and apps externally as if a user was clicking or touching elements of the user interface and interacting with it; or it can be a series of specially written code units and projects which instantiate the program’s objects and methods in code and test that they behave and return results as expected, usually by providing test routines which supply a set of parameters or carry out actions to exercise the code and then return true or false to indicate whether the test passed or failed.

What is a unit test?

A unit test is a specially written set of one or more programs which create or instantiate a program’s objects and calls the programs methods in a controlled way purely to test that those objects and functions behave as expected. A unit test often returns true to indicate the test was successful and when these tests are gathered together into a project it is often referred to as a “unit test project”. Many automated CD/CI (continuous integration, continuous delivery) systems will not allow new code to be integrated unless there is a test project which has all the tests it contains ‘passing’ (returning true).

A unit test is not intended to be run by an end-user and is usually written with the most minimal set of functionality required to exercise the objects, methods or functions it is designed to test. Unit tests operate at the code level rather than at the user interface level.

What is an automated test script?

An automated test script might be a program designed to run a set of unit tests or it might be a set of instructions which drive the user interface of the application to attempt to automate the testing of the various controls and input or output.

Automated test scripts are available in several different programming languages, such as Python, C#, Ruby, Java, among others. However, because Python is more closely related to the English language it helps make it easier to learn to write test scripts in Python. Furthermore, unlike other programming languages, Python is an open-source language with an accessible syntax so the mechanics of how various concepts work are more simple to read and grasp than languages like C.

What are Python testing frameworks?

A Python testing framework is a set of functions and routines which help provide the capability to perform automated testing of programs and apps. The apps might not be written in Python although the tests are.

Every Python testing framework has advantages and disadvantages, but Python’s popularity means there is almost certainly something out there that will work for your business project.

You can read more about Python test automation here.

What are some high-performance Python testing frameworks for 2022?

Top 6 Best Python Testing Frameworks [Updated 2022 List] -  a person looming at a laptop screen displaying the Embarcadero Python tools

You should be familiar with the Python testing frameworks listed below.

What Is PyScripter and why is it the go-to tool for Python testing frameworks?

Many developers consider PyScripter to be one of the best Python IDEs. PyScripter is an editor with syntax highlighting, a Python interpreter, a debugger, a project coordinator, and more. However, PyScripter’s inherent capability for integrated unit testing is its most noteworthy feature. As a result, it has made a name for itself as one of the greatest Python testing tools for software development.

You may carry out automated unit testing thanks to PyScripter’s automatic test creation. The unit testing GUI that comes with the PyScripter IDE is excellent. Additionally, it provides a sophisticated graphical user interface for executing unit tests, a common Python module, in its unit tests window. For further details, consult the official documentation.

The two most important toolbar buttons on this window are Refresh and Run. 

Updating the unit test panel loads the PyScripter unit tests for the active module. It’s important to note that this necessitates importing the component into the built-in interpreter. Use the tree view to select the tests you wish to run after loading a module. You may access the testing methods or class definition in the source code by double-clicking on the name of a test or test class.

Run performs the chosen tests, making it easy to use. In the tree view, the color adjacent shows the test’s state following execution. For instance, the colors green and purple indicate success. The color red indicates a Python exception. The aggregate data are immediately below the tree view, and you can learn about the errors made by clicking on the failed tests.

Is Pytest a popular Python testing framework?

Undoubtedly one of the most popular Python testing frameworks available, Pytest is an open-source testing framework. Unit testing, functional testing, and API testing are all supported by Pytest. You will want Python 3.5 or later to run it.

What are the advantages of using Pytest?

Pytest allows for small and straightforward test suites. Secondly, utilizing plugins, such as pytest-randomly, pytest-cov, pytest-django, and pytest-bdd, is very expandable. Additionally, you may include the pytest html plugin in your project to easily produce HTML reports. You may use the Pytest plugin pytest-xdist to run tests concurrently. It possesses a sizable community. Pytest is a great approach to handling context between stages and supports fixtures, which assist you in covering all the parameter combinations without rewriting test cases.

What are the disadvantages of using Pytest?

Although Pytest makes it simple to create test cases, you won’t be able to use those in any other testing framework since Pytest uses its special techniques. Therefore, compatibility is not important for Pytest.

What Are Some High-Performance Frameworks for 2022? PyScripter
PyScripter has a unit test wizard to automate your use of Python testing frameworks

What Is TestProject?

An automation framework called TestProject is cost-free. It provides local and cloud HTML reports and simple test automation creation. It includes all necessary dependencies as elements of the single cross-platform client executable and supports the Pytest and Unittest frameworks.

What are the advantages of using TestProject?

TestProject is automatic and generates free reports in HTML and PDF format. TestProject’s RESTful API makes execution history easily accessible. Additionally, TestProject always uses the most recent Selenium/Appium driver releases. It provides a single SDK for testing on Android, iOS, the web, and other platforms and has built-in reporting and test runner features. TestProject is compatible with all operating systems across all platforms.

What are the disadvantages of using TestProject?

One of the biggest disadvantages is that TestProject cannot run simultaneous tests and can only do one test at a time, sequentially. Secondly, operating on-premises requires you to store tests on a shared network drive or git repository.

What Is Testify?

Testify is an automated Python testing framework.

What are the advantages of using Testify?

Testify is simple to use, offers a wide range of plugins for extra functionality, and allows for test discovery. Additionally, it has easy syntax.

What are the disadvantages of using Testify?

Implementing parallel testing with Testify is challenging. It also lacks thorough documentation therefore novices may need to take more time locating useful sources for examples and answers to any questions that might arise.

What Are Some High-Performance Frameworks for 2022? A unit test displayed in PyScripter

What Is PyUnit?

PyUnit is a unit testing framework often also known as Unittest, is used with JUnit. In addition, PyUnit is the built-in testing framework for Python and is delivered as a part of the Python packages by default. As a result, PyUnit is typically where developers begin their testing.

What are the advantages of using PyUnit?

PyUnit does not need extra modules installed as its creation is within the standard Python library. As a result, it provides rapid, clear, and straightforward test case execution. Additionally, it supports the rapid creation of test reports, including unittest-sml-reporting and XML reports.

What are the disadvantages of using PyUnit?

Test code supports abstraction. Thus, occasionally, the purpose might be ambiguous.

Is Behave a popular tool for test automation?

One of the most well-known Python BDD testing frameworks is Behave. It performs quite similarly to Cucumber frameworks despite not officially being part of the project.

What are the advantages of using Behave?

Behave enables the authoring test cases in understandable language, facilitating simple team cooperation across related features. A ton of informational material and support is available to get you going. It fully supports the Gherkin language. There is no need for technical experience to create feature files. Behave also has connectors for Flask and Django.

What are the disadvantages of using Behave?

Behave does not support execution in parallel and is exclusive to black box testing.

How can you use PyScripter as your Python testing framework?

PyScripter is an IDE that offers critical support for unit testing in addition to the frameworks above. There are two levels: GUI for unit testing and automatic test script creation.

Use the Unit Test Wizard option from the Tools menu to construct the fundamental structure of a test script for the first level, automated development of test scripts. First,examination of the active module’s source code takes place, and its methods and functions are shown. Next, you select(check) the functions and procedures you wish to build tests for and then hit OK. You will instantly receive a test script built on the unittest standard Python module. this creates a code for each test that you can write

To display the Unit Tests window for the second level, the GUI for unit testing, choose Unit Tests from the View Menu. you can also conduct unit tests using this window’s sophisticated user interface based on the unittest standard package for Python.

What are some of the frequently asked questions about Python testing frameworks?

Top 6 Best Python Testing Frameworks [Updated 2022 List] - an image of an avid student looking intensely at a laptop screen showing a Python unit test

Below are some of the commonly asked questions, along with their answers.

What is a Python testing framework?

Apply a collection of standards or rules called a testing framework while developing and creating test cases. A framework consists of a variety of procedures and routines intended to aid developers and QA specialists in conducting tests more quickly.

What types of testing are available in Python?

There are four main test kinds, each based on the level of code granularity and the test’s objective.

  • First is unit tests which validate the code’s unique logic and functions.
  • The second is feature tests which evaluate the component’s performance.
  • Then come integration tests.
  • Finally there are performance tests.

Which tool Is used for Python testing?

Unittest is the Python code testing tool provided by the standard library. The comprehensive testing tool pytest focuses on reducing boilerplate code and preserving backward compatibility. In addition, the unittest extension nose makes it simpler to write and test cases.

What type of framework is Pytest?

Pytest is undoubtedly one of the most popular Python testing frameworks available. It is an open-source testing framework. Unit testing, functional testing, and API testing are all supported by Pytest. You must have Python version 3.5 or later to use it.

Which is better, Pytest or Unittest?

Both frameworks are excellent for completing testing in Python, although pytest is simpler to use. Pytest’s code is clear, concise, and effective. We must import modules, make a class, and specify the testing functions for unittest in that class.

What are Selenium Python frameworks?

Based on the functional approach, there are three primary categories of Selenium frameworks: Framework based on data. Framework based on keywords. hybrid structure

Are you ready to start using some best Python testing frameworks?

Top 6 Best Python Testing Frameworks [Updated 2022 List] - a person about to download the free PyScripter IDE

The advantages of PyScripter over other Python testing tools make it the best. You should continue using PyScripter and its sophisticated capabilities as you gain more knowledge and your application develops.

Now that you know the importance of PyScripter and testing frameworks click here and download the best testing IDE!

The post Top 6 Best Python Testing Frameworks [Updated 2022 List] first appeared on Python GUI.

]]>
https://pythongui.org/top-6-best-python-testing-frameworks-updated-2022-list/feed/ 0 8273
PyGUI: The Simple Way To Create A GUI With Python https://pythongui.org/pygui-the-simple-way-to-create-a-gui-with-python/ https://pythongui.org/pygui-the-simple-way-to-create-a-gui-with-python/#respond Fri, 16 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8208 Designing a straightforward graphical user interface (GUI) compatible with various systems can be challenging. It need not be that way, though. Instead, you can design appealing user interfaces that you and your users will like,...

The post PyGUI: The Simple Way To Create A GUI With Python first appeared on Python GUI.

]]>
Designing a straightforward graphical user interface (GUI) compatible with various systems can be challenging. It need not be that way, though. Instead, you can design appealing user interfaces that you and your users will like, using Python and the PyGUI module!

It is crucial that there is no problem in the finished product that is provided to the customer. Performing certain types of tests as part of the development process is important to look for issues during software pre-release. This article will concentrate on using the best Python testing tools for developers and designing a GUI with Python.

What is a Python GUI?

PyGUI: The Simple Way To Create A GUI With Python Image of a discussion where a laptop is showing the PyScripter screen.

A GUI is the visual, graphical part of an app or program. The GUI is usually the part of a computer program where the user interacts with the functionality of the app using elements which appear to be buttons, edit controls and so on to make selections and trigger behavior. An app’s GUI also presents information-conveying and action-representative items such as graphs, images and fonts.

What is the importance of a GUI?

A development framework simplifies a developer’s job. If your app creates a poor first impression it can affect the user’s overall opinion of the app’s quality and prevent the application from becoming successful. An important part of that first impression if the GUI; if it looks attractive, modern and well designed then the user is pre-primed to believe that the underlaying functionality of the app is also likely to be well-designed too. You’ll use various graphical components, such as buttons, checkboxes, toggles, and dropdown menus to handle the user’s interactions and they should appear to be in harmony with each other. Random placement, tab orders, incorrect usage of well-known controls, or ugly widgets do not enhance your first impression as users are not able to interact with the applications functionality.

That first impression created by the elements of the GUI is your chance to ensure the user forms a positive opinion of your app.

The value of your program and its user experience is also strongly influenced by security and performance. Although you’ll want your program to be quick and secure, you don’t want to have to compromise your GUI to achieve these goals. A poor user GUI experience can quickly impact your user base if users can’t effectively interact with your program even if the app is well-written in every other aspect.

What is the importance of the GUI framework?

Development frameworks simplify a developer’s job. They facilitate the development of a specific type of application or the use of a specific language. For example, Python GUI frameworks simplify the process of creating a Python GUI instead of manually coding the user interface by hand in Python code.

How to create a GUI with Python?

PyGUI: The Simple Way To Create A GUI With Python. A laptop with the Delphi and Python tools download screen showing.

Identify your project: what project are you doing?

Deciding what the problem is – the “problem domain” – and the estimated output of the program — the endpoint and what you want to accomplish — is the first stage in creating a GUI application in Python. If you can properly address this question of the problem domain, refine what it is you actually want the app to achieve, it will direct you to the subsequent actions. One of the key elements of the widespread adoption of the Python language is it is easy to write Python code and there is a massive selection of libraries and frameworks available to address pretty much any possible need. Before you write any Python code you should take your understanding of the problem domain and what you want the app to achieve and see what frameworks and libraries are available that can help you reduce the amount of code you will need to write.

Is selecting the appropriate package to launch the GUI important?

When beginning a GUI using Python, the developer must next decide which GUI framework package to employ because there are numerous Python-based packages. Here is a list of Python packages with extremely dynamic interfaces that are arguably the best or most popular ones to use while beginning Python GUI programming.

What Is Tkinter?

On Windows, several Python editors use Tkinter. Python offers a quick and easy approach to creating GUI applications when used with Tkinter. Tkinter further provides a strong object-oriented interface for the Tk GUI toolkit.

Making a Python GUI application with Tkinter is a fairly simple operation. You must take the following actions to achieve this:

  • First, make the Tkinter module to your application by importing it into the app’s Python code.
  • Second, configure the GUI program’s primary window.
  • Third, incorporate one or more of the widgets mentioned above such as buttons and calendar pickers into the GUI program.
  • Finally, start the main activity loop to respond to each user-triggered event.

Tkinter has a lot of benefits. Thanks to its cross-platform library, the same program works on macOS, Windows, and Linux. Additionally, Tkinter creates programs that look like they belong to the architecture they are running on by using local OS components to produce visual elements.

Tkinter is a well-liked Python GUI framework, but it, too, has its share of issues. One notable criticism is that UIs made with Tkinter look outdated. If you want a modern, clean interface, Tkinter may not be precisely what you’re searching for. Tkinter also necessitates a lot of scripting, whereas other technologies allow users to design the UI for their Python projects visually. VCL and FMX from Delphi are two such libraries that are reinforced when used with RAD studio.

How can you update your GUI with PyQt?

Qt is a well-known cross-platform GUI framework created in C++ and owned by Nokia. PyQt is a Python UI framework for Qt. Windows, iOS, Linux, and Android are all supported by PyQT. Even so, desktop applications are where it is most frequently utilized. There are two editions of PyQT; PyQT4 and PyQT5, which is based on QT 5.x.

Before choosing PyQT you should examine the terms of the PyQT license. Distribution of both editions of PyQT under the GPL edition 3 license and are compatible with Python 2 and 3. Some functions are not accessible but the free version is available for testing. Additionally, PyQT is free to use if your developing program is open-source. PyQT has the best features of Python and QT.

What Is WxPython?

WxPython is an open-source framework that functions as a Python extension module and is sometimes referred to as WxWindows. WxPython features a slightly more up-to-date approach and introduces Python resources like the WxWidgets cross-platform Interface package.

What is DelphiFMX?

PyGUI: The Simple Way To Create A GUI With Python. The Delphi FMX and  DelphiVCL logos

DelphiFMX is a free super-charged Python GUI library which brings the power of Delphi’s FireMonkey FMX library into Python. FireMonkey (FMX) is Delphi’s cross-platform GUI library used by Delphi developers to create cross-platform apps which work on Windows, iOS, Android, macOS and Linux. It takes advantage of GPU hardware acceleration using OpenGL or DirectX to create slick, modern, and high-performance user interfaces. The DelphiFMX Python module supports Windows, macOS, Linux, and Android development with Python.

Python GUI Interfaces created with DelphiFMX look absolutely 100% modern and professional. The DelphiFMX and DelphiVCL frameworks integrate seamless with PyScripter and give Python developers the ability to really inject a huge level of quality into the user interface and user experience of their Python apps – contributing to the wow factor which, as we discussed earlier, is so important for the user’s first impressions of your app’s overall professionalism.

Why is PyScripter the best option for your GUI?

The MIT license applies to most of the features included in PyScripter, a free and open-source Python IDE. This program began as a straightforward IDE that offered a powerful scripting option for Delphi programs to go along with the great Python for Delphi (P4D) components. It has now developed into a fully functional stand-alone Python IDE with the help of Morgan Martinez, a P4D developer, and a few pioneer users. Thanks to its creation in Delphi using P4D and the SynEdit component we can also add Python scripts to Delphi programs to increase their functionality.

PyGUI: The Simple Way To Create A GUI With Python. The PyScripter screen.

PyScripter has a modern user interface but is currently limited to Microsoft Windows operating systems. The availability of various features and use of a secure and extremely fast compiled language makes it a good Python programming environment and faster than other Python IDEs.

This amazing Python script writer aims to offer a full Python IDE packed with helpful functionality that can rival other languages’ conventional Windows-based IDEs. PyScripter is an excellent application. With many truly useful, must-have features, it is portable, adaptable, and expandable. Being a native Windows app, rather than a script or interpreted app, makes it far faster and more responsive than other clumsy text editors, all-purpose IDEs, or other Python cross-platform IDEs.

What features are offered by PyScripter?

PyGUI: The Simple Way To Create A GUI With Python. What Features Are Offered by PyScripter? A person on the phone next to a laptop showing the PyScripter download screen.

PyScripter is the best IDE because it has functionality like code recommendations and a debugger. In addition, it offers advanced features, including integrated unit testing, syntax highlighting, and a built-in Python interpreter. As a result, many mistakes, bugs, and inconsistencies are found in your code and fixed early in developing an application especially if you use Python unit testing which is a breeze to set up with PyScripter. Furthermore, detailed documentation comes with the IDE, which really helps both new and experienced Python developers.

Due to its creation with a fully compiled language PyScripter is faster and very light on computer memory and resources compared to other Python IDEs. It has many fantastic features that make it an excellent Python programming experience and ensure that assistance is available when the code encounters difficulties.

To read more on creating a Python GUI along with some great video tutorials and videos – try this dynamic search link: https://pythongui.org/?s=python+gui

Go ahead and click here to download a totally free copy of PyScripter today, then follow some of the tutorials and get designing Python GUIs like a pro!

The post PyGUI: The Simple Way To Create A GUI With Python first appeared on Python GUI.

]]>
https://pythongui.org/pygui-the-simple-way-to-create-a-gui-with-python/feed/ 0 8208
Introduction To Python Data Visualization https://pythongui.org/introduction-to-python-data-visualization/ https://pythongui.org/introduction-to-python-data-visualization/#respond Wed, 14 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8227 Python data visualization gives you a wealth of benefits. It enables you to quickly understand complex relationships between data. As a result, you can easily identify patterns and trends. You can convey the information to...

The post Introduction To Python Data Visualization first appeared on Python GUI.

]]>
Python data visualization gives you a wealth of benefits. It enables you to quickly understand complex relationships between data. As a result, you can easily identify patterns and trends. You can convey the information to others through different charts and graphs. Also, Python data visualization tools help you to grasp complex data. More importantly, they enable you to effectively make strategic business decisions. That’s why you need to learn the way of visualizing the data with Python.

Python makes it very easy to represent complex information. It supports a variety of libraries to help you get the job done with just a few lines of code. In this post, you will find all the details.

What is data visualization in Python?

Data visualization in Python refers to the graphical representation of complex information through visual aids, like charts, plots, and infographics. It allows you to effectively visualize data relationships. Hence, you can easily uncover key insights. You can use the information to make data-driven decisions and grow your business.

How can you perform Python data visualization?

Python offers several graphing libraries to help you effortlessly visualize data. The most popular ones are:

  • Matplotlib: A comprehensive library for creating interactive visualizations in Python
  • Pandas: A Python library used for analyzing data.
  • Seaborn: A data visualization library built on top of matplotlib
  • Plotnine: An implementation of a grammar of graphics in Python, based on ggplot2.
  • Plotly: An open-source plotting library that supports over 40 unique chart types

In this tutorial, we will use Matplotlib, Pandas, and Seaborn to create basic data visualizations in Python. Let’s get started.

Read: Why Is Python Best for Programming Data Visualization?

What are the prerequisites for Python data visualizations?

  • Python: You need to have it installed on your PC.
  • Jupyter Notebook: Install the latest version on your PC.

Which datasets do I need for Python data visualization?

The very first step is to download the required datasets. In this tutorial, we will be using two different datasets: Iris [1] and Wine Reviews [2]. They are available for free download.

Once you are done with the download, put the two files in the root folder of your project. The file structure will look like this:

Introduction To Python Data Visualization - the file structure of the app

Then you have to create a new file, called “Introduction-to-Data-Visualization-with-Python-Ehsanul,” in the same folder.

Introduction To Python Data Visualization - create a new file

Now, open the file with a double-click.

How can I import the required libraries for Python data visualization?

The second step is to import the required libraries. We will use Matplotlib, Pandas, Pylab, and Numpy. You can import them by using these lines:

import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline

How can I read the datasets for Python data visualization?

Next, let’s read the datasets that we have downloaded in the first step. Let’s get started with the iris.csv file. Use this line to read the first five rows of sepal_length, sepal_width, petal_length, petal_width, and class columns.

iris = pd.read_csv('iris.csv', names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class'])
print(iris.head())

The output will look like this:

Introduction To Python Data Visualization - the output will look like this.

Next, let’s read the winemag-data-130k-v2.csv file. Use this line to read the first five rows.

wine_reviews = pd.read_csv('winemag-data-130k-v2.csv', index_col=0)
wine_reviews.head()

The output will look like this:

Introduction To Python Data Visualization. A finished visualization.

Now, you are completely ready for creating data visualization with Python.

Read: 10 Resources That’ll Make You Better At Python Programming Software

How can I create Python data visualization with Matplotlib?

You can use Maplotlib to build beautiful data visualization. Let’s create a scatter plot, a line chart, and a bar chart.

How can I create the scatter plot?

1. First, you have to create a figure and axis.

fig, ax = plt.subplots()

2. Then you can scatter the sepal_length against the sepal_width with this line.

ax.scatter(iris['sepal_length'], iris['sepal_width'])

3. Next, you have to set the title and labels with this code:

ax.set_title('Iris Dataset')
ax.set_xlabel('sepal_length')
ax.set_ylabel('sepal_width')

You will see this output:

Introduction To Python Data Visualization - a scatter plot

4. Finally, let’s make the graph meaningful by adding three different colors to the three classes. You will use red for Iris-setosa, green for Iris-versicolor, and blue for Iris-virginica. Add this code:

# create a color dictionary
colors = {'Iris-setosa':'r', 'Iris-versicolor':'g', 'Iris-virginica':'b'}
# create a figure and axis
fig, ax = plt.subplots()
# plot each data-point
for i in range(len(iris['sepal_length'])):
    ax.scatter(iris['sepal_length'][i], iris['sepal_width'][i],color=colors[iris['class'][i]])
# set a title and labels
ax.set_title('Iris Dataset')
ax.set_xlabel('sepal_length')
ax.set_ylabel('sepal_width')

You will see this output:

Introduction To Python Data Visualization - another scatter plot

How can I create a line chart?

Creating a line chart is very simple. You need to utilize the plt() method. Here are the steps:

1. First, you need to get columns to plot.

columns = iris.columns.drop(['class'])

2. Then you have to create x_data.

x_data = range(0, iris.shape[0])

3. Next, you need to create the figure and axis.

fig, ax = plt.subplots()

4. Then you can plot each column with this code:

for column in columns:
    ax.plot(x_data, iris[column])

5. Finally, you need to set the title and legend with this line:

ax.set_title('Iris Dataset')
ax.legend()

The output will look like this:

Introduction To Python Data Visualization - showing the visualization and code.

How can I create a bar chart?

You can create a bar chart by utilizing the bar method. Here are the steps:

1. First, you have to create a figure and axis.

fig, ax = plt.subplots()

2. Then you have to count the occurrence of each class with this line:

data = wine_reviews['points'].value_counts()

3. Next, you have to get x and y data

points = data.index
frequency = data.values

4. Then you can create the bar chart by passing points and frequency into ax.bar() method.

ax.bar(points, frequency)

5. Finally, you have to set the title and labels.

ax.set_title('Wine Review Scores')
ax.set_xlabel('Points')
ax.set_ylabel('Frequency')

You will see this output:

Introduction To Python Data Visualization - a bar chart

How can I create Python data visualization with Seaborn?

Seaborn is another popular visualization library. It is built on top of Matplotlib. Let’s use it to create a histogram and a line chart.

How can I import Seaborn?

You can import Seaborn with this line:

import seaborn as sns

How can I create a histogram with Seaborn?

You just need to use this code to create the histogram:

sns.distplot(wine_reviews['points'], bins=10, kde=False)

You will get this output:

Introduction To Python Data Visualization a histogram

How can I create a line chart with Seaborn?

Simply use this line:

sns.lineplot(data=iris.drop(['class'], axis=1))

You will get this output:

Introduction To Python Data Visualization - the output of the combined visualizations

Read: How To Use Data Visualization Tools In Python

Should I use Python for data visualization?

Python is one of the most popular languages on the planet. It is open-source. Hence, you don’t have to spend any money to use its features and libraries. Also, you can easily connect Python to any database system. Therefore, you get flexibility. On top of that, Python is highly scalable. It can be very useful for handling and representing large amounts of data. That’s why you should strongly consider using Python for data visualization.

Does PyScripter support Jupyter Notebook?

PyScripter supports Jupyter Notebook. However, you need to install “jupiter” using “pip” on your PC. Once the installation is done, you can start using notebooks on PyScripter.

PyScripter is a powerful Python programming tool. It offers several amazing features, including the remote engine and debugger. Try it now for free.

FAQ for Python Data Visualization

Which data visualization tool is best for python?

The best Python data visualization tool is Matplotlib. It is a comprehensive library for conveniently creating static, dynamic, and interactive visualizations. Matplotlib was released in 2003. Right now, it is the most popular Python plotting library on the planet.

What is meant by data visualization in Python?

Data visualization in Python refers to the practice of representing complex data in visual formats, like charts, graphs, maps, etc. It enables you to quickly comprehend key insights and effectively make important business decisions. Python offers several amazing data visualization libraries. The most popular ones are Matplotlib, Seaborn, and Pandas.

How do you visualize big data in python?

You can visualize big data in Python using different libraries, including Panda and Matlotlib. They are very easy to use. They require you to write a few lines of code to visualize complex data. As a result, you can boost your efficiency and workflow.

Is Python good for data visualization?

Python is the best programming language for visualizing data. It offers powerful graphing packages, like Matplotlib, Panda, Seaborn, etc. They enable you to effortlessly visualize complex data with just a few lines of code.

Which Python library is used for data visualization?

You can use a variety of libraries for visualizing data in Python, including Matplotlib, Seaborn, Pandas, Plotly, and Plotnine.

[1] https://archive.ics.uci.edu/ml/datasets/iris

[2] https://www.kaggle.com/datasets/zynicide/wine-reviews

The post Introduction To Python Data Visualization first appeared on Python GUI.

]]>
https://pythongui.org/introduction-to-python-data-visualization/feed/ 0 8227
What Is the Best Free Python Compiler for Windows? https://pythongui.org/what-is-the-best-free-python-compiler-for-windows/ https://pythongui.org/what-is-the-best-free-python-compiler-for-windows/#respond Mon, 12 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=7716 Python is a powerful programming language that can run in several settings. PyScripter, PyDev, Jupyter Notebook, and many others are among the free Python compiler for Windows available for executing Python applications. PyScripter is an...

The post What Is the Best Free Python Compiler for Windows? first appeared on Python GUI.

]]>
Python is a powerful programming language that can run in several settings. PyScripter, PyDev, Jupyter Notebook, and many others are among the free Python compiler for Windows available for executing Python applications.

PyScripter is an open-source, free Python compiler with various features licensed under the MIT license. Kiriakos Vlahos created PyScripter, and the project’s SourceForge page has seen over 1.2 million downloads since 2015. This article will look at the best free Python compiler available for windows.

What Is a Python compiler?

What is a Python compiler

A compiler is computer software that converts compiled code in one programming language into another. Python is the fastest-growing programming language in the world. As a result, many Python compilers can accommodate a wide range of project requirements.

Compilers transform source code written in a high-level programming language to a lower-level programming language, such as assembly language, to create an executable program.

What Is the importance of using a Python compiler?

Python is a high-level programming language. We can comprehend the Python code we write, but machines cannot. Therefore, we must convert our Python code into machine language, which a computer can understand. To do this, we constructed a Compiler software to convert our source code into executable code.

Compilers usually translate straight to machine language for languages like C++, but for languages like Java and Python, compilers convert to byte code, an intermediate language. After that, we utilize an interpreter to convert the byte code into machine language. Python is known as an Interpreted language because of this. Python is known as an Interpreted language because of this. Without compilers, the code we write would never run and remain unexecuted.

What to expect from the best free Python compiler for Windows?

What to Expect From the Best Free Python Compiler for Windows

A good python compiler has several features which make it easy for the user to write and debug his code. PyScripter is a powerful compiler with a debugger and a host of sophisticated features such as code recommendations and source control integration. In addition, it is significantly quicker than other Python script writers. It also offers many other features that make it a great Python development environment.

PyScripter has a syntax highlighting feature. Syntax highlighting uses colors and fonts to distinguish language sections in programming languages and other organized files. It allows you to understand what each part of the statement or command does; for example, you can see what section of the statement or command is a function and what portion is a variable like a string.

In addition, the integrated python debugging makes it easy for the programmers to debug the code interactively. Inspect stack frames, view source code, and run any Python function from within any stack frame. Software developers can use debugging to repair bugs before releasing a program to the general audience. Python debugging tools are necessary for Python programming since they aid in identifying excellent and bad Python programming software.

PyScripter includes a Python interpreter that allows users to run Python code without saving it and provides code completion.

What add-ons make PyScripter special?

PyScripter provides Source Control Integration. A collection of methods for storing and syncing source code files in a repository and among developers is known as source control. Source control allows you to track changes to source files and version them. It also allows large groups to work on duplicate files simultaneously, with changesets automatically merged.

External Tools are defined in PyScripter and can work alone or in conjunction with the compiler. PyScripter may be smoothly integrated with your favorite Python tools or command-line programs if you choose tools with a lot of flexibility. You may define or alter external tools using the “Tools|Configure Tools..” menu item. The PyScritper.ini file stores the tool definitions. PyScripter includes external tools such as PyLint, TabNanny, Profile, and others.

PyScripter has a powerful auto-complete feature as well as automatic code formatting. Autocomplete tools are handy since they allow individuals to complete code more quickly while reducing errors. When working on a Python project, using a compiler with code autocomplete may make things much more manageable. Basic code completion helps you fill in the names of classes, methods, and keywords inside the visible scope. When you call code completion, PyScripter analyses the context and gives alternatives accessible from the current point.

What makes PyScripter the best free Python compiler for Windows?

PyScripter began as a lightweight compiler to offer a reliable programming option for Delphi applications that would complement the excellent Python for Delphi (P4D) components. It has now matured into a full-featured stand-alone Python compiler, thanks to the support of P4D developer Morgan Martinez and a few early users. It’s written in Delphi with P4D and the SynEdit component, but Python scripts may be used to extend it.

It has a modern user interface and is currently only available for Microsoft Windows operating systems. As it is written in a compiled language, it is faster than other compilers and offers a diverse range of attributes that make it a productive Python development environment.

Python is a powerful programming language that can be used to develop a range of applications, as seen by the rise of analysts and data scientists. As a result, Python’s popularity has increased. Furthermore, a good Python compiler makes managing your code development a breeze. To read more about Python, click here.

PyScripter is the greatest compiler since it comes with a debugger and many advanced features like code suggestions. In addition, it has several additional features that make it an excellent Python programming environment. Overall, PyScripter is the best package since it has more functionality than any other compiler.

PyScripter aspires to build a Python IDE that can compete with commercial Windows-based IDEs for other languages. It is an excellent, feature-rich, lightweight, adaptable, and expandable tool. Moreover, it’s significantly faster and more responsive on Windows than bulky text editors, general-purpose compilers, or other Python cross-platform IDEs since it was created from the bottom up for Windows.
You must be pretty excited to test out all of the features mentioned above. So click here to begin coding in the world’s most popular python coding language.

The post What Is the Best Free Python Compiler for Windows? first appeared on Python GUI.

]]>
https://pythongui.org/what-is-the-best-free-python-compiler-for-windows/feed/ 0 7716
Top 10 Python IDEs in 2022? How to Choose The Best One https://pythongui.org/top-10-python-ides-in-2022-how-to-choose-the-best-one/ https://pythongui.org/top-10-python-ides-in-2022-how-to-choose-the-best-one/#respond Fri, 09 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8052 Every Python developer should use the right tools to make good use of their time. Here I will go through the contenders for the top 10 Python IDEs and editors, and we will focus on...

The post Top 10 Python IDEs in 2022? How to Choose The Best One first appeared on Python GUI.

]]>
Every Python developer should use the right tools to make good use of their time. Here I will go through the contenders for the top 10 Python IDEs and editors, and we will focus on the free ones available for Windows. I will highlight the most important features to look for, but I can’t help revealing my personal favorite, PyScripter.

Click here to download PyScripter for free.

What free Python IDEs and editors are available for Windows?

Python editors are available for all operating systems. Many of them are even platform-independent. Code can be written in a plain text editor (Notepad, Notepad++, vim, nano, emacs, etc), but it is recommended to use an integrated development environment (IDE).

Below is a list of the top 10 most popular IDEs.

  1. PyScripter
  2. Atom
  3. PyCharm
  4. Sublime Text
  5. Visual Studio Code
  6. Idle
  7. Spyder
  8. Thonny
  9. Online Python compilers
  10. Jupyter

What is an integrated development environment?

As the name says, an IDE is a software which includes a code editor, a compiler, often an interpreter and a debugger. Some IDEs come with package managers, collaborative tools and more so that the whole process of code development can happen within the same environment. This saves time and effort for programmers since all the needed tools are available within the same program.

Why use Python IDEs?

Text editors are the minimum needed to write code, but they are clumsy. If you were to use, e.g., Notepad under Windows, you have to edit the code, save it, and then call Python separately in a shell to execute the code. An IDE can provide a number of features that are helpful for software development. These include code completion, syntax highlighting, error checking, and project management tools.

Are Python IDEs essential in 2022?

There is no readily available text editor within the Windows command prompt. Linux and Mac users can benefit from the ability to run a shell and execute commands from inside vim or emacs, for example, just by defining a shortcut key. Still, it is much more efficient to have all needed tools available within the same software. Not to mention that when Python projects are split into multiple source-code files, it becomes painful to open and close them all the time. Why fight with the tools instead of tackling your tasks?

What are the must-have features of Python IDEs?

  • File navigator

As soon as a coding project is split into multiple files (which is recommended!), it becomes necessary to be able to easily switch between different files.

  • Syntax highlighting

Code readability is the single most important coding practice. You might be a brilliant mind, but if your code is messy, you will be lost in your own ideas eventually. Many Python editors employ a colour scheme to designate different parts of the programming language in different colours. This makes it easier to see the structure of the code.

  • Code completion

It is always worth using long and descriptive names for functions and variables. It helps massively with code readability. Good Python editors can help you by providing suggestions based on what code you are typing.

  • Spell checking

Everybody makes mistakes and typos. Some IDEs can detect and highlight obvious typos before you even execute the code. This includes also counting the number of opened and closed brackets. Python editors should also check whether code indentation is correct. (Remember that the IDE is not a mind reader, you know your algorithm best, and you may introduce a bug due to wrong indentation.)

What to watch out for when using Python IDEs?

Some IDEs are rich in features but they try to be a jack-of-all-trades. They are bloated with tools you will probably never use. This is draining your resources, and the IDE is acting sluggishly.

We reviewed the popular Python IDEs more than a year ago. Not much has changed since then around the big names.

The top 10 Python IDEs and editors

Let’s go through all of the top 10 Python IDEs quickly. I will skip the text editors. They are self-explanatory.

PyScripter

As I said in the beginning, my personal favourite is PyScripter. I love its flexibility, the ease of use, but most of all, the fact that it is Python-specific and does not drain memory. It only needs 50 MB of RAM to run my small project!

Top 10 Python IDEs in 2022? How to Choose The Best One. The Task Manager View showing PyScripter

PyScripter makes it possible to install packages without leaving the IDE. That is a huge plus for me. It calls pip behind the scenes and installs the package for the correct Python version. If you have tried doing that by hand, you know how painful it can be.

Atom

We recently reviewed Atom and compared it to PyScripter. Although they share many features, Atom is a multipurpose IDE, not Python-specific. I have heard plenty of positive experiences about Atom, but I have to admit that I had to fight with it to even install it on my computer.

PyCharm

PyCharm is another professional Python-specific editor available for Windows, Linux and Mac. It offers all the necessary features; however, it is free only for academic purposes and open-source projects. For-profit project members need to obtain a licence.

Visual Studio Code

I have many co-workers using Visual Studio Code in their projects, though I never fell in love with it. VS Code is highly customisable and, I would say, more suitable for people who work on various projects involving different programming languages. One upside of it is that it can run Python notebooks. More on them later.

Sublime Text

Sublime text offers all necessary features a Python coder needs and is cross-platform, though it is free only for evaluation. Creating real-life projects requires a paid licence.

Idle

Idle is a primitive Python code editor that only offers some basic features. It is, in fact, itself written in Python. It runs a Python interpreter, highlights the syntax and offers some debugging options.

Spyder

Spyder is an all-around, fairly simplistic Python IDE which can employ an existing Anaconda installation and has an iPython interactive shell, though it also lacks advanced features needed for efficient coding.

Thonny

Thonny is a basic Python-only IDE with a simple interface and limited features. There is a Python interpreter and an output Window. There are no advanced features such as version control or unit testing.

Online Python compilers

Python code can be executed on some servers for free. They tend to be really basic and are not recommended for large programming projects.

Jupyter

Before I learned about PyScripter, I was swearing by Jupyter notebooks. They are nice and handy, but the Jupyter environment is clumsy and sluggish. Load a big dataset, and your browser can even freeze.

Summary

There are some basic Python IDEs and code editors which can restrict your workflow. Our list of the top 10 Python IDEs and code editors shows some of the choices for feature-rich options to suit all your needs.

Do you already use any of our top 10 Python IDEs? Do you have a favorite Python editor? Why not download PyScripter today and see the advantages and improvement in coding efficiency you gain from using this great, feature-packed free Python IDE?

The post Top 10 Python IDEs in 2022? How to Choose The Best One first appeared on Python GUI.

]]>
https://pythongui.org/top-10-python-ides-in-2022-how-to-choose-the-best-one/feed/ 0 8052
Top 10 Fun And Easy Python Projects For Beginners In 2022 https://pythongui.org/top-10-fun-and-easy-python-projects-for-beginners-in-2022/ https://pythongui.org/top-10-fun-and-easy-python-projects-for-beginners-in-2022/#respond Wed, 07 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8039 Python today is one of the most widely used programming languages, and it appears that this trend will stretch way past 2022 and beyond. Therefore, working on some existing Python project ideas is the finest...

The post Top 10 Fun And Easy Python Projects For Beginners In 2022 first appeared on Python GUI.

]]>
Python today is one of the most widely used programming languages, and it appears that this trend will stretch way past 2022 and beyond. Therefore, working on some existing Python project ideas is the finest thing you can do if you are just learning Python. A hands-on approach is helps augment academic knowledge and prepare you for the real-world workplace with practical experience. In this post, we’ll look at a few enjoyable and easy Python projects that beginners can use to practice their programming skills using the best Python editor for Windows.

What are some interesting Python projects for beginners?

Project-based learning enhances student learning. Working on their projects is a requirement for ambitious developers when it comes to jobs in software development. Developing real-world projects is the best method to sharpen your abilities and translate your academic knowledge into practical experience.

How to create a number guessing game in Python? 

This project is a fun game where the user must predict the generated random number within a given range after being given hints. Users are prompted with further suggestions to help them out each time their estimate is incorrect (at the cost of reducing the score).

The application also has functions determining whether the user entered a number and the discrepancy between two numbers.

For a number guessing project, we will need to implement the following:

  1. Take user input for a random number’s upper and lower bounds.
  2. Ask the user to guess a random number between the range.
    1. If the guess is above the number, tell the user that the number is higher.
    2. Tell the user the number is lower if the guess is below the number.
    3. If the guess is the same as the number, end the game.
  3. End if number of guesses exceeds a certain count, otherwise loop back to 2.
import random
import math
# Taking Inputs
lower = int(input("Enter Lower bound:- "))

# Taking Inputs
upper = int(input("Enter Upper bound:- "))

# generating random number between
# the lower and upper
x = random.randint(lower, upper)
print("ntYou've only ",
	round(math.log(upper - lower + 1, 2)),
	" chances to guess the integer!n")

# Initializing the number of guesses.
count = 0

# for calculation of minimum number of
# guesses depends upon range
while count < math.log(upper - lower + 1, 2):
	count += 1

	# taking guessing number as input
	guess = int(input("Guess the number:- "))

	# Condition testing
	if x == guess:
            if count == 1:
                  print("Congratulations you did it in a single try!")                      
            else:
		      print("Congratulations you did it in ",
			      count, " tries")
		# Once guessed, loop will break
		break
	elif x > guess:
		print("You guessed too small!")
	elif x < guess:
		print("You Guessed too high!")

# If Guessing is more than required guesses,
# shows this output.
if count >= math.log(upper - lower + 1, 2):
	print("nThe number is %d" % x)
	print("tBetter Luck Next time!")

How can you make a rock paper scissors project in Python?

This program uses a variety of Python functions to create the gameplay so it’s an excellent opportunity to become familiar with that crucial idea.

Before making a move, the program waits for the user to take action. A string or alphabet representing rock, paper, or scissors could be used as the input. After evaluating the input string, the result function determines the winner, while the scorekeeper function updates the round’s score.

To implement a number guessing game, we need an algorithm. We can implement the project in the following way:

  1. Input a user action (rock, paper, or scissor).
  2. Generate a random action, i.e., rock, paper, or scissors.
  3. Use the rules of rock, paper, and scissors to determine which player is the winner.
  4. Output the result.

Using the above algorithm, here is what the code looks like:

import random

# Inputting user action
user_action = input("Enter a choice (rock, paper, scissors): ")

# Generating Computer action using the possible choices.
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"nYou chose {user_action}, computer chose {computer_action}.n")


# Using the general rules of Rock, Paper, Scissor to determine the 
# winner.
if user_action == computer_action:
    print(f"Both players selected {user_action}. It's a tie!")
elif user_action == "rock":
    if computer_action == "scissors":
        print("Rock smashes scissors! You win!")
    else:
        print("Paper covers rock! You lose.")
elif user_action == "paper":
    if computer_action == "rock":
        print("Paper covers rock! You win!")
    else:
        print("Scissors cuts paper! You lose.")
elif user_action == "scissors":
    if computer_action == "paper":
        print("Scissors cuts paper! You win!")
    else:
        print("Rock smashes scissors! You lose.")

How does a dice roll generator work in Python?

The Dice Roll generator generates random numbers and uses the random function to simulate rolling dice. The polyhedral dice used in many boards and role-playing games can be replicated by changing the maximum value to any number.

You can use this dice roll generator to play games like ludo, snakes and ladders, and much more! 

This project is simple to implement, but we can take it further and keep rolling the dice until the user says “No.” Here is what the algorithm looks like

  1. Input the minimum and maximum ranges from the user (these are the values the dice will randomly take.
  2. Input the number of dice rolls the user wants on each try.
  3. Generate and output the values from the dice roll.
  4. Ask the user if he wants to continue.
    1. If continues, loop back to 3.
    2. Else end the program

Here is what this simple program looks like:

import random

# Enter the mini and max integer limits of the dice rolls below
# 1 is added to the maximum value as it is not included in the range

min = int(input("Enter minimum value"))
max = int(input("Enter maximum value")) + 1

# Store the user's decision
roll = "yes"

while roll == "yes":

    print("Dice rolling...")
    print("Dice values are :")

    # Printing the randomly generated variable of the dice 1
    print(random.randint(min, max))

    # Prompt user enters yes to continue 
    # Any other input ends the program
    roll = input("Do you want to roll the dice again?")

Is it easy to make a a calculator in Python?

Yes, it’s among the simpler projects. You can learn how to create a graphical user interface using this project, which is also a fantastic way to get to know a library like Tkinter. With the help of this library, you can design buttons that execute various tasks and show the results on the screen. 

For our simple calculator, we will implement basic arithmetic functions: addition, subtraction, multiplication, and division. This simple terminal-based calculator will be using simple Python inputs in the terminal. The algorithm will look like this:

  1. Ask the user whether he wants to Add, Subtract, Multiply, or Divide.
  2. Ask the user for two numbers on which to perform the arithmetic operations.
  3. Output the generated new number onto the terminal screen.

Here is what our program looks like:

# Function for addition of two numbers
def add(x, y):
    return x + y

# Function for subtraction of two numbers
def subtract(x, y):
    return x - y

# Function for multiplication of two numbers
def multiply(x, y):
    return x * y

# Function for division of two numbers
def divide(x, y):
    return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
    # Take a choice input from the user
    choice = input("Enter choice of what to do(1/2/3/4): ")

    # Check the choice against the listed operations
    if choice in ('1', '2', '3', '4'):
        number1 = float(input("Enter first number: "))
        number2 = float(input("Enter second number: "))

        if choice == '1':
            print(number1, "+", number2, "=", add(number1, number2))

        elif choice == '2':
            print(number1, "-", number2, "=", subtract(number1, number2))

        elif choice == '3':
            print(number1, "*", number2, "=", multiply(number1, number2))

        elif choice == '4':
            print(number1, "/", number2, "=", divide(number1, number2))
        
        # Asking if user wants to do another calculation
        next = input("Do you want to do another calculation? (yes/no): ")
        if next == "no":
          break
    
    else:
        print("Invalid Input")

Note that we have created several helper functions for the individual arithmetic functions. You can do these in line with the print statements, but we chose to do it this way to enhance code readability and make the tutorial easier to follow.

How can you create a countdown timer in Python?  

A countdown timer does as its anime suggests. It counts down from the inputted number of seconds until it shows a message. It uses the time module, which is important to understand, and a relatively simple module to construct.

To make a simple countdown timer, we will use Python’s time module. The time module’s sleep method allows us to control the sleep time of our loops. We can construct an algorithm as follows:

  1. Input the countdown time from the user.
  2. Decrement from the input time every second until the time reaches zero. Output at every decrement.

Here is what our final code looks like.

import time

def countdown(t):
    # Looping through the time until time reaches 0
    while t != 0:
        # Displaying the minutes and seconds remaining
        min, sec = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(min, sec)
        print(timer)
        print(“n”)
        # Sleeping for 1 second before decrementing the time
        time.sleep(1)
        t -= 1

    # Printing that the countdown has come to an end
    print('Countdown over!')

# Prompt user to enter the countdown time
t = input("Enter the countdown time in seconds: ")


# Calling the function to start counting down the time
countdown(int(t))

What is the Mad Libs generator Python project?

Given that it uses strings, variables, and concatenation, this Python starter project is a nice place to start for newcomers. The input data that the Mad Libs Generator manipulates could be an adjective, a pronoun, or a verb. After receiving input, the program organizes the facts to create a story. If you’re new to coding, you should try this awesome Python project. 

Mad Libs is a fun and easy project that even a novice can do. It is essentially a hard-coded program where you can design your own story, so you can design your own story and implement it as a code. However, some basic functionality remains the same for every Mad Libs project:

  1. Design a story that you want to tell with blank spaces.
  2. Ask the user to input answers based on a list of customized questions.
  3. Add the user inputs to your story and output.

Here is a sample code for a story:

loop = 1

while (loop < 10):

    # List of all questions that the program asks the user
    noun = input("Type a noun: ")
    p_noun = input("Type a plural noun: ")
    noun2 = input("Type another noun: ")
    place = input("Name a place: ")
    adjective = input("Type an adjective: ")
    noun3 = input("Type a third noun: ")

    # Display story created based on the users input
    print ("Be kind to your", noun, "-handed", p_noun)
    print ("For a dog may be somebody's", noun2,",")
    print ("Be kind to your", p_noun, "in", place)
    print ("Where the mood is always", adjective,".n")
    print ("You may think whether this is the",noun3,",")
    print ("Well it is!")

    # Loop back to "loop = 1"
    loop = loop + 1

How can you create a Hangman game in Python?

Hangman is more like a guess-the-word game. While creating this project, you must employ the following fundamental concepts: variables, random, integer, strings, char, input and output, and boolean. Users must submit letter guesses in the game, and each user is given a set number of guesses (a counter variable is needed for limiting the guesses). Hangman is one of the most strongly advised projects for beginners learning Python.

Users can choose terms from a pre-arranged list of words you can generate. Additionally, you must implement particular routines to verify whether a user has submitted a single letter or if the input letter is in the hidden word to determine if the user has truly entered a single letter and print the appropriate results (letters). Here is a sample GitHub repository that will help you get started.

Is an email slicer easy to create in Python?

One of the useful Python projects that will be very useful in the future is this one. The first portion of all e-mail addresses, the part before the @ symbol, contains the alias, user, group, or department of a company. The ‘@’ is a divider in the e-mail address and is required for all SMTP e-mail addresses.

Users can construct a program to extract the username and domain of the email to create an Email slicer in Python. Even better, you may add your own customizations and include this information in a message you send to the host. Although it is a straightforward project idea, it is essential for improving your coding abilities. You can even add a front end for it using Tkinter.

However, one of the basic components of this project would be as follows:

email = input("Enter Your Email: ").strip()
username = email[:email.index('@')]
domain = email[email.index('@') + 1:]

How can I make a YouTube video downloader in Python?

Working on a YouTube video downloader project is one of the best ways to begin exploring your hands-on Python projects for kids. This is the best illustration of how to teach Python to novices in an enjoyable way. Every month, more than one billion individuals watch YouTube. We occasionally like to download certain videos permanently. YouTube does not provide that option, but you can develop an application that allows you to download YouTube videos in various file types and video quality. This project appears difficult, but once you get started, it is simple.

Before starting this project, you must install the pytube module for Python. Python does not come shipped with this module, but it can easily be installed by running the following command:

pip install pytube

The pytube module allows you to download youtube videos based on video links that can be provided. Moreover, it allows you to select the resolution of the video you want to download. 

To create a simple Youtube downloader project, you will first ask the user to enter the video link for this program. Next, create the YouTube module’s object by passing the link as a parameter, after which you can obtain the proper video extension and resolution. You can change the file’s name to suit your needs; otherwise, the original name will be retained. Finally, use the download function, which has one parameter that specifies the file’s location, to download the file next:

# importing the module
from pytube import YouTube

# Setting the save path
SAVE_PATH = "C:/" #to_do

# Inputting link of the youtube video to be downloaded
link = input("Video Link:")

try:
	# Creating object using YouTube
	yotube = YouTube(link)
except:
	print("Unable to Connect!") # Exception handling

# Filter out all files with the "mp4" extension
mp4files = youtube.filter('mp4')

#to set the name of the file
youtube.set_filename('Sample Video')

# Video resolution to download passed in the get() function
d_video = youtube.get(mp4files[-1].extension, mp4files[-1].resolution)
try:
	# Downloading the youtube video
	d_video.download(SAVE_PATH)
except:
	print("Error while downloading!")
print('Download Completed!')

How do I calculate the Fibonacci series with Python?

You can use a function to determine whether a given number is part of the Fibonacci sequence or not when you input a number.

The preceding projects all share the trait of assisting you in getting your fundamentals correct. Both the developer and the bug fixer will be you. Not to add that you’ll also be working with variables, strings, numbers, operators, etc., and writing and implementing various functions.

For this program, we will be looping through a Fibonacci sequence. Here is an algorithm for the project:

  1. Ask the user for an input number to check the Fibonacci sequence.
  2. Using the first two Fibonacci terms, loop through the Fibonacci sequence until you reach a number that is either higher or equal to the input number.
    1. If numbers are equal, the user input-output is part of the Fibonacci series.
    2. If we have reached a greater number than the input, output that the user input is not part of the Fibonacci series.

Here is what an example code would look like:

fib_terms = [0, 1]  # Defining the first two numbers of the sequence

user_input= int(input('Enter the number you want to checkn'))

# Adding new fibonacci terms until the user_input is reached
while fib_terms[-1] <= user_input:
    fib_terms.append(fib_terms[-1] + fib_terms[-2])

if user_input in fib_terms:
    print('Yes. ' + user_input + 'is NOT a fibonacci number.')
else:
    print('No. ' + user_input + 'is NOT a fibonacci number.')

Which IDE should I use to create and build these beginner Python example programs?

If you’re a beginner, PyScripter would be your best option. PyScripter started out as a straightforward IDE that offered a solid scripting option for Delphi applications to complement the great Python for Delphi (P4D) components. It offers a more modern user interface and is quicker than other IDEs because it is designed in a compiled language. As an excellent Python development environment, it also provides many additional features.

This incredible IDE aims to develop a Python IDE that can rival other languages’ conventional Windows-based IDEs. PyScripter is a very helpful tool because it is compact, adaptable, and packed with capabilities. PyScripter was designed from the ground up for Windows and it is significantly quicker and more responsive than cumbersome text editors, all-purpose IDEs, or other Python cross-platform IDEs.

Brace highlighting, code folding, code completion, and syntax checking as you type are some of the useful features of PyScripter. A programmer must look at this if they want to grasp this software. The simplicity of use of a programmer is enhanced by the usage of Python source code tools. Finally, you may save time using this IDE to accept files dropped from Explorer.

The finest Python IDE enables project managers to import pre-existing directories and numerous run configurations. Work is more productive thanks to its integrated unit testing because it enables the creation of automated tests. The unit testing GUI in this program is sophisticated. To enhance the quality of the product, programmers can utilize PyScripter in conjunction with Python tools like PyLint, TabNanny, Profile, and others. It’s important to note that the IDE provides a powerful parameter system for adjusting the integration of external tools.

Click here to begin developing enjoyable and simple projects with the top Python development environment.

The post Top 10 Fun And Easy Python Projects For Beginners In 2022 first appeared on Python GUI.

]]>
https://pythongui.org/top-10-fun-and-easy-python-projects-for-beginners-in-2022/feed/ 0 8039
PyScripter vs. IDLE: Which Is The Best Python IDE For Windows? https://pythongui.org/pyscripter-vs-idle-which-is-the-best-python-ide-for-windows/ https://pythongui.org/pyscripter-vs-idle-which-is-the-best-python-ide-for-windows/#respond Mon, 05 Sep 2022 10:00:00 +0000 https://pythongui.org/?p=8192 Python prides itself on being among the most powerful and widely used programming languages. Its massive popularity partly stems from its incredible versatility and relative strength for applications in data science and machine learning. Python...

The post PyScripter vs. IDLE: Which Is The Best Python IDE For Windows? first appeared on Python GUI.

]]>
Python prides itself on being among the most powerful and widely used programming languages. Its massive popularity partly stems from its incredible versatility and relative strength for applications in data science and machine learning. Python strong adoption is also likely due to its simple syntax, active community, and good collection of choices of a Python IDE for Windows. Python professionals love to rely on the language for their regular scripting needs. It is dynamic, diverse, and an absolute treat for novice programmers too. Although Python is ideal for a wide spectrum of use cases ranging from graphics to software development, programmers prefer to use IDEs or specialized code editors to write and debug their Python code. Like you they may be looking for help like where to get a Python IDLE download and other related tools. 

In this article, we compare two of the most iconic Python IDEs: PyScripter and IDLE, in our search for which is the best Python IDE for Windows. Before moving forward, let’s brush up on some basics regarding the significance of code editor and IDEs.

Why is it essential to use the best Python IDE for Windows?

Python IDEs are incredibly handy tools for both novice and seasoned developers. Simply put, an integrated development environment (IDE) is software made up of commonly used developer tools bundled into a simple-to-use graphical user interface to create a tool which combines all the strengths of each of them.

A typical IDE usually consists of one or more of the following

  • A source code editor for writing the program’s source code
  • Local build automation for creating a local software build, like compiling computer source code.
  • A built-in powerful debugger for debugging code

An IDE can have numerous features that vary and may provide more than just the list shown, but the fundamentals remain the same.

Developers love to use IDEs because they allow for interactive Python development. They automate the process of configuring and integrating multiple utilities in Python code.

Therefore IDEs not only reduce the burden on the developer’s shoulder but can dramatically cut down the effort and time involved. Additionally, since every utility is available on the same workbench, developers don’t have to spend hours learning how to use each separately.

This makes it an incredible advantage for novice developers who depend on IDEs to work on par with the existing team’s expertise and workflow.

Now that we have brushed up on the significance of IDEs let’s move on to comparing two of the most popular ones.

PyScripter vs. IDLE: Which Is The Best Python IDE For Windows?  A laptop showing the PyScripter IDE

What makes IDLE a worthy contender for best Python IDE for Windows?

IDLE (Integrated Development and Learning Environment) is the default Python ide software. It is also currently a widely used Python IDE.

IDLE is gained traction because beginners find it easy to use and at the time of its release there was relatively few alternatives.

What are some of the features of IDLE?

Novice Python developers rely on it to learn Python language efficiently. IDLE works on multiple platforms. This cross-platform support makes a popular choice among professionals and beginners.

  • You can search within any window and search through multiple files.
  • IDLE also has a debugger with stepping and breakpoints features to help developers spot and eliminate bugs.
  • IDLE  is a multi-window text editor with coveted features like smart indent, call tips, auto-completion, and Python colorizing.
  • IDLE is among the few IDEs encoded purely in Python using the Tkinter GUI.
  • You may also launch a Python shell window with colored input, output, and error messages.
  • It is possible to open multiple editor windows on IDLE simultaneously.

Apart from that, IDLE is relatively simple and can run without a browser or server. 

What are the downsides to IDLE?

IDLE still falls behind in numerous aspects despite its user-friendly interface and excellent customization.

One of the major downsides of using it is that a file created using IDLE can only be accessed on its created device. Therefore to access it from a different device, the user needs to send or copy the file to the relevant device. 

  • Perhaps one minor but significant drawback is that IDLE is not as advanced as other Python code editors. For example, IDLE does not automatically save changes while someone is coding which opens the developer to the possibility to lose their work in the event of a power cut.
  • IDLE can also be rather limited for more experienced developers. Many features of IDLE are constrained to prevent overwhelming novice developers, which is admirable, but this can mean pro developers feel a little restricted.
  • Furthermore, IDLE’s performance and organizing features become troublesome as you begin working on bigger projects.
  • Additionally, IDLE lacks auto-completion and theme support by default. It doesn’t have a built-in terminal or an embedded debugger.
  • Furthermore, IDLE does not accept plugins, making it difficult to adapt them to your needs.

These traits can mean IDLE is not the first choice for seasoned developers. While IDLE is a safe haven for beginners, senior developers need an alternative that is practical and powerful.

That’s where PyScripter IDE comes in. Let’s analyze what makes PyScripter so popular.

PyScripter vs. IDLE: Which Is The Best Python IDE For Windows? A screen showing the free Embarcadero Python tools

Why is PyScripter the best Python IDE for Windows?

Although there is a plethora of Python IDEs out in the market, none compares to PyScripter in terms of all-round functionality.

Programmers consider it the best Python IDE for Windows because it is not only jam-packed with features but is also surprisingly compact and flexible. PyScripter is a terrific new Python IDE with unrivaled capabilities and affordability.  Its objective is also to provide a trustworthy scripting solution for Delphi applications.

PyScripter was developed in a compiled, optimized native language – Delphi, which makes it incredibly quick. This makes PyScripter the perfect Python partner since it increases productivity thanks to the features and that zippy performance.

Why is PyScripter a superior Python IDE?

Traditional IDEs like IDLE can occasionally be slow and glitchy, but PyScripter has several exceptional features that make it a favorite choice among programmers and developers worldwide.

PyScripter includes many convenient features, like checking your syntax as you type, auto code completion, and brace highlighting. Unlike IDLE, PyScripter is the top choice for large-scale projects involving Python. It is a powerful and stable Python editor; therefore, professional developers rely on it to run Python scripts. PyScripter conserves your time by automating tedious, time-consuming processes. On top of that, PyScripter employs Python source code tools, which greatly simplify programming.

Speaking of efficiency, you can run scripts without saving them and maintain track of your command history.

PyScripter provides great value for money and is exceptional in terms of functionality and feature starting to build you’re just getting started with building a good Python coding environment or are already an expert.

PyScripter vs. IDLE: Which Is The Best Python IDE For Windows? A person using a laptop with the PyScripter IDE open on the about page.

What is the best Python IDE for Windows to run and debug Python Code?

After carefully comparing IDLE and PyScripter, we have concluded that PyScripter is the best Python editor because it is so far ahead in terms of capability and reliability. Therefore we recommend using PyScripter as your daily driver. It is incredibly lightweight, packed with features, and consumes the least amount of memory while providing top-notch performance.

What else make PyScripter the best Python IDE for Windows?

Apart from overcoming the limitations of IDLE, PyScripter adds numerous other features like code autocompletion, saving code automatically and a syntax highlighting editor to enhance your Python experience.

Whether you are a seasoned developer or a novice, PyScripter is a must-have tool in your arsenal.

What are you waiting for? Join us now and take your Python Experience to the next level!

The post PyScripter vs. IDLE: Which Is The Best Python IDE For Windows? first appeared on Python GUI.

]]>
https://pythongui.org/pyscripter-vs-idle-which-is-the-best-python-ide-for-windows/feed/ 0 8192
APILayer’s 7 AI & Machine Learning APIs for Python Developers https://pythongui.org/apilayers-7-ai-machine-learning-apis-for-python-developers/ https://pythongui.org/apilayers-7-ai-machine-learning-apis-for-python-developers/#comments Sun, 04 Sep 2022 14:42:38 +0000 https://pythongui.org/?p=8197 Python is great for AI and Machine Learning. Working with AI and ML libraries, however, sometimes can be a challenge.  That’s why APILayer, which belongs to the Idera family like Embarcadero, has no less than...

The post APILayer’s 7 AI & Machine Learning APIs for Python Developers first appeared on Python GUI.

]]>
Python is great for AI and Machine Learning. Working with AI and ML libraries, however, sometimes can be a challenge. 

That’s why APILayer, which belongs to the Idera family like Embarcadero, has no less than seven APIs designed to make your life easier as you deploy AI and ML in your software.

These APIs come with simple and easy-to-apply Python documentation, and even junior Python developers in your team can implement these API solutions into your business processes and automation.

Which Python Libraries Are Used For Machine Learning? What Do They Do?

Some of the most popular Python libraries for Machine Learning are scikit-learn, TensorFlow, and Keras. These libraries provide tools that can be used to build, train, evaluate and optimize Machine Learning models.

How To Start Creating New Windows For A Python GUI

So What Are AI & Machine Learning APIs?

AI & Machine Learning APIs are web-based services that provide access to AI & Machine Learning models. These APIs can be used to develop new applications or improve the performance of existing applications.

Why Use a Machine Learning API Rather Than a Machine Learning Python Library?

You might want to use a Machine Learning API rather than a Machine Learning Python library for three key reason reasons:

  • An API can provide a higher-level interface than a library, making it easier to use
  • An API can be more scalable than a library since it can be used by multiple applications simultaneously
  • An API can be more flexible than a library since it can be updated more efficiently to support new features or changes in the underlying data

How Can I Use APILayer’s AI & Machine Learning APIs?

You can use AI & Machine Learning APIs by making calls to the API using a programming language like Python or Java. These calls will allow you to access the API’s AI & Machine Learning models. To make an API call, you will need to have the API URL, the name of the API method you wish to call, any parameters that the method requires, and your API key. The methods and parameters will depend on the API you are using. If you use the Python requests library, the results from the URL will be returned in JSON format.

APILayer’s AI & Machine Learning APIs

APILayer offers a number of different AI and Machine Learning APIs that can help you with everything from natural language processing to predictive modeling.

In this blog post we will look at the following seven:

  • Natural Language Processing (NLP)
  • Sentiment API
  • Did you mean this API
  • Keyword API
  • Text to Emotion API
  • Bad Words API 
  • Resume Parser API

1. Natural Language Processing API

api001-8933097-4483085

The APILayer NLP API is one of the best ways to get started with natural language processing in Python. 

The NLP API can extract meaning from text and make your applications more intelligent. It API can help you with tasks such as sentiment analysis, text classification, entity extraction, and more. It also offers NLP features that include part-of-speech tagging, named entity recognition, and sentiment analysis.

Consider combining this API with Python’s Beautiful Soup Library to analyze and tag data found on websites, or Python libraries used for reading word documents to analyze text in documents.

Explore the documentation and get yourself a FREE API key

2. Sentiment API

api002-9286342-2939603

APILayer’s Sentiment API uses natural language processing to determine the sentiment of a piece of text. It can be used to analyze social media data, customer reviews, or any other type of text data. The API is easy to use, and it offers a free plan with up to 300 requests per month.

Features include sentiment analysis of customer reviews, automated customer support, text classification, language detection, summarization, and chatbots

Explore the documentation and get yourself a FREE API key

3. “Did you mean this” API

api003-2165331-5749110

Google’s famed “Did you mean this?” feature is a powerful feature to easily guide your users for corrections. The Did You Mean This API features a fast and convenient way to embed this feature into your application. 

Business use cases include: 

  • To help users find the right product or service on your website
  • To suggest alternative spellings or products on your eCommerce website 
  • To provide better search results on your website 
  • To improve the usability of your website 
  • To reduce customer support queries 
  • To increase customer satisfaction 
  • To increase sales and conversions on your website 
  • To enhance the quality of your website’s search results 
  • To reduce the number of abandoned shopping carts on your website 
  • To improve the overall user experience on your website

View the documentation and get yourself a FREE API key:

4. Keyword API

api004-4393558-3516610

With APILayer’s Keyword API, you can extract the most relevant words and expressions from text. Keyword extraction helps you find out what’s relevant in a sea of unstructured data. Extract keywords or key phrases to discover the main topics in your text. 

Business use cases include: 

  • Identify relevant topics for content marketing 
  • Find out what customers are saying about your product 
  • Understand what your competitors are talking about 
  • Generate tags for a blog post 
  • Get ideas for new products or services 
  • Find out what’s being said about a current event 
  • Monitor your brand’s reputation 
  • Analyze a text for sentiment 
  • Translate a document into another language 
  • Summarize a document

Check out the documentation on the link below and get yourself a FREE API key.

5. Text to Emotion API

api005-5582020-2435196

If you’re looking for a way to add emotional context to your text data, the APILayer Text to Emotion API is worth exploring. This API uses natural language processing to analyze text and return a score for six different emotions: anger, fear, joy, sadness, disgust, and surprise. You can use this API to analyze social media posts, customer feedback, or any other text data that you have.

  • Create a customer service chatbot that responds to customer emotions 
  • Create a marketing campaign that targets customers based on their emotions 
  • Create an app that tracks your mood and offers activities to improve your emotional state 
  • Develop a messaging app that analyzes the emotions in your messages and provides feedback 
  • Create a social media monitoring tool that analyzes the emotions in posts and comments 
  • Develop a training program for employees on how to deal with customers’ emotions 
  • Use emotional data to create targeted ads 
  • Create a customer loyalty program that rewards customers based on their emotions 
  • Analyze social media sentiment to identify trends and target customers 
  • Use emotional data to improve customer service interactions

Check out the documentation on the link below and get yourself a FREE API key

6. Bad Words API

api006-5532119-5148641

If you are looking for a way to filter out bad words from your text, then the Bad Words API from APILayer is an excellent option. This API allows you to quickly and easily filter out bad words from your text and is straightforward. Send a request to the API with the text you want to filter, and the API will return a list of bad words found in the text.

  • A profanity filter for social media platforms 
  • A content moderation tool for online forums and comments sections 
  • A text analysis tool for identifying the offensive language in user-generated content 
  • A tool for monitoring and analyzing social media conversations for signs of hate speech or online harassment 
  • A tool for automatically flagging or censoring profanity in user-generated content 
  • A plugin or extension for web browsers that block profanity on websites would be nice. 
  • A mobile app for tracking and avoiding profanity in public places 
  • A learning tool for children to help them avoid using bad words

Check out the documentation on the link below and get yourself a FREE API key.

7. Resume Parser API

api007-4861034-8598750

The APILayer Resume Parser API allows you to parse resumes and extract data such as contact information, education and work history, skills, and more. This can be useful for building a database of candidates for a job or for creating a profile of an individual for research purposes. The APILayer resume parser API is easy to use and provides good results.

This API would be beneficial for you if you are developing any of the following business ideas:

  • Resume Parsing Service 
  • Job Board 
  • Recruitment Agency 
  • Online Job Portal 
  • Career Counseling Service 
  • Job Search Engine 
  • Online Job Training 
  • Employment Services 
  • Job Placement Services 
  • Human Resources Management

Check out the documentation on the link below and get yourself a FREE API key.

Talk to Us!

There it is, our list of seven great APIs by APILayer. Need help deciding which are best for your business? Talk to us! We’re here to help you achieve your goals.

Contact us today to get started.

The post APILayer’s 7 AI & Machine Learning APIs for Python Developers first appeared on Python GUI.

]]>
https://pythongui.org/apilayers-7-ai-machine-learning-apis-for-python-developers/feed/ 1 8197
7 Secrets To Building A Stunning Python Graphical UI https://pythongui.org/7-secrets-to-building-a-stunning-python-graphical-ui/ https://pythongui.org/7-secrets-to-building-a-stunning-python-graphical-ui/#respond Mon, 29 Aug 2022 15:15:15 +0000 https://pythongui.org/?p=8162 A Python graphical UI can be created relatively easily using some existing packages supporting Python GUI functions. We have a quick overview of the most popular packages that do the job. What makes a good...

The post 7 Secrets To Building A Stunning Python Graphical UI first appeared on Python GUI.

]]>
A Python graphical UI can be created relatively easily using some existing packages supporting Python GUI functions. We have a quick overview of the most popular packages that do the job.

What makes a good Python graphical UI?

There is no one-size-fits-all answer to this question, as the best way to build a stunning GUI will vary depending on your specific needs and preferences. However, some tips that may help you create an attractive and effective GUI include using high-quality images and fonts, making use of color effectively, and ensuring that all elements are easy to navigate.

First and foremost, a good UI is logical and intuitive and requires no effort from the user to figure out how to interact with the software and get results. Users are intelligent, but their brains have to focus on achieving their goals, not on figuring out how to find where to click.

The main points to keep in mind when designing the layout are

  • Logical positions of the design elements
  • Simplicity
  • Color scheme
  • Appropriate fonts
  • Consistent design effects
  • Optimal and flowing use
  • Action confirmation

Are the logical positions of the design elements in a Python graphical UI important?

Users expect to see certain components in specific locations. The logical place for a menu bar is on top, not bottom right, for example. Likewise, the close button is expected to be on the top right corner. Putting it to the bottom left would leave users confused.

Components must be there where the user needs them. Let’s consider a long text box that requires scrolling and clicking a button (e.g., agreeing with terms and conditions). The button should be available right where the user will end scrolling. It would be annoying to scroll back up to the beginning just to find the Accept button.

Why should we aim for simplicity when designing a Python graphical UI (user interface)?

We are all in a hurry. We have no time to search for a feature. It has to be obvious how to do what we are aiming to do. Clutter makes the user wonder where to click and which of the countless menus to scroll through. A good program is supposed to make the user’s life easier, not clumsier. Animations should be limited or completely avoided. People are probably not using the piece of software for fun but to obtain specific results.

7 Secrets To Building A Stunning Python Graphical UI.  A studio desk with three monitors showing a good UI

Why is a consistent color scheme important in UI design?

Black text on a light gray background is easy on the eyes. If somebody is supposed to use your program for hours, you want to ensure that they are not straining their eyes. If somebody gets a headache from using your software, they will probably start avoiding it and look for alternatives.

Red text on a blue background is a disaster. Nobody would even try reading it. Likewise, some colors simply do not go together in any circumstances. There are many online tools to create various color palettes.

What role do appropriate fonts play in Python graphical UI design?

Some labels are more important than others. They should be drawn in bigger font than the rest of the text or at least in bold font to attract the user’s attention.

How important is it to have consistent design effects?

You need to choose the visual style in advance. Try to plan everything before writing the code. Decide whether you want to use clean, simplistic UI components with uniform colors or if you want to have drop shadows, transparency and glass-like looks. Using clear icons will massively improve the user experience.

What do we mean by optimal and flowing use?

The user needs to get things done quickly. Think about it – how willing are you to make 20 mouse clicks just to save a file? How about enabling keyboard shortcuts to do it without even thinking?

What is action confirmation in UX and Python graphical UI design?

There is nothing more annoying than a stuck program. Your program needs to respond to the user’s actions so that they know that the program is doing something. For example, a button should change in some way when pressed.

7 Secrets To Building A Stunning Python Graphical UI. A login screen

What to avoid when building a user interface?

  • Confusing structure
  • Clutter
  • Screaming or mismatching colors
  • Too many animations
  • Unintuitive and unnatural arrangement
  • Inconsistent style
  • Overcomplicated menu structure
  • Lack of feedback on user actions

Bonus advice

If you have limited experience, take a look at the software that you use yourself. Study the positions of the components, and ask yourself if the design annoys you. Is there something that you would modify if you were the programmer?

What tools are available for building GUIs?

The popular Python GUI packages offer similar functionality. The core idea is to create the main window, a menu and items on the window that the user may or may not interact with. It is recommended to use an IDE to develop the code. We highly recommend PyScripter – a lightweight, stable and feature-rich IDE.

Download PyScripter

The available Python graphical UI packages include:

  • DelphiVCL
  • Tkinter
  • PyQt
  • WxPython
  • GTK+ 3
  • Kivy

They can be installed easily via the pip package or in PyScripter, for example.

What UI components are available?

Inside the main window, there can be buttons, checkboxes, radio buttons, combo boxes (dropdown lists), toggles, text fields, and more. There are ready-made widgets that save the developer’s time when planning their GUI. On-click events can be assigned to widgets to allow interactivity. They also have an identifier so that the interaction with a function can affect a specific component.

7 Secrets To Building A Stunning Python Graphical UI. A DAW style Python GUI

How to get started creating a Python graphical UI?

There is a large number of resources to get started with Python GUI programming.

You should definitely check out our tutorial on how to build a GUI currency converter using Python.

In a video tutorial, you can see how to create the 2048 game using Python.

A comprehensive video guide about using Tkinter is available here

Why not try it out for yourself?

Click here to download PyScripter now and start building a Python graphical UI.

The post 7 Secrets To Building A Stunning Python Graphical UI first appeared on Python GUI.

]]>
https://pythongui.org/7-secrets-to-building-a-stunning-python-graphical-ui/feed/ 0 8162
Python Test Automation: Six Options For More Efficient Tests https://pythongui.org/python-test-automation-six-options-for-more-efficient-tests/ https://pythongui.org/python-test-automation-six-options-for-more-efficient-tests/#respond Tue, 23 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=8138 Although software testing in Python is a broad topic, it doesn’t have to be challenging. In a few simple steps, you can get started developing basic tests for your application, and you can expand from...

The post Python Test Automation: Six Options For More Efficient Tests first appeared on Python GUI.

]]>
Although software testing in Python is a broad topic, it doesn’t have to be challenging. In a few simple steps, you can get started developing basic tests for your application, and you can expand from there. Excellent testing tools are already present in the Python standard library. Utilizing the language’s built-in capabilities will help you create robust test automation. But because Python is used for many things, including creating Python automation testing tools, API testing, and adding test automation to a Python codebase is simple, you might sometimes need some more test libraries as options for efficient testing. This article will discuss the 6 top Python testing tools.

What is Python testing?

Python automation testing tools

In the world of testing, automation testing is a well-known context. In this scenario, a script rather than a human is used to carry out the test plans. Python includes the tools and libraries needed to support automated system testing. Writing test cases in Python is comparatively simple. Python-based test automation frameworks are rising in popularity along with the use of Python.

How to differentiate between automated and manual testing?

You must list all the features of your application, the various input types it can accept, and the anticipated outcomes of having a full set of manual tests. Then, you must double-check each item on that list every time you modify your code. However, this is clumsy.

Automated testing, a more efficient software testing technique, can help with that. Test automation involves using a script rather than a human to carry out your test plan (the components of your application you want to test, the order in which you want to test them, and the anticipated responses). 

Test automation makes work easy in the long run. You can already build automated tests for your application with Python’s built-in tools and libraries.

What are the six best options for automated testing in Python? 

Python automation testing tools

Let’s discuss the top six options for automated Python testing.

What is PyUnit?

The default Python test automation framework is known as PyUnit or Unittest. It became a part of the Python standard library in version 2.1 and is backward compatible with all later iterations of the language. A Python version of JUnit, the common unit testing framework for Java, is called PyUnit. 

Therefore, it will be very simple for developers to switch from Java to Python. Kent Beck’s Smalltalk testing framework is responsible for creating both testing frameworks.

The PyUnit test framework provides you with all the tools you may need to create automated tests, including:

  • Fixtures that help you can set up and tear down the objects required in a test.
  • Provide you with methods so that you can perform the actual tests.
  • Help you group test classes into logical units using Suites. 
  • Finally, provide you with runners for executing tests.

How is PyTest as an automated testing framework?

A superset of PyUnit’s features is available in PyTest, a native Python test library. Its architecture isn’t modeled but rather has a distinct Python flavor. It uses Python decorators and assertions a lot.

Additionally, PyTest supports parameterized testing, which facilitates code coverage and promotes code reuse.

PyTest has its support for test discovery in addition to fixtures, suites, and test runners. You can choose which tests to run based on the method names, packages, or decorators you add to your test code. PyTest also supports parallel test execution. Combined, these features make managing sizable code bases simpler than PyUnit.

Is Behave one of the preferred test automation tools?

Behave is a behavior-driven (BDD) test framework. As opposed to PyUnit and PyTest, you write your tests in the Gherkin language used by Cucumber. Despite not being an official Cucumber variant, it is one of the most widely used BDD frameworks for Python and fully supports Gherkin.

Because Behave is so popular, PyCharm Professional Edition from JetBrains includes a plugin. In addition, a wealth of online guides and documentation are also available for using Behave.

Your tests are written using a natural language grammar that describes a feature in terms of behavior and expected test results. Then you write your tests with annotations that match the conditions and behavior. Finally, the test is administered, the data is gathered, and it is recorded in your behavior files by behave.

What is Lettuce used for in terms of a Python test?

Lettuce is a Python and Selenium tool for behavior-driven automation. It uses a text syntax similar to Behave’s based on Gherkin to describe test scenarios, but it is not quite as compatible. Nevertheless, Lettuce works well with small projects and has a smaller footprint than Behave.

Additionally, integrating it with frameworks like Selenium and Nose is simple.

What features does the Robot framework have?

The most well-known Robot Framework is a Python-based open-source automation testing framework. This framework was created entirely in Python and is used for test-driven development and acceptance testing. In the Robot framework, test cases are written in keyword style.

The Robot can run Java and .Net and supports cross-platform testing for desktop, mobile, and web applications on Windows, Mac OS, and Linux operating systems.

Robot also serves as a tool for robotic process automation and acceptance testing (RPA). Moreover, Robot installation is highly advised using Pip (Package Installer for Python).

Can you perform efficient tests using Nose2?

The Nose2 is a Python-based unit test framework capable of running Doctests and UnitTests.

Since Nose2 is based on unittest, and for this reason it is also known as extend unittest or unittest with the plugin designed to simplify and ease testing. Nose supports many functions for writing tests and exceptions and uses collective tests from unittest.testcase.

Additionally, it allows for the simultaneous definition of package fixtures, classes, modules, and complex initialization in place of frequent writing.

Do you know all about Python testing automation?

Python automation testing tools

Over the past ten years, Python has steadily gained in popularity. You probably use Python already or are planning to add it to your toolkit soon.

Python’s growing popularity, frameworks, testing tools, and other utilities have increased. The top six options for you successfully covered in our discussion today. These frameworks are compatible with PyScripter, the best IDE.

What is PyScipter?

To complement the excellent Python for Delphi (P4D) components by offering a robust scripting solution for Delphi applications, PyScripter was initially developed as a compact IDE.

Why do developers love PyScripter?

Many developers consider PyScripter to be one of the most feature-rich Python IDEs on the market right now.

This IDE guarantees automatic test generation, enabling you to carry out unit testing automatically. It also has a fantastic GUI for unit testing. Additionally, it provides a sophisticated graphical user interface for running unit tests, a common Python module, in its unit tests window. So, PyScripter makes the software testing process easy as you can write test cases conveniently.

Now put all this knowledge to work and use PyScripter today for Python automation testing tools!

The post Python Test Automation: Six Options For More Efficient Tests first appeared on Python GUI.

]]>
https://pythongui.org/python-test-automation-six-options-for-more-efficient-tests/feed/ 0 8138
How Best Python Development Tools Improve Developer Productivity https://pythongui.org/how-best-python-development-tools-improve-developer-productivity/ https://pythongui.org/how-best-python-development-tools-improve-developer-productivity/#respond Mon, 22 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=8130 Python is one of the most popular programming languages worldwide. It is renowned for clear syntax, being dynamic, and being strongly object-oriented. Python also has a wide range of uses, from being the first programming...

The post How Best Python Development Tools Improve Developer Productivity first appeared on Python GUI.

]]>
Python is one of the most popular programming languages worldwide. It is renowned for clear syntax, being dynamic, and being strongly object-oriented. Python also has a wide range of uses, from being the first programming language for students to the preferred language for AI/ML programs. Programmers may easily put down their code using the best Python development tools and the best Python editor.

Many of the best Python IDEs have been developed as a result of the growing demand for Python worldwide. When creating something using this fantastic programming language, you want to be sure you have the appropriate Python development tools. Furthermore, the instruments you employ will frequently influence the rest of your encounter.

This post will examine a dedicated code editor, PyScripter, some of the best Python tools available, and the Python libraries for Delphi.

Why is a good Python integrated development environment necessary?

best Python development tools

Integrated Development Environment is referred to by the abbreviation IDE. By leveraging highlighting, resource management, compilers, debugging tools, and other software development requirements, it is a coding tool that makes authoring, testing, and debugging code easier. IDEs and code editors are a well-defined notion, but as other tools, like notebooks, gain access to functionality previously only available in IDEs, it is being redefined. 

PyScripter is a popular open-source code editor. Beginning as a simple IDE, PyScripter aimed to provide a reliable scripting solution for Delphi applications to go along with the top-notch Python for Delphi (P4D) components.

Because PyScripter was created in a compiled language, it is quicker than some of the other IDEs and has various features that make it an effective Python programming environment. When competing with other available IDEs, PsScripter always takes the lead. Some examples of these available text editor are Visual Studio Code, Sublime text, etc.

What is the importance of productivity tools in Python code editors?

All phases of the software development lifecycle must be productive for software engineers. Several applications are now available to aid Python developers in staying concentrated and productive throughout the whole software development lifecycle, from developing and testing their code to optimizing performance.

Developers may use these tools to improve code optimization, organize work, auto code completion, and automate the laborious chores associated with working in a software development environment. Other uses of these tools include automatic code formatting, syntax highlighting, and code analysis.

What are some other amazing Python development tools which increase developer productivity?

best Python development tools

Numerous Delphi and C++Builder developers utilize the established GUI libraries VCL and FireMonkey(FMX). The DelphiVCL and DelphiFMX libraries for Python are a collection of Python modules that give Python programmers access to the dependable and established VCL and FireMonkey (FMX) GUI frameworks.

While DelphiFMX for Python uses the cross-platform FireMonkey framework and delivers a strong, flexible GUI framework to Windows, Linux, macOS, and Android, DelphiVCL for Python is focused on native Windows development and uses the Windows-only VCL framework.

Using the VCL and FMX libraries for Python programming does not necessitate prior Delphi experience.

 However, it is a great benefit when working with these libraries. The popular PyScripter Python IDE’s open-source Python4Delphi library is used to build the libraries.

What is so superior about DelphiVCL?

For building outstanding, cutting-edge graphical user interfaces (GUIs) for your Python scripts, DelphiVCL is a strong framework. Since DelphiVCL is independent of Delphi, installing Delphi is not necessary. 

However, you may utilize Delphi’s robust IDE software and user-friendly designers to graphically build and enhance your user interface for usage in Python GUI App development (available even in the free Community Edition). 

Watch this excellent video to learn about the DelphiVCL and see what it can do to build gorgeous, contemporary GUIs for your Python projects. Applications may require user interfaces. Python and DelphiVCL are also covered in the video. 

The VCL is a well-known native Windows GUI framework with a sizeable library of built-in visual components and a wide range of third-party components. How can Python users take advantage of the greatest foundation for native Windows programs? The DelphiVCL Python module makes the VCL a leading tool for developing native Windows GUIs. 

Why is Python GUI with DelphiFMX successful?

The Delphi FireMonkey framework is built on the Python for Delphi Library. To create graphical user interfaces for Windows, macOS, Linux, and Android, you may get the DelphiFMX Python package from pip. Modern software must leverage GPU acceleration using DirectX or OpenGL. The user-friendly package includes buttons, lists, menus, and panels.

Designers and developers can use FireMonkey Stencils with Delphi, RAD Studio, or C++ Builder to construct multi-build device apps. The styles and interface components of the FMX Framework provide countless design possibilities, while FMX Stencils ease developer and designer cooperation.

In addition to FMX Stencils, you may create wireframes and mockups using tools like Sketch, Photoshop, Illustrator, and Balsamiq. By transforming the vector components into Sketch and Illustrator symbols, Photoshop smart vector objects, and SVGs, designers may quickly and easily create application user interface mockups and prototypes.

What is Python4Delphi?

Python’s object-oriented, dynamically typed, interpreted, interactive programming language enables quick, iterative development, and its libraries are among the most well-documented and well-maintained code resources accessible. Python is comparable to Delphi in this regard.

A collection of free Lazarus and Delphi components known as Python for Delphi (P4D) covers the Python DLL (FPC). They create new Python packages and types and make it simple to launch Python applications. Python extensions may be developed as DLLs using P4D, among other things. Different levels of capability are possible with P4D, including:

  • Access to the Python API at a low level.
  • Bi-directional high-level interaction with Python.
  • Access to Python objects is made possible through modified Delphi versions.
  • Employing RTTI to wrap Delphi objects for usage in Python codes.
  • Python extension modules are produced using classes and methods from Delphi.

P4D makes it very easy to use Python as a programming language for Delphi applications. 

Do you now know all about the best Python development tools?

best Python development tools

Due to the huge success of Delphi’s Windows development tools, the business is now using its expertise to create Python GUIs. Due to the outstanding underlying architecture and careful attention to detail, Delphi’s Python tools let you create stunning and effective GUIs for your applications. Additionally, it provides fully customizable final user interfaces, aesthetic and functional components, and enterprise-ready features.

DelhiVCL and DelphiFMX provide a high premium on quality, and their connection with corresponding operating systems adds an extra degree of security to the python ide software.

A powerful tool with many features and customization possibilities is DelphiFMX. Due to its built-in support for hardware acceleration, it is strongly suggested for developers who exclusively work with Windows. The ideal IDE for maximizing the use of these modules is PyScripter, a text editor that simplifies Python debugging.

It’s time to put your knowledge of the Python development tools to use now that you know how they can improve your productivity. So click here and begin your journey with PyScripter now!

The post How Best Python Development Tools Improve Developer Productivity first appeared on Python GUI.

]]>
https://pythongui.org/how-best-python-development-tools-improve-developer-productivity/feed/ 0 8130
PyCharm vs. Spyder: What’s The Best Option For Python Programming? https://pythongui.org/pycharm-vs-spyder-whats-the-best-option-for-python-programming/ https://pythongui.org/pycharm-vs-spyder-whats-the-best-option-for-python-programming/#respond Fri, 19 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=8106 PyCharm and Spyder are two of the most popular IDEs (Integrated Development Environments) for Python programming. To be clear, an IDE is a piece of software that offers tools to make programming easier. We will...

The post PyCharm vs. Spyder: What’s The Best Option For Python Programming? first appeared on Python GUI.

]]>
PyCharm and Spyder are two of the most popular IDEs (Integrated Development Environments) for Python programming. To be clear, an IDE is a piece of software that offers tools to make programming easier. We will see which IDE makes the programming easier in this post about PyCharm vs Spyder. Programmers utilize Python, an object-oriented language, in various fields, including computer science, engineering, machine learning, and more.

In this post, you will learn all you need to know about PyCharm and Spyder, including a comparison of each IDE’s features and what sets them apart. The IDEs are both a Python download for Windows. After reading this comparison of PyCharm and Spyder, you may evaluate your needs and preferences to choose which IDE is the best fit. B

Which IDEs will we discuss?

PyCharm vs. Spyder: What's The Best Option For Python Programming? A laptop with the DelphiVCL and DelphiFMX library download page

The right Python coding software is one of the finest resources accessible to prospective programmers. Python is suggested for beginning programmers due to its widespread use and relative simplicity.

What is Spyder?

An open-source, cross-platform IDE for Python is called Spyder. Anaconda distribution makes it accessible for Windows, Linux, and Mac OS. Spyder combines the capabilities of a scientific program with all the advantages of a comprehensive development tool. Programmers may expand Spyder by adding new plugins. Programmers may also use Spyder as a PyQt5 extension library.

This IDE includes a multilingual text editor with a wealth of functionalities. Unfortunately, programmers must install separate packages to test various Python versions because Spyder’s Python version is static.

What is PyCharm?

According to a 2019 Stack Overflow study, PyCharm is the ninth most well-liked programming environment. This IDE is cross-platform and supports a wide range of programming languages, including HTML, CSS, Angular JS, JavaScript, and TypeScript. A free Community Edition, a premium Professional Edition (PE), and a Student Edition are available. The Professional Edition’s features are also available in the Student Edition.

PyCharm vs. Spyder: what features do they have?

PyCharm vs. Spyder: What's The Best Option For Python Programming? The Delphi4Python Exporter page

Which one has a better text editor?

Spyder and PyCharm are sophisticated text editors. Both IDEs contain many beneficial features, such as code completion, allowing users to finish lines of code with which they are acquainted automatically. Each application also has syntax highlighting and style analysis capabilities. Additionally, Spyder and PyCharm both include the “go to definition” or “go to declaration” functionality to assist users in finding component definitions.

Code snippets and editable preset templates are both included in PyCharm. Developers frequently desire an integrated project browser, which it has. Users may also change everything, including the themes and syntax highlighting. Additionally, PyCharm has safe refactoring capabilities. On the other hand, the outline explorer in Spyder is a function, class, and method browser.

Spyder enables programmers to produce code cells. According to the firm, a “code cell” in Spyder is a group of lines that many users may execute simultaneously. These lines are often found in a script. In addition, Spyder may divide data horizontally.

Do the IDEs have scientific stack support?

Multiple libraries and dependencies are supported by both IDEs, especially through Conda. Matplotlib, NumPy, Jupyter Notebooks, and R are the libraries supported by both applications. Spyder and Anaconda both share standard libraries, but you can also download more than 1,500 Python or R data science packages.

Conda integration in PyCharm allows you to isolate dependencies by project while still maintaining separation. In addition, some libraries are provided by PyCharm through “Scientific Mode,” which is only accessible with the student and premium editions of the program.

Which IDE has documentation for help?

Both IDEs provide seamless, easy access to the assistance files. Users can use the text editor or command prompt to access help features. Once there, users may view examples, code samples, and the specification of any object, method, or class that is part of the common libraries. Both IDEs also provide a built-in browser for accessing web resources for typical library material.

Do the IDEs have a built-in Python debugging tool?

Programmers can benefit from using a debugger. Both PyCharm and Spyder offer an integrated debugger in this situation. Moreover, the PyCharm debugger is portable.

The PyCharm Pro version includes a JavaScript debugger. Additionally, PyCharm provides the option to step through your code visually. The quickest debugger available is PyCharm’s, according to the JetBrains website.

Spyder uses the PDB debugger. One of the many helpful features of this debugger is a window that shows the line, file, and status of each breakpoint. Additionally, the variable explorer may swiftly modify variables in each breakpoint. One appealing feature of this IDE is the variable explorer on Spyder; it displays all global memory addresses and lets you interact with them.

Are version control systems available?

Git, SVN, Perforce, and other popular version control systems are available in PyCharm. With features like repository change views, obsolete changes notice, overall change lists, and shelved changes, the application offers unified support for all VS systems. In addition, these VC systems include the plugins that the IDE’s default setting has enabled. On the other side, Spyder only offers minimal interaction with the Git version management system.

What price plans do the two IDEs have to offer?

Although a free alternative is accessible for student users, PyCharm is available for $199.00 per month. Spyder, in contrast, is open-source and cost-free.

Are there any limitations?

Both PyCharm and Spyder provide necessary IDE capabilities, but it’s crucial to take into account some of their restrictions.

Due to the range of plugins it comes with, PyCharm is a large application; therefore, companies searching for the lightest, quickest IDE may wish to consider alternative solutions. In addition, PyCharm provides comprehensive support for Python but less for other programming languages. Because of this, it might not be the best option for businesses that don’t use Python frequently.

Which IDE is the best?

PyPyCharm vs. Spyder: What's The Best Option For Python Programming? A screen showing a description of Python tools.

Although Spyder is a lightweight software, inexperienced users may find it more challenging to use than PyCharm because of its lack of extensions and customizability. However, businesses that want an IDE that may be completely customized could select PyCharm. Additionally, Spyder lacks PyCharm’s library of code snippets, which might make coding slower than with other programs.

It is difficult to decide which IDE is the best. It relies on a number of variables, including your tastes, the application area, and the programming language you want to employ.

Because PyCharm has many more extensions installed by default, Spyder is lighter than PyCharm. Therefore, when Spyder is installed via Anaconda, you may download a bigger library with it. However, PyCharm may be a little more user-friendly because of its completely customizable user interface.

Is there any other Python programming IDE apart from PyCharm and Spyder?

An IDE may distinguish between good programming and programming that is bad. Python is a powerful programming language that creates a wide range of applications, as demonstrated by the rise of analysts and data scientists. As a result, Python is now more well-liked. Furthermore, managing your code development is made easier with a good Python IDE. Therefore, using highly capable, modern IDE software is advantageous to help give a better, more hand-holding experience.

PyScripter is the best IDE with several complex capabilities, including code suggestions, a debugger, and many more advanced features. It is substantially faster than other Python IDEs since it was created in a compiled language. In addition, it has other more features that make it an excellent Python programming environment.

Since PyScripter offers more functionality than PyCharm and Spyder, it is obvious from the feature comparison above that PyScripter is a better overall package. All of the core functionalities are included in all of these IDEs, although PyScripter has a few extra. In these articles, you can read about the comparison of PyScripter vs. Spyder and PyScripter vs. PyCharm. This contributes to the explanation of why it is a well-liked favorite with good ratings.

The comparisons in this post should have helped you make a decision. Please share your thoughts in the section below.

The post PyCharm vs. Spyder: What’s The Best Option For Python Programming? first appeared on Python GUI.

]]>
https://pythongui.org/pycharm-vs-spyder-whats-the-best-option-for-python-programming/feed/ 0 8106
What Are The Best Python IDE And Code Editors In 2022? https://pythongui.org/what-are-the-best-python-ide-and-code-editors-in-2022/ https://pythongui.org/what-are-the-best-python-ide-and-code-editors-in-2022/#respond Wed, 17 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=8099 Python is possibly the twenty-first century’s most powerful and widely used programming language. Its popularity stems from its versatility, as it is used for data science, server-side web development, advanced programming, math, planning, simulations, and...

The post What Are The Best Python IDE And Code Editors In 2022? first appeared on Python GUI.

]]>
Python is possibly the twenty-first century’s most powerful and widely used programming language. Its popularity stems from its versatility, as it is used for data science, server-side web development, advanced programming, math, planning, simulations, and machine learning. Python’s popularity has grown due to its simplicity, syntax clarity, dynamic community, versatility, and wide range of best IDE Python has available. Moreover, the popularity of Python means a great selection of apps are available when you’re looking to find a Python editor for Windows for free.

As Python has gained popularity over the years, Integrated Development environments have undergone numerous developments to make it easier to write Python code. An integrated development environment (IDE) software program gives computer programmers access to various software development tools. Additionally, they combine well-known developer tools into a solitary graphical user interface (GUI).

What are the best IDEs for Python on the market?

What Are The Best Python IDE And Code Editors In 2022? A laptop with a Python IDE on it

What makes PyScripter one of the best Python IDE and code editors in 2022?

PyScripter is by far the best IDE Python can have in 2022. It’s an excellent program that is compact, flexible, expandable and packed with features. It was additionally created from the ground up for Windows. As a result, it performs noticeably better than bloated text editors, all-purpose IDEs, or other Python cross-platform IDEs in speed and responsiveness.

An integrated Python interpreter in PyScripter provides call hints and code completion. This program records your command history and lets you run scripts without saving them. This IDE also includes a remote Python debugger for debugging Python code. As a result, variables, the watch window, and the call stack are all visible.

Because of its simplicity of use and superior features, PyScripter consistently receives the highest ratings compared to its rivals. However, PyScripter will charge customization fees if your system needs special features to meet your particular business needs. These prices will change based on your needs and requirements.

You will unavoidably encounter difficulties as a Python developer. Furthermore, you should research the error message online if you are unsure what’s wrong. A developer community aided by the IDE can be helpful because they frequently find solutions more quickly and effectively. Pyscripter is more advantageous for Python developers because it is a community-driven project instead of IDLE Text. Moreover, PyScripter has a fantastic autocomplete feature and automatic code formatting. It has numerous other features making it the best IDE on the market.

Why is IDLE such a popular Python IDE?

The default IDE that comes with Python is called IDLE. All essential features are present, such as a Python shell window, autocompletion, highlighting, intelligent indentation, and a simple debug tool.

In light of this, IDLE is quite constrained for developers. All of its features are limited to that to avoid confusing new users. It is also lightweight. Furthermore, IDLE’s performance and organization tools become problematic once you start working on bigger projects.

Additionally, IDLE does not come with Theme support or auto-completion by default. It lacks an embedded debugger or built-in terminal. Additionally, IDLE does not support plugins, so you cannot customize it to meet your needs.

How is Thonny as a Python Code Editor and IDE?

Thonny is a free Python IDE that was created for programming beginners. The user interface (UI) is straightforward and has built-in features for autocomplete, auto designing, and investigating.

It also has unique features for beginners, such as a variable value tracker displayed close to the main editorial manager. In addition, to help inexperienced engineers focus on coding, all options are set using menus rather than configuration documents. A simple package manager streamlines even module establishment for beginners.

How is Atom compared to other Python IDEs on the market?

Atom stands among the best IDE Python and is an open-source text editor created with CoffeeScript. However, the underlying code of Atom has now mostly been converted to JavaScript. This is significant because it gives developers easier access to extensibility.

The purpose of Atom is to support and be multilingual. Python is a lightweight and dynamic language used in hybrid projects incorporating Java, HTML, CSS, and other integrations. In addition to utilizing the editor’s core functions, Atom’s IDE-Python package also adds features like completions, references, definitions, styling checking via linting, and code formatting.

Why is Spyder a fan favorite IDE?

Spyder is a Python-based environment that is extremely powerful and simple. Its uniqueness stems from the variety of features it provides. For instance, simple debugging, sophisticated editing, visually appealing visualization techniques, interactive executions, and numerous others.

Spyder is a Python-specific IDE designed for data scientists and ML engineers. It’s included with the Anaconda distribution that includes other popular Python libraries like Scikit-learn, Mumpy, Matplotlib, Scipy, and Pandas. Moreover, it includes great features like autocompletion, a powerful debugger, and an iPython shell. However, it has limited data visualization tools making it less friendly for data analysis and scientists.

Why is Sublime Text preferred over other Python Code Editors?

Sublime Text is a profoundly responsive code editorial manager utilized by many designers. Atom and Sublime Text look very similar from the overall perspective. This is not surprising given that many believe Atom is based on Sublime.

A few dozen programming languages are natively supported by Sublime, which also color-codes elements per the selected language (more on below). You will even receive real-time parsing error warnings from the code editor!

Additionally, Sublime offers code folding and auto-completion, including user-created variables. The latter reduces the size of lengthy pieces of code by concealing portions.

When using Sublime, the program’s speed becomes immediately clear. This is because the code editor was created using Python and C/C++, which is very compact. When working with large files, this distinction is also obvious. As a result, sublime Text can handle much more work without encountering issues.

Developers may need to look for an external tool to complete the task since Sublime Text does not come with a built-in debugger. Additionally, Sublime Text lacks a GUI for unit testing, but this can be done with third-party plugins.

What makes Visual Studio Code so popular in the Python developer community?

Visual Studio is an overall IDE that upholds Python through a Python Tools for Visual Studio (PTVS) module. Visual Studio has broad elements, with work in help for Git, an inherent terminal, and exhaustive unit test apparatuses. It additionally has a commercial augmentation center like Atom.

Visual Studio additionally accompanies Intellisense, generally viewed as one of the most mind-blowing autocompletion frameworks accessible to designers today. You can likewise add modules to permit support for web dev instruments like Flask or Django.

However, despite being a popular editor, it has many drawbacks. It is quite heavy for a code editor, and despite its support for a vast array of languages, it needs a community-driven plugin that is not optimized. Moreover, managing plugins for various applications can cause multiple issues; running large code files takes time compared to other code editors.

What is the best Python programming IDE in 2022?

What Are The Best Python IDE And Code Editors In 2022? The PyScripter download page

In this article, we spent highlighting the best things about the best IDEs Python has available as well as some shortcomings, but we can conclude with absolute certainty that PyScripter is by far the best IDE for Python in 2022.

PyScripter is a free, open-source dedicated and specialized Python IDE (Integrated Development Environment) that aims to compete with commercial IDEs for other languages in terms of features. It is feature-rich while being lightweight. This lightweight IDE contains all the functionality you’d expect from a modern Python IDE. It’s also natively compiled for Windows to use the least amount of memory while providing the best performance. PyScripter is a Delphi application with Python script extensibility.

Don’t just take our word for it! Cick here and start your journey of experiencing PyScripter, the best IDE for Python, free, now.

The post What Are The Best Python IDE And Code Editors In 2022? first appeared on Python GUI.

]]>
https://pythongui.org/what-are-the-best-python-ide-and-code-editors-in-2022/feed/ 0 8099
10 Mistakes Most Developers Make With Python GUIs https://pythongui.org/10-mistakes-most-developers-make-with-python-guis/ https://pythongui.org/10-mistakes-most-developers-make-with-python-guis/#respond Mon, 15 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=8093 Python is one of the most widely used programming languages worldwide. It is a high-level, object-oriented programming language. Several PythonGUI libraries are different in terms of functionality and licensing. Python is an interpreted language, giving...

The post 10 Mistakes Most Developers Make With Python GUIs first appeared on Python GUI.

]]>
Python is one of the most widely used programming languages worldwide. It is a high-level, object-oriented programming language. Several PythonGUI libraries are different in terms of functionality and licensing.

Python is an interpreted language, giving programmers freedom. However, enormous independence comes with great responsibility and the possibility of error. Programming is simpler with PyScripter, a free, open-source Python integrated development environment (IDE) for Windows which uses Python tools to simplify programming. In this post, we’ll go through 10 frequent errors Python programmers make in this post and how to correct them.

What are some common mistakes made by developers when creating a Python GUI?

10 Mistakes Most Developers Make With a Python GUI. An image of the PyScripter download page

How can invalid class variables be avoided?

One of the most frequent errors made by movie producers is this one. Python treats class variables as dictionaries. A class is lacking a property if one of its attributes is absent. That suggests that changing anything in one class shouldn’t impact other classes. In contrast to instance variables, class variables are shared by all instances inside a class. As a result, class variables and local variables function entirely differently. Since Python is an object-oriented language, class and local variables function differently. Programmers frequently change a class variable without using the proper class name, which causes an instance variable with an identical name to be created.

To avoid making this error again, programmers should always refer to class variables by their right names when identifying or changing them, ensuring that all class members receive the most current value.

Why should you refrain from utilizing improper indentation?

Python’s formatting rules for indentation are rather detailed. Language indentation in this programming determines whether a code line is connected to earlier code blocks. Developers frequently undervalue the critical necessity of employing proper indentation. Although PEP 8 suggests an indentation of four spaces, you can determine the number of spaces as long as they are uniform. Inexperienced programmers frequently make inefficient use of the spaces and tab keys.

If the indentation looks the same, you might not realize you’ve confused tabs and spaces, so pay great attention. We advise employing a Python IDE that features a search and replaces functions to maintain constant spacing to resolve this issue. PyScripter is the best Python GUI available if you’re seeking the perfect one. If PEP’s rules are inappropriate for you, you should commit to a certain number of spaces. Sticking to a certain amount of space is essential to avoiding this mistake.

How do I handle an UnboundLocalError?

This is one of the blunders that developers make the most frequently. In addition to the LEGB standard, Python developers need to comprehend its scope rules. The Local, Enclosing, Global, Built-in rule, also known as LEGB, is the foundation of the Python programming language. It’s crucial to understand that Python adheres to this particular order.

Following the LEGB rule, Python will initially assume that any variable allocated in a range is local to that scope and will override any variable of the same name in an outer scope. As a result, the code that was successful when you assigned the variable may now result in a “UnboundLocalError” when you call the function again. Using a Python IDE like PyScripter would be the best method to resolve this problem. However, you can easily correct this problem using an assignment statement to define or declare the variable as global explicitly.

How do Similar module names result in an error?

When importing a built-in module that you know is included in the Python Standard Library, you might be surprised to see the error message “ImportError.” This problem frequently occurs when programmers import a file into their library that has the same name as a built-in module from the Standard Library. In some cases, Python prefers the similarly named module you’ve installed to the built-in module from the Standard Library. The answer? Simply give the library file a new name that is distinct and separate from any Standard Library modules.

How can you use default function parameters from expressions?

By assigning a default value to a function parameter in Python, you may indicate that the argument is optional. Although this is a fantastic language feature, when the default value is changeable, it might cause some difficulty. Take this definition of a Python function, for instance:

def foo(bar=[]): # bar is optional and defaults to [] if not specified
bar.append("baz") # but this line could be problematic, as we'll see…
return bar

The misconception that the optional parameter will always be set to the default expression when the function is invoked without a value is rather prevalent. For instance, given the code above, one may anticipate that repeatedly calling foo() (i.e., without giving a bar argument) always would return “baz,” as the presumption would be that bar is set to [] each time foo() is called (i.e., a new empty list). However, a function argument’s default value is only ever analyzed once when the function is declared. As a result, calls to foo() without specifying a bar argument will continue to utilize the list. The bar parameter is only defined to its default (i.e., an empty list) when foo() is first declared.

What is the importance of the proper use of brackets or parentheses?

A surprising number of Python beginners make this error. Similar to arithmetic, a statement must be understandable for the number of open and closed parentheses and brackets to match. Verify your code to ensure that every open parenthesis or bracket has a matching closing to complete the concept.

What is the probable reason for a syntax error?

If you’re getting syntax issues, you could have neglected to include a colon at the end of a statement. A colon follows each structural sentence in Python code. This also holds for function headers, where the colon causes the remaining lines in the function to be indented. Beginner Python programmers frequently make this mistake. Simply practice this guideline until it is instinctive to make it right: every structured sentence finishes with a colon!

How to use the Python init function correctly?

The init method may be used as a constructor to create an object or allocate memory to a new class object. When an object is formed from a class, the init method is used as the constructor, enabling the class to configure the class’s attributes. In other words, it is only ever used to set values. But trying to utilize this function to return values is a typical error Python programmers make. Just realize that the Python init method’s function can only be used as a constructor to remedy this.

How to deal with limit in iterators?

Early Python programmers should know that iterators and generators have limits. Developers switching from Python 2 to Python 3 may frequently see this problem. Python3 is more effective since it includes many more generators. For individuals experiencing new difficulties, this can be challenging.

This error may appear as follows: you might use Python 2’s zip iterator function to merge two lists before attempting to output this list afterward. However, python3 won’t deliver all the values to you once if you use the same code. This is because the iterator is empty and cannot return any more values due to your use of it.

Simply changing a function to a list at the outset will address this. However, a list cannot be exhausted, although an iterator can be. For additional information on Python iterators, see this site.

Can users use changeable default parameters?

Another frequent issue occurs when default arguments are given mutable data types. When a function is created in Python, defaults for mutable data types are only evaluated once. If you only use the function once in your code, you might not notice anything strange, but if you use it again, Python will utilize the default value determined during the initial function call.

Let’s assume you’re working with a list of mutable data types. The interpreter will use the list first formed when the function is declared. Setting “None” as the default value is one technique to fix this programming issue. Any value given to the function can subsequently be verified to ensure that it matches the parameter.

How to improve your Python GUI experience?

10 Mistakes Most Developers Make With Python GUIs - the DelphiVCL and DelphiFMX libraries page

The Embarcadero-sponsored PyScripter Python IDE is a remarkable innovation with unmatched features and value for the money. It is brief and uncomplicated, and its goal is to give Delphi programs a dependable scripting solution. In addition, it offers a straightforward, useful Python UI that is both tidy and modern. As a result, PyScripter can effectively assist you in avoiding all of the errors that Python developers frequently make.

The well-known GUI libraries VCL and FireMonkey are used by many Delphi and C++Builder developers (FMX). The DelphiVCL and DelphiFMX libraries for Python are a set of Python modules that provide access to the trusted and well-respected VCL and FireMonkey (FMX) GUI frameworks for Python programmers.

While DelphiFMX for Python brings a robust, adaptable GUI framework to Windows, Linux, macOS, and Android using the cross-platform FireMonkey framework, DelphiVCL for Python is targeted at native Windows development and employs the Windows-only VCL framework.

Using the VCL and FMX libraries has a lot of advantages. The libraries are created using the open-source Python4Delphi package from the well-known PyScripter Python IDE.

We hope you’ve found this article helpful and it will help you avoid these common Python GUI mistakes. Click here and view our products for a smooth scripting experience.

The post 10 Mistakes Most Developers Make With Python GUIs first appeared on Python GUI.

]]>
https://pythongui.org/10-mistakes-most-developers-make-with-python-guis/feed/ 0 8093
Is PyScripter A Portable Python IDE? https://pythongui.org/is-pyscripter-a-portable-python-ide/ https://pythongui.org/is-pyscripter-a-portable-python-ide/#respond Wed, 10 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=8047 The popularity of app and workspace portability is still high, and many applications are available that give you a virtual identity on a USB device that fits in your pocket. If you work as a...

The post Is PyScripter A Portable Python IDE? first appeared on Python GUI.

]]>
The popularity of app and workspace portability is still high, and many applications are available that give you a virtual identity on a USB device that fits in your pocket. If you work as a developer, there may have been days when you could not carry a laptop with you. It becomes challenging when you might need to code in an IDE like Pyscripter at such times. USB flash drives help a lot since these thumb-sized devices are something you can pop in your pocket and easily carry with you everywhere you go. Did you know you can set up your USB stick to allow you develop your code and apps on the move without relying on tools and programs installed on any particular machine? Portable apps help make that possible. In this article, we will go over the concept of a portable app and then discuss how to use PyScipter as a portable Python IDE.

What is a Portable app? 

A portable program doesn’t require an installer. A single folder, which you can install anywhere on the system, contains all files necessary to operate the application. The app will continue to function even if you relocate the folder. An executable file for a portable app is often downloaded as a ZIP file, extracted to a folder, and run. If you save settings, they are saved in files in the same folder as the app.

What are the pros of a portable app?

The main advantage of adopting portable apps is obvious: they are portable. Put them on a USB drive to transfer them from computer to computer, for instance. They won’t leave any residue on the computers you use to operate them. Everything is saved directly in the portable app’s folder on the USB drive, including any settings you’ve saved. It functions similarly to how MS-DOS and Windows 3.1 did when they were first released.

Portable apps can be useful even if you don’t switch between computers. They have a reduced impact on your PC, typically smaller and lighter than most installable programs. You can sync them with your other PCs’ settings. Alternatively, you can use an app just once without worrying about contaminating your system.

Yes, you will inevitably need to install apps. They either require leverage of Windows’ multi-user or security features or are too huge to run as portable apps. You can pick between an installer and a ZIP when downloading a program because many of them are available in both forms.

Is PyScripter A Portable Python IDE? A hand holding a USB thumb drive which can run portable apps

Are there any downsides to portable apps?

Of course, employing portable apps has its drawbacks. Windows User Account Controls (UAC) for portable apps don’t function the same way as permanently installed apps and they are more vulnerable to non-administrative operations. 

Another drawback is that portable programs are frequently not developed with simultaneous users in mind. Since you’re presumably making a portable drive that you can use for yourself, this probably isn’t a significant concern. However, if a program needs to be used by numerous people, you’ll need multiple copies of the app folder on your portable drive, or everyone will need to utilize the same settings. 

Lastly, if you’re using a USB drive to run portable applications, take care to properly ‘eject’ the device rather than simply unplug it from the USB socket. Otherwise, you risk corrupting the programs or causing improper setting savings. Some PCs also are subject to trouble correctly handling USB devices when the PC is put to sleep or hibernate. Unfortunately, it’s relatively common to find some PCs nowadays don’t manage sleep well.

What are some features of portable IDEs?

The idea behind portable IDEs is the same as that of portable apps. Portable IDEs don’t require installation and don’t alter your PC’s settings. You can store portable IDEs anywhere, as long as there is enough capacity, including on an internal drive, an external storage device like a USB stick or SD card, a networked drive, or a cloud storage service like OneDrive or DropBox.

Similar to portable apps, portable IDEs have several benefits, including the ability to run on machines with restricted user permissions, the ability to carry your software with you when switching between computers, and the fact that they don’t interfere with any other installed programs.

Some portable IDEs come with an “installer,” but don’t be alarmed—this just unzips a compressed file archive and saves the extracted files to a location of your choice—it doesn’t alter your system files in any way. Although the application is an EXE file, the extracted folder also includes related files, such as fonts and settings, which are necessary to function.

Is PyScripter A Portable Python IDE? A person sitting on the edge of a mountain ledge with a laptop

What are some examples of Portable IDEs?

There are several postable IDEs available today. Let’s discuss a few.

Microsoft created Visual Studio Code, usually referred to as VS Code, a source-code editor for Windows, Linux, and macOS. Visual Studio Code supports a portable mode. This mode makes it possible for any data that VS Code creates and maintains to reside close to one another so that it can be transported between environments. The installation folder location for VS Code extensions can also be adjusted in this mode, which is handy in corporate settings when doing so would violate restrictions against installing extensions in the Windows AppData folder which is the default place for the non-portable mode install.

The Eclipse IDE is well-known for its Java Integrated Development Environment (IDE), but it also contains a ton of other awesome IDEs, such as C/C++, JavaScript/TypeScript, PHP, and more. Eclipse also has a portable version with which you can develop software directly from your removable mass storage device, even without admin rights.

Is PyScripter a portable Python IDE?

Yes, there is a portable version of PyScipter. Portable PyScripter, initially developed as an integrated development environment for Delphi applications, is now a stand-alone Python IDE.

It shows a user-friendly interface yet has a lot of powerful functions within easy reach. It offers an editor with syntax highlighting, a built-in Python interpreter with debugging, editor views, and code exploration.

The program is simple to use and is made to seem like other Python-compatible development tools. The application’s window components can be rearranged or made to float. You have access to an interactive interpreter, message windows, file, code, and project explorer windows with Portable PyScripter. The editor in Portable PyScripter is robust. Drag and drop operations can be used for editing, context-aware indentation, brace highlighting, and syntax highlighting.

You may construct templates by saving the layouts with specified names, a nice feature that takes advantage of the rearrangeable interface. Using one template for script editing and another for debugging enables you to design tailored layouts for various work phases.

The application offers you a variety of text editing tools and features because you utilize text throughout the entire coding process. For example, you can cut, copy, and paste material, enter and dedent code blocks, add different parameters, and select the appropriate encoding. You may also import Python scripts, run a syntax check, and debug them.

You can use this complete tool to run your Python programs in various ways. The integrated debugger, running without debugging, and even running outside of the application are all options for debugging.

What is the best portable Python IDE?

It’s easy to make the choice – PyScripter is a purpose-built Python IDE designed to be the best possible choice of Python IDE. The portable app version of PyScripter has all the full power of PyScripter’s tooling, editing, debugging and code editing capabilities natively built in. It is produced as a native Windows app not based on the Electron framework unlike VS Code so it doesn’t suffer from the same large memory usage that often occurs with Electron-based apps. Unlike Eclipse’s Java-centric origins PyScripter is specifically designed for editing and executing Python code and Python programs.

Portable PyScripter can compete with other top-tier offerings as a trustworthy Python integrated development environment. For the most convenient way to begin writing Python programs, click here.

The post Is PyScripter A Portable Python IDE? first appeared on Python GUI.

]]>
https://pythongui.org/is-pyscripter-a-portable-python-ide/feed/ 0 8047
Become An Expert With A Python GUI Builder By Watching These 5 Videos https://pythongui.org/become-an-expert-with-a-python-gui-builder-by-watching-these-5-videos/ https://pythongui.org/become-an-expert-with-a-python-gui-builder-by-watching-these-5-videos/#respond Tue, 09 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=7998 Python is a powerful programming language that works well in a variety of environments. Free Python compilers for Windows for running Python programs include PyScripter, PyDev, Jupyter Notebook, and many more. In addition, there is...

The post Become An Expert With A Python GUI Builder By Watching These 5 Videos first appeared on Python GUI.

]]>
Python is a powerful programming language that works well in a variety of environments. Free Python compilers for Windows for running Python programs include PyScripter, PyDev, Jupyter Notebook, and many more. In addition, there is a diverse range of options for a Python GUI builder.

The MIT license applies to PyScripter, an open-source, free Python compiler with a comprehensive set of great features. Kiriakos Vlahos developed PyScripter, and since 2015, more than 1.2 million downloads have taken place from the project’s SourceForge page. This article will discuss how to master the finest Python IDE for Windows by pointing you to some of the superb resources available.

What is an integrated development environment (IDE), and why do you need it?

Python GUI builder for macbook

A desktop application is an Integrated Development Environment (IDE) that offers features and tools for software development. A source code editor, a debugger, and a compiler are frequently included in IDEs. For functionality like code autocomplete, syntax labeling, and error detection, Python developers require an IDE. In addition, major Python libraries and frameworks support IDEs, making it simpler to create sophisticated applications by utilizing pre-existing algorithms and components. 

You could get by without an IDE in Python coding, but you would be severely lacking. Python programming is made simpler by a number of capabilities provided by IDEs, such as code completion, syntax highlighting, and error detection. Additionally, they offer built-in assistance for well-known Python libraries and frameworks, making creating sophisticated programs simpler.

What makes PyScripter the Best Python GUI builder?

To complement the outstanding Python for Delphi (P4D) components, PyScripter was first developed as a compact compiler to provide a reliable programming alternative for Delphi applications. Thanks to the assistance of Morgan Martinez, the developer of P4D, and a few early users, it has now developed into a fully functional standalone Python compiler. Python scripts may be used to expand it; it was created in Delphi using P4D and the SynEdit component.

Only Microsoft Windows operating systems are currently supported, and it features a modern user interface. It is quicker than other compilers due to the fact that it is created in a compiled language and has a wide range of qualities that make it an effective Python development environment.

Building a Python IDE that can compete with for-profit Windows-based IDEs for other languages is PyScripter’s goal. It is a fantastic tool with many lightweight, flexible, and extendable features. Additionally, it runs noticeably quicker because it was built from the ground up for Windows. It responds to user input on that platform than hefty text editors, all-purpose compilers, or other Python cross-platform IDEs.

Which videos will help me become a professional with Pyscripter?

Python GUI builder on macbook

Digital videos have an unmistakable impact on culture today. Millions of people daily visit online video-sharing platforms like YouTube. Because of their popularity, it seems that they will be included in the educational system.

Below are a few videos that can be watched to assist the viewer in using PyScripter, the best Python IDE. 

Getting to know PyScripter – webinar replay

Kiriakos Vlahos, also known as Mister PyScripter, was the keynote presenter of this webinar. He was accompanied by Kyle Wheeler, general manager of Embarcadero, and Jim McKeeth, developer advocate, for this engaging webinar. You can learn the fundamentals of using PyScripter, look at the new features included in version 4, pick up some productivity tips, and find out why Embarcadero sponsors PyScripter. To learn more about creating Python GUI applications, visit the PythonGUI blog.

Introduction to Python GUI Development with Delphi for Python – Part 1: Delphi VCL for Python

Discover how Embarcadero’s just-released free Python GUI modules provide Python the strength and adaptability of Delphi’s GUI frameworks. The GUI libraries VCL and FireMonkey (FMX) are established. While FireMonkey offers a robust, adaptable GUI framework for Windows, Linux, macOS, and Android, VCL focuses on native Windows development. The webinar is divided into two parts. First, you will learn about these new, free Python modules in this webinar and how to utilize them to create graphical user interfaces in Python. Then, you can use Python to target Android GUI applications in Part 2!

Python native Windows GUI with Delphi VCL

User interfaces are sometimes necessary for applications. This video discusses Python with DelphiVCL. The VCL is an established native Windows GUI framework with a sizable library of integrated visual components and a strong selection of third-party components. Although it is the best framework for native Windows programs, how can Python users utilize it? The VCL is a premier package for creating native Windows GUIs with Python, thanks to the DelphiVCL Python package (based on the free Python4Delphi library). Delphi may be used to create the full GUI, while Python can be used to provide the logic. To know more, watch the webinar now!

Tkinter vs DelphiFMX in the Embarcadero Open Source stream

The stream specifically targets Python developers because it compares Tkinter with DelphiFMX for Python GUI development. An overview and comparison of the two libraries will be presented at the outset. The presenter will then address a few queries. These inquiries are what is new in DelphiFMX, and where may it be improved? After reviewing bugs and pull requests, the webinar will outline a roadmap for upcoming improvements. Future streams will feature other Python Ecosystem projects, non-Python applications, and even beloved community initiatives!

PyTorch for Delphi with the Python data sciences libraries – webinar replay

The videos we’ve already presented focus on the DelphiFMX Python Developer side of the Embarcadero Python Ecosystem. This video will examine the ecosystem’s Delphi (and maybe C++Builder) side.

This section examines the latest Python Data Sciences Libraries and associated projects, which greatly simplify writing Delphi code against Python libraries and facilitate deployment on Windows, Linux, macOS, and Android. Examples are using the Python Natural Language Toolkit with PyTorch, the package that powers applications like the Tesla Autopilot, Pyro from Uber, and Transformers from Hugging Face.

This is one in a series of regularly scheduled live streaming examining the most recent open source initiatives from Embarcadero. The event will be hosted by Jim McKeeth, who will be accompanied by participants from the open source projects’ communities and development teams, as well as representatives from Embarcadero and Idera’s product management. A wonderful chance to get a behind-the-scenes look at Embarcadero’s Open Source initiatives and influence their future.

You should attend this webinar if you are passionate about machine learning, artificial intelligence, or data sciences.

Getting Started with Python4Delphi

Last but not least, this short video deals with a few questions regarding installing components and getting started. 

Why is PyScripter the best Python IDE for Windows?

Python GUI builder for you

With PyScripter as your primary Python compiler, you get various features. For example, you can visualize your data easily. Data visualization attempts to understand data by placing it in a clear context and aiming to discern patterns, trends, and otherwise invisible relationships. Excellent graphing tools with a variety of features are available in Python. Python offers a great library for you whether you want to create interactive plots or completely customized ones.

Matplotlib, which is low-level and flexible, Pandas Visualization, which is based on Matplotlib, Seaborn, which has a high-level interface and excellent default styles, plotnine, which is based on R’s ggplot2, which uses Grammar of Graphics, Plotly, which can create interactive plots and Bokeh are a few well-known plotting libraries in Python.

Now that we have given you the videos which can easily make you an expert with PyScripter do not spend too long thinking. Download PyScripter now and start coding!

The post Become An Expert With A Python GUI Builder By Watching These 5 Videos first appeared on Python GUI.

]]>
https://pythongui.org/become-an-expert-with-a-python-gui-builder-by-watching-these-5-videos/feed/ 0 7998
Python Get Request vs. Post Requests: What’s The Difference? https://pythongui.org/python-get-request-vs-post-requests-whats-the-difference/ https://pythongui.org/python-get-request-vs-post-requests-whats-the-difference/#respond Mon, 08 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=8044 When users are ‘surfing the net’ and browsing web pages and interacting with web resources a number of things are actually happening which are not always obvious. Python often plays a large part in this...

The post Python Get Request vs. Post Requests: What’s The Difference? first appeared on Python GUI.

]]>
When users are ‘surfing the net’ and browsing web pages and interacting with web resources a number of things are actually happening which are not always obvious. Python often plays a large part in this thanks to Python’s popularity. Understanding what goes on for Python get request and post request handling and the differences between the two helps us write better software and demystifies the ‘nuts and bolts’ of the internet so we can make better use of it. This is especially useful when we are trying to interact with a REST server. Read on to find out how PyScripter, the best Windows 10 IDE for Python (or indeed any version of Windows), offers numerous advantages which help us write, debug and understand how a Python Get request works.

What part does Python Get request play in internet communications?

The web server software on the web server computer receives an HTTP request from a client PC or device. The request is made to access a server resource such as a web page, image, sound file, movie or indeed almost anything which can be carried across the internet. A URL (Uniform Resource Locator), which contains the data required to access the resource, is used by the client to submit the request. The main or most often used are the POST, GET, PUT, PATCH, and DELETE HTTP methods. Each method performs a particular action; for instance, the Python get request function enables you to get data from a data source using the internet.

This article will focus on two popular Python request modules; GET and POST requests.

What is a REST API?

A REST API, commonly referred to as a RESTful API, is a web API that complies with the restrictions of the REST architectural style and enables communication with RESTful web services. Computer scientist Roy Fielding came up with the acronym REST, which stands for representational state transfer.

Learn more about REST APIs by visiting the blog and reading some of our great articles which will teach you all about them.

What is a HTTP Request?

The client-server architecture is used by the HTTP protocol or hypertext transfer protocol. Typically, the server is the machine hosting the website, and the client is the web browser. For making HTTP requests in Python, we utilize the requests module. In addition to handling request and response data, it can handle many other elements of HTTP communication. Authentication, compression, decompression, chunked requests, etc., are all supported.

In the form of a request message with the following format, an HTTP client delivers an HTTP request to a server:

  • A Request-line
  • Zero or more header (General|Request|Entity) fields followed by CRLF
  • An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields
  • Optionally a message-body

Request-line

The Request-Line starts with a method token, then lists the Request-URI, protocol version, and CRLF at the end. Space SP letters are used to separate the components.

Request-Line = Method SP Request-URI SP HTTP-Version CRLF

Which HTTP request methods are available?

The request method indicates the method to be performed on the resource identified by the given Request-URI. The method is case-sensitive and should always be mentioned in uppercase. All the supported methods in HTTP/1.1 are listed below:

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • CONNECT
  • TRACE

As mentioned earlier, we are only going to focus on the difference between GET and POST request methods.

What is the GET Method and how does it work?

Information may be retrieved from a server using a provided URI and the GET technique. Data should only be retrieved and not changed in any other way by GET requests.

An example of making a GET Request is shown below:

# importing the requests library
import requests

# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"

# location is given here
location = "delhi technological university"

# defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}

# sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)

# extracting data in json format
data = r.json()

# extracting latitude, longitude, and formatted address
# of the first matching location
latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']

# printing the output
print("Latitude:%snLongitude:%snFormatted Address:%s"
%(latitude, longitude,formatted_address))

The above example makes a GET request to the Google Maps API to obtain a particular place’s latitude, longitude, and formatted address.

What is the POST Method and how does it work?

A POST request is utilized when sending data to the server via HTML forms, such as customer information, file uploads, etc.

An example of making a POST Request is shown below:

# importing the requests library
import requests

# defining the api-endpoint
API_ENDPOINT = "http://pastebin.com/api/api_post.php"

# your API key here
API_KEY = "XXXXXXXXXXXXXXXXX"

# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''

# data to be sent to api
data = {'api_dev_key':API_KEY,
'api_option':'paste',
'api_paste_code':source_code,
'api_paste_format':'python'}

# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)

# extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)

By submitting a POST request to the PASTEBIN API, this example demonstrates how to post your source code to pastebin.com.

What is the difference between HTTP GET and POST requests?

What is the role played by Get and Post methods for Form submission?

METHOD="GET" and METHOD="POST" are fundamentally distinct since they relate to various HTTP requests specified in the HTTP standards. Both techniques start by having the browser create a form data set, which is subsequently encoded according to the enctype attribute’s instructions. While only application/x-www-form-urlencoded is permitted for METHOD="GET”, the enctype attribute for METHOD="POST” can be either multipart/form-data or application/x-www-form-urlencoded. The server receives this collection of form data once it has been sent.

When METHOD=”GET” is used to submit a form, the browser creates a URL by first adding a “?” to the value of the action attribute, then attaching the form’s data set (which is encoded using the application/x-www-form-urlencoded content type). The browser then processes this URL as though it were a link.

When a form with METHOD="POST" is submitted, a POST request is made using the action attribute’s value and a message constructed using the enctype attribute’s specified content type.

How do Python GET requests and POST requests work differently for Server-side processing?

In theory, whether a form submission is processed depends on whether it uses METHOD="GET" or METHOD="POST" to send the data. Different decoding techniques are required since the data is encoded in various ways. So, generally speaking, altering the METHOD could require altering the script that handles submissions. For instance, when utilizing the CGI interface, the script receives the data when GET is used in an environment variable (QUERYSTRING). However, when POST is used, form data is sent via the standard input stream (stdin), and the Content-length header specifies how many bytes must be read.

GET and POST variables confliction

In certain languages, like PHP, the data from the GET and POST parameters are available independently and merged into a convenience variable. In PHP, this variable is called $_REQUEST. If a conflict arises—when the same parameter name is used with different values in GET and POST—the dispute is addressed according to a set of criteria. The variables order configuration directive in PHP determines the order of priority. EGPCS is the default order (environment, GET, POST, Cookie, Server). This indicates that a variable in $_GET takes priority over a variable in $_POST, which takes precedence over a variable in $_COOKIE.

What is the recommended usage of a Python GET request compared to a POST request?

When sending “idempotent” forms, or ones that don’t “substantially affect the condition of the world,” GET is advised. The use of POST is advised when database changes or other operations are involved.

In contrast to “POST” requests, “GET” requests are frequently cacheable. Since caches could service the most common searches, this might significantly affect query systems’ efficiency, especially if the query strings are short. Even for idempotent requests, utilizing POST is sometimes advised.

Even for idempotent requests, utilizing POST is sometimes advised:

  1. METHOD="GET" is not applicable if the form data contains non-ASCII characters, such as accented characters, even if it could function in reality (mainly for ISO Latin 1 characters).
  2. When dealing with implementations that cannot handle URLs that are lengthy, METHOD="GET" may become problematic if the form data set is large—say, hundreds of characters.
  3. Avoiding METHOD="GET" will help users understand how the form works and will make “hidden” fields (INPUT TYPE="HIDDEN") even more hidden because they won’t be included in the URL. However, hidden fields will still be visible in the HTML source code even if you use METHOD="POST."

Why should I use PyScripter as my Python IDE?

MIT-licensed PyScripter is a lightweight, feature-rich, free, open-source Python-specific IDE created by Kiriakos Vlahos, who previously created Python4Delphi. This library connects Python and Object Pascal in Delphi, and since 2015, the project’s SourceForge website has only had about 1.2 million downloads. It is made in Delphi with the help of SynEdit, a sophisticated multi-line edit control created in Pascal.

A robust, lightweight, adaptable, and flexible Python IDE is PyScripter. Since it was designed only for Windows systems, it operates there more quickly and effectively than bloated text editors, all-purpose IDEs, or other Python cross-platform IDEs.

Now you know the difference between GET and POST request methods. Click here to start using the best free python IDE straight away.

The post Python Get Request vs. Post Requests: What’s The Difference? first appeared on Python GUI.

]]>
https://pythongui.org/python-get-request-vs-post-requests-whats-the-difference/feed/ 0 8044
PyScripter vs. Spyder – Best Python Coding IDE? https://pythongui.org/pyscripter-vs-spyder-best-python-coding-ide/ https://pythongui.org/pyscripter-vs-spyder-best-python-coding-ide/#respond Fri, 05 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=7500 Python is a high-level programming language that may be used to create various applications, including web apps, software and game development, network programming, graphical user interfaces (GUIs), scientific and quantitative applications, and more. Python’s popularity...

The post PyScripter vs. Spyder – Best Python Coding IDE? first appeared on Python GUI.

]]>
Python is a high-level programming language that may be used to create various applications, including web apps, software and game development, network programming, graphical user interfaces (GUIs), scientific and quantitative applications, and more. Python’s popularity has risen because of its simplicity, clarity of syntax, dynamic community, and versatility. However, if you are a beginner setting up an effective development environment can be tricky (here is a step-by-step guide to help you get started with Python). Consequently, there is a lot of Python coding software on the market right now, which new developers can learn and use. As a result, choosing the best IDE for software development becomes a critical task for which PyScripter and Spyder are fantastic options.

This article will explore two Python coding software, namely PyScripter and Spyder, their pros and cons, and which is the best IDE in the market.

What meaningful features do the IDEs offer?

PyScripter vs. Spyder - Best Python Coding IDE? What meaningful features-do the PyScripter or Spyder offer?

Users rate PyScripter and Sublime Text highly for writing a Python script due to their valuable features. Even though they have several basic similar features, let’s look at some that can help differentiate the two.

Are the IDEs lightweight? 

IDEs (integrated development environments) are programs that assist in creating other programs. IDEs also make an effort to combine all programming tasks into a single application. One of the most important features of an IDE is that it provides a consolidated interface for all of a developer’s tools. But not all IDEs are created equal.

A lightweight IDE is faster, more elegant, and makes the design process easier for developers. A lightweight IDE also works on a project level, loading significantly more data at the start, analyzing the project structure if necessary, etc. As a result, picking a decent IDE is crucial. Fortunately, the best IDEs are lightweight, and PyScripter is no exception.

PyScripter is a native lightweight IDE which makes it superior to other offerings in the market, thus making it a favorite amongst developers. In contrast, Spyder is not a lightweight IDE.

Which of the two IDEs is easy to use and set up? 

When it comes to IDEs, ease of use and setup are critical. As a result, developers are at odds when deciding which IDE to utilize. There are numerous excellent IDEs and text editors on the market. None, however, comes close to matching PyScripter’s excellence.

Spyder is a good contender when it comes to ease of use. It is ready to install IDE, making it a pretty popular IDE. Furthermore, it is also relatively easy to install and run. Similarly, PyScripter is also a ready-to-install IDE, but PyScripter also adds multiple additional functionalities while being lightweight. This makes it extremely popular amongst coders and developers.

Do the two IDEs support real-time collaboration?

Collaborative coding tools are programs that allow programmers to collaborate on code remotely. Real-time code collaboration has grown quickly in recent years, changing how engineers work within teams working on the same code base. Moreover, a good developer today is expected to code with real-time collaboration. Thus, developers must choose and get familiar with IDEs that offer real-time collaboration.

PyScripter has this fantastic feature, but IDLE does not. Consequently, PyScripter has become a popular choice amongst aspiring developers and seasoned developers alike.

Are PyScripter and Spyder community-based IDEs?

Individuals can participate and feel responsible for their growth when the community is in charge. As a result, communities respect development projects that integrate community input, foster consensus, and create a strong feeling of ownership.

You will surely confront obstacles as a Python coder. Furthermore, if you’re not sure what’s wrong, seek up the error message on the internet. An IDE-supported developer community can be advantageous because it usually addresses problems more quickly and efficiently. Therefore, since Pyscripter is a community-driven project, it is more beneficial for developers than Spyder. 

Do the IDEs support unit testing?

Software testing is an extensive process requiring lengthy processes, each with numerous steps. On the other hand, unit testing is an essential part of the software development process since it ensures that only the best products reach the end-user. Moreover, Unit testing also determines if programs and apps meet the needs of their users.

Its main purpose is to ensure that each component works properly and as planned. Moreover, The entire system can only function properly if all individual elements are in good working order. The program developers themselves do unit testing. Therefore, these tests are sometimes carried out by independent software testers.

PyScripter ensures that tests are generated automatically, allowing for automated unit testing. This IDE also has a fantastic unit testing interface. Furthermore, its unit tests window provides a sophisticated graphical user interface, a common Python module, for conducting unit tests. For further information, consult the official documentation.

These unit testing features are even available to Python developers on Spyder. However, PyScripter offers additional functionality making it the better option for unit testing.

Which IDE supports different themes and customizability? 

Many developers neglect the feature of theme support in an IDE. Developers can customize the appearance of their IDE by choosing from a variety of themes. Furthermore, this leads to a better and more balanced user experience.

PyScripter includes a variety of dark and light editor themes (editor syntax coloring). You can also choose between dark and light styles for the application’s user interface using the View, Select style menu command. To change the editor theme, open the Editor Options, go to the Color Theme tab, select the theme you want, and click the “Apply Theme” button. Furthermore, you may find that, while you enjoy a theme’s color scheme, the background is too dark or light for your tastes. Changing the darkness of a theme is fairly simple.

Unfortunately, Spyder is not customizable, nor does it support different themes. Thus, PyScripter, by default, becomes the better choice.

Does the IDE support an interactive development environment? 

Python is an interpretative language, which means it executes each line of code sequentially. As we all know, computers can only understand machine language, commonly known as binary language. As a result, every time you run a Python script, the Python interpreter converts user-written Python code into a language that computer hardware or systems understand. In addition, one of the interpreter’s benefits is that you can start an interactive session with it and test it using Python code. This is an excellent way to put new programming principles to the test.

To view the output of a specific piece of code, most IDEs need you to run Python. Like many other IDEs, Spyder can evaluate Python statements while giving you real-time feedback and preserving your changes. PyScripter, on the other hand, evaluates inline Python statements without the need for breakpoints. It provides instant feedback, but since it is lightweight, which Spyder is not, it provides quicker and more accurate feedback.

Do the IDEs support web development?

A web development IDE is a powerful tool that includes features like autocomplete, grammar checking, debugger, suggestion, and seeing a live web page within the IDE to understand the output better. However, there is no predetermined list of features that should be included in an IDE’s arsenal.

Spyder is not a web development IDE, although PyScripter is.

Which is the best Python coding software IDE?

PyScripter vs. Spyder - Best Python Coding IDE? A picture of a laptop on a desk with the laptop's browser window open to the download page for the Embarcadero Python tools

In this article, we went over the features presented by both IDEs. Looking at the article, we see that PyScripter offers all Spyder’s capabilities, plus much more.

PyScripter is an open-source Python Integrated Development Environment (IDE) that aims to compete with commercial IDEs for other languages in terms of features. It is feature-rich while being lightweight. This lightweight IDE contains all of the functionality you’d expect from a modern Python IDE. It’s also natively compiled for Windows to use the least amount of memory while providing the best performance. PyScripter is a Delphi application with Python script extensibility.

PyScipter will forever change the way you program in Python. To join us and experience the greatness of PyScripter, the best Python IDE available, click here.

The post PyScripter vs. Spyder – Best Python Coding IDE? first appeared on Python GUI.

]]>
https://pythongui.org/pyscripter-vs-spyder-best-python-coding-ide/feed/ 0 7500
What Are Python Native Development Tools? https://pythongui.org/what-are-python-native-development-tools/ https://pythongui.org/what-are-python-native-development-tools/#respond Thu, 04 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=7733 In the modern world, Python has become one of the most popular and widely used programming languages. As a result, it is sparking a movement to increase interest in coding and programming. In addition, because...

The post What Are Python Native Development Tools? first appeared on Python GUI.

]]>
In the modern world, Python has become one of the most popular and widely used programming languages. As a result, it is sparking a movement to increase interest in coding and programming. In addition, because of its ease of use and tens of thousands of libraries, it is a multi-purpose programming language for data visualization, GUI applications, online applications, artificial intelligence, deep learning, and other applications. Python development tools, its IDEs (one of the finest alternatives is PyScripter), and code editors extend the programming language’s capabilities, whether the necessity is for scalability, dependability, or processing. As a result, to get the most out of the language, developers should become acquainted with different Python Native development tools.

Python’s increasing popularity can be attributed to its easy syntax, which appeals to experienced and novice programmers. In addition, its growing and the active community helps enhance the Python user experience. In this article, we’ll look at several fantastic Python development tools that can help you become a better Python programmer.

Why do you need a good Python IDE?

What Are Python Native Development Tools? - Why Do You Need a Good Python IDE

The acronym IDE stands for Integrated Development Environment. It is a coding tool that simplifies code writing, testing, and debugging by utilizing highlighting, resource management, compilers, debugging tools, and other software development demands. Although the IDE is a well-defined concept, it is being redefined as alternative tools, such as notebooks, obtain features formerly available solely in IDEs. This application integrates several technologies created expressly for software development.

As a result, your IDE will be necessary from the outset. IDEs are normally selected based on the preferences of the developer. However, some are better suited for specific tasks than others. Moreover, It’s also worth mentioning that switching between the two is simple. In addition, It’s as simple as starting a text document in Microsoft Word or Notepad, so choosing which to use is straightforward. You’ll probably try a few different ones until you find one that works. But before that, it is important to master the basics of Python.

Having said that, PyScripter is a well-known and well-liked Python IDE.

Why is PyScripter an important native development tool?

What Are Python Native Development Tools? Why is PyScripter an Important Native Development Tool

PyScripter is a free, open-source Python IDE that includes a wide range of MIT-licensed functionality. Kiriakos Vlahos created PyScripter, and the project’s SourceForge website has seen over 1.2 million downloads since 2015. This software began as a basic IDE to supplement the great Python for Delphi (P4D) components by offering a powerful scripting solution for Delphi applications.

PyScripter, among many other IDEs, has a modern user interface and is currently only available for Microsoft Windows operating systems. However, it is faster than some of the other IDEs because it is written in a compiled language and has a wide range of capabilities that make it an ideal Python programming environment.

PyScripter’s features include brace highlighting, code folding, code completion, and syntax checking as you type. Furthermore, the use of Python source code tools simplifies programming for programmers. Finally, PyScripter allows you to drag and drop files from Explorer into this IDE, which could save you time.

This excellent IDE aims to produce a Python IDE that can compete with typical Windows-based IDEs for other languages. PyScripter is excellent software. With many characteristics, it is lightweight, adaptable, and expandable. In addition, it is significantly faster and highly responsive than other clunky text editors, general-purpose IDEs, or other Python cross-platform IDEs because it was created from the ground up for Windows. You can learn more about PyScripter here.

What is Pyhon4Delphi?

What Are Python Native Development Tools? What is Pyhon4Delphi

Consider integrating Delphi’s GUI and desktop app development power with Python in your applications to give world-class solutions to your clients’ needs. Python4Delphi is the answer to your prayers.

Python for Delphi (P4D) is a free Delphi and Lazarus component library that wraps the Python DLL (FPC). In addition, they make it simple to run Python programs while also allowing for creating new Python modules and types.

Furthermore, the best feature of P4D is that it simplifies Python as a scripting language for Delphi applications. Moreover, It also includes a plethora of customized examples and tutorials that are ready to use in the development of real-world apps. In a word, P4D offers a selection of real-world apps that can be modified to your individual needs and used in Python GUI.

Why is DelphiVCL a valuable Python native development tool?

What Are Python Native Development Tools? Why is DelphiVCL a Valuable Python Native Development Tool

Thousands of Delphi and C++Builder developers rely on mature GUI libraries like VCL and FireMonkey(FMX). DelphiVCL and DelphiFMX Python libraries are a collection of Python modules that give Python programmers access to the powerful and mature VCL and FireMonkey (FMX) graphical user interface frameworks.

The Visual Component Library (VCL) is a collection of visual components designed to aid in the rapid development of Windows applications using the Delphi programming language. VCL provides a diverse set of visual, non-visual, and utility classes for Windows application development, web development, database development, and console development.

DelphiVCL for Python focuses on native Windows programming and leverages the VCL framework for Windows entirely to provide a complete and versatile GUI framework for Windows, Linux, macOS, and Android.

Although prior Delphi expertise is beneficial when working with these libraries, it is not required when using the VCL library for Python programming.

Learn more about VCL here.

What makes DelphiFMX a useful Python tool?

FireMonkey (FMX) Stencils are available for designers collaborating with developers to create multi-device apps utilizing RAD Studio, Delphi, or C++Builder. In addition, they increase communication between designers and developers, making taking advantage of the FMX Framework’s UI components and styles’ unlimited creative possibilities even easier.


FMX Stencils also allows users to generate wireframes and mockups with applications like Balsamiq, Sketch, Photoshop, Illustrator, and others. The FMX components were generated in vector format and styled to match the available themes. In addition, the symbols and smart vector objects are labeled in line with FMX naming conventions, ensuring that designers and developers use the same terminology and preventing misunderstanding-related problems.

FireMonkey is Delphi’s cross-platform GUI library (FMX). It uses OpenGL or DirectX GPU hardware acceleration to produce clean, modern, high-performance user interfaces. DelphiFMX Python development is supported on Windows, macOS, Linux, and Android. In addition, it includes a powerful style system that the user can tweak.

Do you now know all about the best Python development tools?

What Are Python Native Development Tools? Do You Now know All About The Best Python Development Tools

Delphi’s Windows development tools have been enormously successful, and the company is now applying that knowledge to Python GUI development. Delphi’s Python tools assist you in creating beautiful and powerful GUIs for your applications due to the superb underlying architecture and meticulous attention to detail. In addition, it offers enterprise-ready capabilities through visual and functional components and complete control over the final user interface.

Its Python tools can also be used to construct professional-looking applications for various platforms. Quality is a primary priority for DelhiVCL and DelphiFMX, and their integration with respective operating systems offers an added layer of protection. For a pleasant GUI experience, DelhiFMX may even utilize the GPU hardware capabilities of the user’s GPU.

User interface design does not have to be tough. A range of Python tools is accessible as pip packages. DelphiFMX is a strong tool with several capabilities and customizability options. It is highly recommended for Windows-only developers due to its inherent support for hardware acceleration. Furthermore, PyScipter is the best IDE for making the most of these modules.

Now that you know about the best Python development tools, It’s time to put your knowledge to action. So click here and explore how Delphi’s Python tools.

The post What Are Python Native Development Tools? first appeared on Python GUI.

]]>
https://pythongui.org/what-are-python-native-development-tools/feed/ 0 7733
5 Real-Life Lessons About The Best IDE for Python https://pythongui.org/5-real-life-lessons-about-the-best-ide-for-python/ https://pythongui.org/5-real-life-lessons-about-the-best-ide-for-python/#respond Wed, 03 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=7980 The technological environment of today requires computer programming. Learning programming fundamentals will make you stand out and give you an edge over the competition. Python is perhaps the most popular and widely used programming language...

The post 5 Real-Life Lessons About The Best IDE for Python first appeared on Python GUI.

]]>
The technological environment of today requires computer programming. Learning programming fundamentals will make you stand out and give you an edge over the competition. Python is perhaps the most popular and widely used programming language today. It is appropriate for many applications thanks to its high-level, interpreted, and object-oriented architecture. Additionally, Python’s focus on readability, syntax, program modularity, and code reuse significantly speed up program development while lowering maintenance costs. Moreover, Python’s ability highly depends on the IDE so it is very important to know the best IDE for Python. Python is perhaps the most versatile language and has led to an increase in the search for “Python IDE download.”

The increased demand for Python across the globe has led to the creation of many of the best Python IDEs. A Python IDE with many features made available under the MIT license is PyScripter, which is free and open-source. In addition to an overview of the top Python coding tools, this article will offer tips for using Python for complete beginners. So let’s Python IDE download and get started!

Why is Pyscripter gaining so much popularity?

best IDE for Python on pc

A Python IDE with many features made available under the MIT license is PyScripter, which is free and open-source. Kiriakos Vlahos developed PyScripter; since 2015, more than 1.2 million people have downloaded it from the project’s SourceForge website. This program started out as a simple IDE to support the fantastic Python for Delphi (P4D) components by offering a powerful scripting solution for Delphi programs.

Thanks to Morgan Martinez, the developer of P4D, and a few early adopters, it has now developed into a fully functional standalone Python IDE. In addition, Python scripts can be used to extend it; it was created in Delphi using P4D and the SynEdit component.

Only the Microsoft Windows operating system is supported by PyScripter, which has a modern user interface. However, it is quicker than some of the other IDEs because it is written in a compiled language and has a wide range of features that make it a good Python programming environment.

This great IDE strives to create a Python IDE that can compete with other languages’ traditional Windows-based IDEs. The tool PyScripter is fantastic. Rich in features, portable, flexible, and expandable. Because it was built from the ground up for Windows, it is noticeably quicker and more responsive than large text editors, general-purpose IDEs, or other Python cross-platform IDEs.

1. How to use PyScripter as an interpreter?

An integrated Python interpreter provided by PyScripter may be of great assistance. Users can run Python scripts without saving them using this interpreter, providing call suggestions and code completion advice. The user can also access PyScripter’s complete command history (all commands executed in the interactive Python session).

2. Does PyScripter support debugging?

One key feature many developers find particularly helpful when debugging apps is walking through your script as it executes. As a result, this feature is included as a standard in most excellent coding software.

A Python interpreter is already included in PyScripter for quick call hints and code completion. This program lets you run scripts without storing them and keeps track of your command history. Additionally, a remote Python debugger is supported by this IDE, allowing Python debugging. The user can see variables, the watch window, and the call stack. Debugging can be assisted by conditional breakpoints or thread debugging. Instances where the programmer cannot find the error in his code can also benefit from debugger indications. Your files can not only be executed without being saved but they can also be debugged without being saved, which is a nice bonus.

3. How to use PyScripter as a syntax highlighting editor?

One of PyScriptor’s most fundamental yet crucial features is split view/side-by-side file editing. Additionally, it provides the user with total support for encoded Python source files.

PyScripter offers nice features, including brace highlighting, code folding, code completion, and syntax checking as you type. To master this software, a programmer ought to investigate that. Additional ease of use for a programmer is added by the use of Python source code utilities, such as (un)tabify, (un)comment, (un)indent, etc. Finally, you might save a lot of time using this IDE to handle files dropped from Explorer, making it unquestionably the best IDE for Python.

4. Can you run unit tests using PyScipter?

Unit testing significantly raises the quality of the code. Additionally, it helps developers find even the smallest errors that might be present in units before integration testing. Unit testing also helps in the early detection of various software flaws. As a result, software engineers can take care of those problems before continuing. The main advantage of handling errors early with unit testing is that no other software components are impacted later in the project. As a result, the design process is completed with greater efficiency, less downtime, and lower costs than would otherwise be required.

According to Python developers, one of the top Python testing tools for software development is PyScipter.

You can carry out automated unit testing thanks to PyScripter’s automatic test generation. The unit testing GUI that comes with this IDE is excellent. Additionally, it provides a sophisticated graphical user interface for running unit tests, a common Python module, in its unit tests window.

The two most important toolbar buttons on this window are Refresh and Run.

Refreshing the unit test window loads the PyScripter unit tests for the active module. It’s important to note that this necessitates importing the module into the built-in interpreter. Use the provided tree view to select (check) the tests you want to run after loading a module. You can access the test method or class declaration in the source code by double-clicking on the name of a test or test class.

Run executes the chosen tests, making it easy to use. In the tree view, the test’s status following execution is indicated by the color next. For instance, the colors green and purple indicate success, and the color red indicates a Python exception (i.e., any other error). The aggregate statistics are immediately below the tree view, and you can read information about the errors made by clicking on the failed tests.

5. Do you know of some other unique features that Pyscripter offers?

PyScripter functions as a project manager and lets you import multiple run configurations and existing directories. This software has a highly developed GUI for unit testing and has many native Python development tools. Programmers can further improve the quality of the software by integrating PyScripter with Python tools like PyLint, TabNanny, Profile, etc. The IDE’s powerful parameter functionality for tailored external tool integration should be noted.

To become an expert in Python programming software, a programmer needs to be familiar with several features that PyScripter offers. Some of these are as follows: 

  • Code Explorer.
  • Find and Replace in Files Menu.
  • The Integrated regular expression testing module.
  • The ability to alter the choice of Python version to run through the command line parameters.
  • The ability to Run Python Scripts externally.
  • Ease of Find Definition/Find references in the IDE.
  • Highly modern GUI with docked forms and configurable look and feel (themes).

Do you want to put what you have learned into action?

best IDE for Python for mac

Python is important because more and more computing and scientific applications are using it, as shown by the growth of analytics and business intelligence. Managing your coding projects is simple and quick with a good Python IDE. The best IDE, however, is Pyscripter, which includes tools like a debugger and code recommendations. Additionally, it is quicker than some other Python IDEs because it was written in a compiled language. A great Python programming environment, it has a tonne of cool features.

Now you know all the Real-Life lessons about the Best IDE. So, click here to start your journey with the best Python programming software.

The post 5 Real-Life Lessons About The Best IDE for Python first appeared on Python GUI.

]]>
https://pythongui.org/5-real-life-lessons-about-the-best-ide-for-python/feed/ 0 7980
24 Hours to Improving A Python GUI https://pythongui.org/24-hours-to-improving-a-python-gui/ https://pythongui.org/24-hours-to-improving-a-python-gui/#respond Tue, 02 Aug 2022 10:00:00 +0000 https://pythongui.org/?p=7974 Since its first release, Python has become one of the most potent programming languages. It has become a favorite among various developer communities due to its straightforward syntax and strong object-oriented nature. Python GUI is...

The post 24 Hours to Improving A Python GUI first appeared on Python GUI.

]]>
Since its first release, Python has become one of the most potent programming languages. It has become a favorite among various developer communities due to its straightforward syntax and strong object-oriented nature. Python GUI is one area of development which has experienced greatly increased interest. An application’s user interface and experience are crucial to its commercial success, so developers are constantly on the lookout for reliable technologies for these elements since Python tools have more advantages than many other GUI technologies and is the reason why many people rely on a free Python IDE.

You can create visually appealing GUIs for your Python applications with the aid of various development frameworks and libraries. However, the majority entail a fair number of concessions and costs. Therefore, most seasoned developers suggest using a well-liked technology, such as the Python GUI tools in Delphi. By utilizing this technology, you can gain access to libraries that streamline the development process and support the creation of memorable user interfaces. This article will take you through the necessary details you ought to know about Python GUI development tools and how to improve a Python GUI quickly with a free Python IDE.

What are some important tools that can revamp your Python GUI? 

24 Hours to Improving A Python GUI - Python GUI on a laptop

What things should you look for in a Python GUI tool? 

A good GUI tool must be robust and scalable. You must ensure that any development tool can provide performance at all times. The reliability of your development technologies determines the reliability of your applications. As a result, your Python tools must provide consistent GUI performance throughout. 

It must have a modern appearance and functionality. Your Python tools will heavily influence the quality of the GUI you create. Not all will provide a user interface that is both clean and appealing enough to stand out. 

Finally, it must provide development support across all platforms. Python is a highly versatile and robust programming language developed for all major platforms. You can create applications for not only Windows but also Android, macOS, and Linux with the correct Python tools. Check out this beginner’s guide to Python tools to learn more.

What is Python4Delphi?

Python has many tools that help build GUI’s but none of them compared to Python4Delphi. Python4Delphi (P4D) is a well-rounded solution to all your programming problems. It is the most popular among Python developers because it combines Python with Delphi’s GUI functionality to produce stunning results. It is a collection of free Lazarus and Delphi components that make it simple to create any Python module. The best thing about P4D is its simple use of Python as a programming language. There are countless customizable tutorials available to assist you if you get stuck.

How can you use DelphiVCL to improve your Python GUI? 

DelphiVCL is a Python module that provides Python GUI apps access to Delphi’s VCL for robust and high-performance native Windows visual widgets. It connects Delphi’s VCL (Visual Component Library) and Python with the Python4Delphi library. For the time being, DelphiVCL is only available for Windows.

The Python DelphiVCL module allows you to use Python to access the entire VCL! You don’t need any Delphi or Object Pascal experience or knowledge to take full advantage of the Native GUI benefits as a Python developer.

VCL is a set of visual components for developing Windows applications quickly using the Delphi and C++ programming languages. VCL includes several visual, non-visual, and utility classes that can be used to create Windows applications, web applications, database applications, and console applications. TObject is the ancestor of all VCL classes. In addition, TObject introduces methods for basic behavior such as construction, destruction, and message handling.

You can quickly execute Python scripts and create new Python modules and types by integrating them with Python using Python for Delphi (P4D). P4D makes Python a simple scripting language for Delphi applications. It also includes many ready-to-use demos and tutorials created to solve real-world problems.

Can DelphiFMX enhance my Python GUI? 

DelphiFMX uses GPU libraries to provide a hardware-accelerated, rich user interface that runs fast and looks great on Windows, macOS, iOS, Android, and Linux. On Windows, it uses DirectX, Linux uses OpenGL, Android uses OpenGL-ES, and iOS and macOS use Metal. Although FMX and VCL are similar, they are not designed to work together. Instead, they have been built from the ground up to be cross-platform solutions.

It has integrated GPU effects, animations, and a robust styling system. It also has a highly adaptable component system, allowing you to accomplish more with fewer parts. In addition, platform services from DelphiFMX allow the UI and UX to intelligently adapt to platform differences, making it one of the fastest GUI experiences on the market.

How can PyScripter help you in adding value to your Python GUI?

PyScripter is frequently regarded as the best Python IDE. Embarcadero sponsors this popular, free, and open-source Python IDE. This IDE has all the features you’d expect from a modern Python IDE but is also very light and fast. PyScipter is natively compiled for Windows, which allows it to use minimal memory while providing maximum performance. It also includes full Python debugging, both locally and remotely. Another notable feature of this IDE is its integration with Python tools such as PyLint, TabNanny, Profile, etc. You can also use it to run or debug files directly from memory.

A Python interpreter that offers call indications and code completion is built into PyScripter. This program allows you to run scripts without saving them and keeps track of your command history. For debugging Python code, this IDE also has a remote Python debugger. As a result, it is possible to see variables, the watch window, and the call stack. Conditional breakpoints and thread debugging are additional tools for debugging. Debugger indications are also helpful when the programmer cannot find the error in his code. It is a useful feature; the ability to debug your files without saving them in addition to being able to destroy them.

PyScripter includes every feature of a professional IDE, including brace highlighting, code folding, code completion, and syntax checking as you type. Additionally, it supports features you’d expect to find in a legitimate native app, like the ability to drag and drop files into the PyScripter IDE. These features all work together to save time and make the development process easy and enjoyable.

Are you ready to use Delphi4Python?

24 Hours to Improving A Python GUI - a man holding up a laptop like his favorite cake. He is smiling at the laptop screen which is showing the DelphiVCL and DelphiFMX download page.

It’s easier and faster to learn Delphi and create native GUI apps. Python has many packages to help developers with everything from basic programming to advanced Scientific, Machine Learning, Artificial Intelligence, and Deep Learning tasks. Users can create ultra-fast native GUI apps by combining the strengths of Delphi and Python. 

Delphi has had great success with its Windows development tools and is now applying that knowledge to Python GUI development. Delphi’s Python tools enable you to create stunning and potent GUIs for your applications, thanks to the excellent underlying architecture and meticulous attention to detail. It offers enterprise-ready functionality through visual and functional elements and overall control over the finished user interface. Additionally, PyScipter is the best IDE for optimizing the use of these modules.

Now that you’ve learned about the most important ways to improve your Python GUIs click here and use the best IDE to work on your Python GUIs.

The post 24 Hours to Improving A Python GUI first appeared on Python GUI.

]]>
https://pythongui.org/24-hours-to-improving-a-python-gui/feed/ 0 7974
Python GUI: Expectations vs. Reality https://pythongui.org/python-gui-expectations-vs-reality/ https://pythongui.org/python-gui-expectations-vs-reality/#respond Mon, 01 Aug 2022 18:00:49 +0000 https://pythongui.org/?p=7967 Python has become a top choice for managing infrastructure, creating modern software, and analyzing data. It is no longer an obscure utility language but a powerful force in developing web applications and systems administration. Python...

The post Python GUI: Expectations vs. Reality first appeared on Python GUI.

]]>
Python has become a top choice for managing infrastructure, creating modern software, and analyzing data. It is no longer an obscure utility language but a powerful force in developing web applications and systems administration. Python is a key driver in big data analytics and the artificial intelligence explosion. Moreover, it is a programming language that allows for interactive design, and its vast array of tools and frameworks has resulted in an increase in Python download for Windows. It has a large selection of Python GUI (Graphical User Interface) framework options helping developers create GUI applications quickly and securely.

Python includes several graphical user interface frameworks or toolkits that can be installed as third-party libraries. This article will cover some of the most popular and best Python GUI frameworks and discover the realities of Python GUI frameworks. These frameworks make it interactive and straightforward for developers to create graphical user interfaces. So, let’s Python download for windows and get started!

Why is a Python GUI important?

Python GUI for laptop

Your application’s user interface makes the first impression. Making a good first impression of your application is essential if you want to be successful. For your user to interact with the functionality offered by your application, you’ll need a wide variety of graphical elements, such as buttons, checkboxes, toggles, dropdown lists, search fields, sliders, tooltips, and many more. Unsightly widgets or random placement won’t enhance the first impression.

Another crucial element that determines the caliber of your application and the user experience it provides is performance. You don’t have to sacrifice your GUI to make your application fast and secure. However, your user base will suffer if users cannot interact with your application effectively.

Why do you need a Python GUI framework?

Development frameworks are made to simplify a developer’s job. They make it simpler to develop a specific application or work with a specific language. For instance, using a GUI framework for Python instead of trying to code the user interface for your application manually makes the process much simpler.

What to look out for in a Python GUI tool?

A good GUI tool must be robust and scalable. You must ensure that any development tool can provide performance at all times. The reliability of your development technologies determines the reliability of your applications. As a result, your Python tools must provide consistent GUI performance throughout.

It must have a modern appearance and functionality. Your Python tools will heavily influence the quality of the GUI you create. Not all will provide a user interface that is both clean and appealing enough to stand out. 

Finally, it must provide development support across all platforms. The versatility of Python as a programming language stems from the fact that it can be used to develop for all major platforms. You can create applications for not only Windows but also Android, macOS, and Linux with the correct Python tools.

What is the truth behind Python GUI?

Python GUI for mac

To deliver top-notch solutions for your customers’ needs, think about integrating Python in your applications with the strength of Delphi’s GUI and desktop app development. You should use Python4Delphi to fix your issues.

A group of free Lazarus and Delphi components known as Python for Delphi (P4D) wrap the Python DLL. They enable powerful new Python modules and type creation while making it simple to execute Python scripts.

The best aspect of P4D is how easy it is to use Python as a scripting language for Delphi applications. Additionally, it includes a sizable collection of adaptable tutorials and demos that can be used to create practical apps. In a nutshell, P4D gives you access to various real-world applications that can be customized to meet your unique needs and used in Python GUI.

Including Python support in your Delphi programs gives you the best of both worlds: access to a HUGE variety of libraries and functions from the Python ecosystem, along with Delphi’s renowned speed, usability, and processing power. It truly is a “dream team.”

What makes DelphiVCL the most powerful Python GUI framework?

VCL is a set of visual components for developing Windows applications quickly using the Delphi and C++ programming languages. VCL includes several visual, non-visual, and utility classes that can be used to create Windows applications, web applications, database applications, and console applications. TObject is the ancestor of all VCL classes. In addition, TObject introduces methods for basic behavior such as construction, destruction, and message handling.

DelphiVCL is a Python module that provides Python GUI apps access to Delphi’s VCL for robust and high-performance native Windows visual widgets. It connects Delphi’s VCL (Visual Component Library) and Python with the Python4Delphi library. 

Any framework for developing software must always be able to deliver high performance. The dependability of your apps depends on how reliable your development technology is. Your Python tools must therefore ensure constant GUI performance throughout. To consider the tools in the long run, they should also be able to manage development at all scales.

Any lags or crashes will significantly harm your user experience. You can avoid this by developing high-performance user interfaces for various platforms using Delphi’s VCL and FMX Python modules. These frameworks are also built on the Python4Delphi library for Delphi, which is used to create enterprise-ready applications.

Why is Pyscripter amazing for creating a Python GUI?

Another amazing tool out there by Python GUI is Pyscripter. PyScripter is a fantastic program. It is lightweight, adaptable, expandable, and loaded with features. Moreover, it was built from the ground up for Windows. As a result, it is significantly faster and more responsive than bloated text editors, general-purpose IDEs, or other Python cross-platform IDEs.

PyScripter has a built-in Python interpreter that offers call hints and code completion. This program allows you to run scripts without saving them and keeps track of your command history. For debugging Python code, this IDE also has a remote Python debugger. As a result, it’s possible to see variables, the watch window, and the call stack.

PyScripter is consistently rated highest compared to its competitors because of its ease of use and premium features. However, if your system requires unique features to meet your specific business needs, PyScripter will charge customization fees. These costs will vary depending on your requirements and needs. To learn more about Powerful Native Windows Open Source And Free Python IDE.

Why don’t you start using Python GUI tools today? 

Python GUI for you

P4D has had great success with its Windows development tools and is now applying that knowledge to Python GUI development. Delphi’s Python tools enable you to create stunning and potent GUIs for your applications, thanks to the excellent underlying architecture and meticulous attention to detail. In addition, it offers enterprise-ready functionality through visual and functional elements and overall control over the finished user interface.

Python GUI components for Delphi offer a modern and stylish interface look. Every graphical element you might need is comparable to the native features of the platform. Moreover, its powerful functionality helps create applications with a polished modern appearance for various platforms. Quality is a top priority for DelhiVCL and DelphiFMX, and their integration with corresponding operating systems adds a layer of security. For a smooth user interface, DelhiFMX may even use the GPU hardware capabilities of the user’s GPU for custom rendering.

Now that you know the truth about Python GUI click here and start creating GUI with P4D modules.

The post Python GUI: Expectations vs. Reality first appeared on Python GUI.

]]>
https://pythongui.org/python-gui-expectations-vs-reality/feed/ 0 7967
Common Mistakes Of Python Coding Software https://pythongui.org/common-mistakes-of-python-coding-software/ https://pythongui.org/common-mistakes-of-python-coding-software/#respond Fri, 29 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7295 Since its introduction, Python has consistently grown in popularity because of its simple and easy-to-use interface which makes both novice and experienced developers like using and integrating it. It is a multi-purpose and adaptable programming...

The post Common Mistakes Of Python Coding Software first appeared on Python GUI.

]]>
Since its introduction, Python has consistently grown in popularity because of its simple and easy-to-use interface which makes both novice and experienced developers like using and integrating it. It is a multi-purpose and adaptable programming language that is most commonly used in online application development. Python’s strength is its readability of code. Because it is dynamically typed, it supports a variety of programming paradigms as well as a large library. Python is popular among programmers because it is lightning quick and hence increases productivity. In addition to being portable, Python is also entirely free and open source. Python, unlike C/C++, allows you to create code once and execute it anywhere rather than having to rewrite it every time, making it a developer choice.

Although Python is a versatile programming language with numerous perks, many novice developers face difficulty utilizing it as their daily driver. Python allows for line-by-line execution of code therefore the overall execution process is relatively slow. In order to use Python efficiently, developers must learn how to avoid common mistakes of Python coding software. Read on to find out more about Python and the common mistakes to avoid while using it.

How to avoid using incorrect Class variables?

how-to-opt-for-the-best-python-ide-for-windows-3904849

This is one of the most common mistakes done by movie developers. Class variables are regarded as dictionaries in Python. If one attribute is missing from a class, that class is missing a property. That implies that if you alter something in one class, it shouldn’t affect other classes. Contrary to instance variables, class variables are shared by instances across an entire class. Python is an object-oriented language therefore class variables and instance variables work by a completely different mechanism. Programmers often do the mistake of modifying a class variable without using the correct class name as a result an instance variable is produced with the same name.

In order t rectify this mistake, developers should always use the correct class name to identify or modify class variables so that all the objects in the class should receive the latest value. Below is an example of such an error.

In [1]: class A(object):
…: x = 1
…: class B(A):
…: pass
…: class C(A):
…: pass…:

In [2]: vars(A)
Out[2]: 
mappingproxy({'module': 'main','x': 1,'
dict': ,
'weakref': ,'doc': None})

In [3]: vars(B)
Out[3]: mappingproxy({'module': 'main', 'doc': None})

In [4]: vars(C)
Out[4]: mappingproxy({'module': 'main', 'doc': None})

When you request B.x or C.x, it first searches that class namespace for any “x,” then moves on to A’s namespace, finds it, and returns it.

When you set a variable to B.x = 2, it is now directly added to B’s class namespace:

In [5]: B.x = 2
…:

In [6]: vars(B)
Out[6]: mappingproxy({'module': 'main', 'doc': None, 'x': 2})

Why you should avoid using incorrect indentation?

Python is quite specific with its guidelines regarding indentation. In this programming, language indentation indicates if the code line in question is related to previous code blocks or not. Developers often overlook the importance of using correct indentation which is crucial. Although PEP 8 recommends an indentation of four spaces, you can choose to have the number of spaces according to your liking as long as they are consistent. Novice programmers often fail to combine spaces and tab keys efficiently.

You’ll want to pay close attention since you might not know you’ve mixed tabs and spaces if the indentation appears the same. In order to fix this problem, we recommend using a Python IDE which ensures consistent spacing via its search and replace tool. If you are looking for an ideal Python GUI, then you can’t get a better one than PyScripter. You should also commit to a certain number of spaces if PEP’s guidelines are unsuitable for you. The key to avoiding this error is to stick with a specific number of spaces.

How to deal with the UnboundLocalError?

This is among the list of most common mistakes made by developers. It is crucial for Python developers to understand its scope rules in addition to the LEGB standard. Python is based on the principle of LEGB also known as the Local, Enclosing, Global, Built-in rule. It is important to know that Python follows this specific sequence. 

Python will first presume that any variable assigned in a range is local to that scope and will overwrite any variable with the same name in an external scope, following the LEGB rule. When you call the function again, the code that worked well when you assigned the variable may now produce a “UnboundLocalError.” The superior way of fixing this issue would be to use a Python IDE such as PyScripter. But you can also fix this error by clearly defining or declaring the variable as global via the use of an assignment statement.

How is PyScripter an ideal Python coding software solution?

Common Mistakes Of Python Coding Software - the Embarcadero Python tools page

PyScripter is a wonderful innovative Python IDE with incomparable capabilities and value for money, sponsored by Embarcadero. It’s short and straightforward, with the purpose of providing a reliable scripting solution for Delphi programs. It has a basic and practical user interface that is both clean and contemporary. PyScripter is lightning fast because of its compiled language development. This makes it an excellent Python partner since it increases productivity by improving Python’s code execution speed. If you use PyScripter it can help you efficiently avoid all of the commonly committed mistakes by Python developers.

Above all, PyScripter saves you time by automating repetitive, time-consuming tasks. PyScripter employs Python source code tools to make programming easier. It also has a call signal translator built-in. You can also keep track of your command history and execute scripts without having to save theming.  PyScripter is the finest Python IDE, and we can’t say enough extraordinary things about it. It is very remarkable in terms of performance and features. This IDE is a must-have for anyone learning Python.

So what are you waiting for? Join us now to enhance your Python programming experience!

The post Common Mistakes Of Python Coding Software first appeared on Python GUI.

]]>
https://pythongui.org/common-mistakes-of-python-coding-software/feed/ 0 7295
Where Can I Create A Python Script? https://pythongui.org/where-can-i-create-a-python-script/ https://pythongui.org/where-can-i-create-a-python-script/#respond Thu, 28 Jul 2022 19:23:33 +0000 https://pythongui.org/?p=7771 Almost everyone is familiar with the popular programming language Python. Programming, website development, machine learning, and data science are just a few of the business sectors where it is often used. Given its wide range...

The post Where Can I Create A Python Script? first appeared on Python GUI.

]]>
Almost everyone is familiar with the popular programming language Python. Programming, website development, machine learning, and data science are just a few of the business sectors where it is often used. Given its wide range of use cases, it is not unexpected that Python has surpassed Java as the most popular programming language. In addition, Python script developers are among the highest-paid professionals in the field, particularly in machine learning, data science, and even web development. As a result, learning Python becomes crucial if you want to build a successful career as a developer. The initial stage in this is learning how to write fundamental Python code and create Python scripts.

So, if you are already familiar with the very fundamental syntax of Python, you should continue reading this article that will focus on teaching you how to create a Python script. If not, we recommend solidifying your Python concepts and resuming this article. So, let’s get started.

What is a Python Script?

A Python script is a text file, usually ending with the extension “.py”. The .py file contains lines of Python code which can be referred to as a Python ‘script’. A Python script, however, is a set of instructions included in a file that is intended to be run like a regular application or program. The concept is that the file will be run or performed from the command line or within a Python interactive shell to carry out a specific activity. In addition to the basic Python instructions, of course, the file can contain functions and import different modules. Check out this article to learn more about Python scripting.

Where should you create a Python script?

Where Should You Create A Python Script

Python scripts are almost identical to the Shell scripts you have already encountered in that they are plain text files with lines of Python code that will be executed sequentially, one line at a time. Since the script is a computer program containing Python keywords and instructions most programmers use a specialized text editor with syntax highlighting when writing and editing Python scripts.

Python scripts are written in plain text; you cannot use a word processor like Microsoft Word since it will add much additional information to the file that Python won’t be able to interpret. Additionally, it would be best to choose an editor that is familiar with the programming language you’re using so that it can highlight certain sections of the code, assist with formatting, and flag any syntax problems. There are several solutions available, but PyScripter is unquestionably one of the best.

What is the importance of a Python IDE?

Integrated Development Environment, a constrained IDE that comes with Python, is included (IDLE). Most individuals doubt whether anything else is necessary for learning or perhaps even for creating complete apps. Unfortunately, while the tools that come with Python are intriguing and even helpful in getting started, they won’t make it easy for you to develop productive applications. You need a better tool if you decide to use Python long-term.

Feature lists vary in editors available for Python scripts but there are a core set of features that makes coding easier. Let’s see them:

  • Save and reload code files
  • Run code from within the environment
  • Debugging support
  • Syntax highlighting
  • Automatic code formatting

What makes PyScripter the perfect place to create a Python script?

What Makes PyScripter the Perfect Place to Create a Python Script

An open-source Python Integrated Development Environment (IDE) called PyScripter was developed to compete with other languages’ commercially available IDEs functionally. Although lightweight, it is feature rich. The development of PyScripter is funded by Embarcadero and their Delphi development language is the engine which powers PyScripter.

PyScripter has a modern user interface and is currently available for the Microsoft Windows operating system. Finally, because it was created using a native, ‘close to the metal’ compiled language, PyScripter responds a little quicker than some of the other IDEs and has a wide range of features that make it a useful Python development environment.

PyScripter wants to build a Python IDE that can compete with for-profit Windows-based IDEs for other languages. PyScripter is excellent, rich in features, compact, adaptable, and expandable. Because it was designed specifically for Windows systems, it operates there more quickly and effectively than bloated text editors, all-purpose IDEs, or other Python cross-platform IDEs.

Furthermore, PyScripter stands out thanks to the numerous features it has to offer. First, the user is greatly facilitated by its syntax highlighting functionality to start. The use of Python source code utilities ((un)tabify, (un)comment, (un)indent, etc.) as well as code folding, brace highlighting, split view file editing, syntax checking as you type, and search and replace are all made possible by this functionality. Additionally, the user receives complete support for encoded Python source files and context-sensitive keyword assistance in Python. Finally, this IDE accepts files dropped from Explorer as a time-saving measure.

The integrated Python interpreter in PyScripter provides effective call suggestions and code completion. In addition, this program can run scripts without saving them, preserving command history.

Because it supports a remote Python debugger, this IDE also enables Python debugging. As a result, in addition to the call stack, the user can also see variables and the watch window. The programmer can do thread debugging or add conditional breakpoints for efficient debugging. When a programmer cannot locate the issue in his code, debugger suggestions also prove helpful. One has the additional benefit of being able to debug without saving their work, in addition to being able to run their files without storing them.

Are you ready to create a Python Script right now?

Are You Ready to Create a Python Script Right Now

Python is used widely. Whether there is a need for scalability, stability, processing, or I/O performance, or just for simplicity and readability to facilitate maintenance and the onboarding of new employees, it has repeatedly demonstrated its value. The object-oriented, dynamically typed, interpreted, interactive programming language enables rapid, iterative development and its libraries are among the most well-documented and well-maintained code resources accessible. Python’s rising fame might be attributed to its straightforward syntax, which appeals to both seasoned and inexperienced developers. Because of its adaptability and expanding community, it attracts a lot of developers. Many of the best Python IDEs have been developed due to the widespread demand for Python.

IDEs like PyScripter are super useful because they take care of most of the difficulties around programming. They make creating Python scripts very easy and efficient. 

Now that you know where you can create Python scripts in the best possible way click here and start coding right away!

The post Where Can I Create A Python Script? first appeared on Python GUI.

]]>
https://pythongui.org/where-can-i-create-a-python-script/feed/ 0 7771
How to Outsmart Your Boss With A Python GUI Library https://pythongui.org/how-to-outsmart-your-boss-with-a-python-gui-library/ https://pythongui.org/how-to-outsmart-your-boss-with-a-python-gui-library/#respond Wed, 27 Jul 2022 12:43:16 +0000 https://pythongui.org/?p=8020 Thanks to its high degree of readability, broad use, and most importantly, its beginner friendliness. Python is a well-loved programming language. It’s fantastic for creating graphical user interfaces and is highly helpful for data science...

The post How to Outsmart Your Boss With A Python GUI Library first appeared on Python GUI.

]]>
Thanks to its high degree of readability, broad use, and most importantly, its beginner friendliness. Python is a well-loved programming language. It’s fantastic for creating graphical user interfaces and is highly helpful for data science and machine learning! However, you require a Python GUI library to build graphical user interfaces. Many alternative Python GUI libraries are available, each with a separate set of features and licenses, which unfortunately makes things rather complex.

In this post, we’ll examine the most well-liked Python GUI frameworks currently on the market and explain why you might want to use them for your projects. You’ll learn about libraries using Python GUI, a Python IDE free for basic users. By the end of the article, you should feel confident choosing the right library for your project.

Python for Delphi: What is it?

Python GUI library for you

A free collection of components called Python for Delphi (P4D) integrates the Python DLL into Delphi. They allow you to quickly run Python scripts and effectively develop new Python modules and types.

The main benefit of P4D is that it is extremely simple to utilize Python as a scripting language for Delphi applications. Furthermore, it includes a wide selection of adaptable tutorials and demonstrations ready to use to create practical programs. In summary: P4D provides various “Hello World!” real-world programs that are prepared to meet your demands.

Download your platform’s most recent version of Python, install it, and start working with Python4Delphi VCL. As an alternative, you may view the simple instructions in this video. Learn how to get started with Python4Delphi and the technical specifics of how Delphi executes your Python code in this incredible Python GUI.

What are the Delphi VCL & FMX Libraries for Python?

Python GUI library for mac

Numerous Delphi and C++Builder developers utilize the established GUI libraries VCL and FireMonkey(FMX). The DelphiVCL and DelphiFMX libraries for Python are a collection of Python modules that give Python programmers access to the dependable and established VCL and FireMonkey (FMX) GUI frameworks.

While DelphiFMX for Python uses the cross-platform FireMonkey framework and delivers a strong, flexible GUI framework to Windows, Linux, macOS, and Android, DelphiVCL for Python is focused on native Windows development and uses the Windows-only VCL framework.

Using the VCL and FMX libraries for Python programming does not necessitate prior Delphi experience. However, it is a great benefit when working with these libraries. The popular PyScripter Python IDE’s open-source Python4Delphi library is used to build the libraries.

What makes Delphi VCL so superior?

For building outstanding, cutting-edge graphical user interfaces (GUIs) for your Python scripts, DelphiVCL is a strong framework. Since DelphiVCL is independent of Delphi, installing Delphi is not necessary. However, you may utilize Delphi’s robust IDE software and user-friendly designers to graphically build and enhance your user interface for usage in Python GUI App development, available even in the free Community Edition. Watch this excellent video to learn about the DelphiVCL and see what it can do to build gorgeous, contemporary GUIs for your Python projects.

Most applications require user interfaces. The winning team of Python and DelphiVCL which together produce great applications with fully featured Python user interfaces are also covered in this video.

The VCL is a well-known native Windows GUI framework with a sizeable library of built-in visual components and a wide range of third-party components. How can Python users take advantage of the greatest foundation for native Windows programs? The DelphiVCL Python module makes the VCL a leading tool for developing native Windows GUIs (based on the free Python4Delphi library). Watch the webinar right away to learn more!

Why Is a Native GUI Important?

Windows provides hardware acceleration for native controllers hence, a great performance. Secondly, Native Windows controls include Windows handles, facilitating OS and intra-application interoperability. Furthermore, consumers may anticipate consistent behavior across all their applications when native controls are utilized. Support for Microsoft Active Accessibility (MSAA) is a framework that takes advantage of natural capabilities like screen readers and on-screen keyboards to increase user interface accessibility. Python and Delphi’s VCL (Visual Component Library) are linked together via the Python4Delphi (P4D) module. Applications with a Windows graphical user interface (GUI) may be made using DelphiVCL. To set it up, just type the following command:

delphivcl pip install

Why is DelphiFMX successful in Python GUI?

The Python for Delphi Library is the foundation for the Delphi FireMonkey framework. You may obtain the DelphiFMX Python package from pip to build Windows, macOS, Linux, and Android GUIs. It uses DirectX or OpenGL GPU acceleration, a must for contemporary software. The package, which is easy to use, has buttons, lists, menus, panels, and many more components. The official GitHub repository has examples.

Designers and developers can use FireMonkey Stencils with Delphi, RAD Studio, or C++ Builder to create multi-build device applications. The FMX Framework’s styles and interface elements offer limitless design options, while FMX Stencils facilitate developer and designer collaboration.

In addition to FMX Stencils, may use comparable programs like Balsamiq, Sketch, Photoshop, Illustrator, and others to generate wireframes and mockups. Designers may quickly and simply produce application UI mockups and prototypes by converting the vector components into Sketch and Illustrator symbols, Photoshop smart vector objects, and SVGs. The labels for the symbols and intelligent vector objects follow FMX naming guidelines, ensuring that developers and designers speak the same language and preventing misunderstanding-related issues.

What do you get with your free DelphiVCL and DelphiFMX Python Module?

Python GUI library for pc

What is DelphiVCL?

A Python package for creating native Windows GUI applications is the DelphiVCL library. Additionally, a QuickStart Guide and a collection of VCL Styles are available for free download. VCL is a GUI framework for Windows application development that Embarcadero Delphi initially created. It utilizes DirectX or OpenGL to render using hardware acceleration. It is user-extensible and has a robust style system.

The Python4Delphi library is the foundation for the natively built Python module called delphivcl. It is freely redistributable and allows Python developers access to the VCL GUI framework from Python without requiring them to utilize Delphi in their development process.

The library is supported by Win32 & Win64 x86 architectures and Python cp3.6, cp3.7, cp3.8, cp3.9, and cp3.10. In addition, it uses the Python4Delphi module with the Embarcadero Delphi IDE, which is the best Windows IDE.

What is DelphiFMX?

DelphiFMX is a python module for Windows, macOS, Linux, and Android GUI development, the FireMonkey framework from Delphi. Embarcadero Delphi created FireMonkey, a GUI framework for creating native cross-platform applications. It utilizes DirectX or OpenGL to render using hardware acceleration. It is user-extensible and has a robust style system.

The Python4Delphi library is the foundation for the natively produced Python module, DelphiFMX. It is freely redistributable and allows Python developers access to the FireMonkey GUI framework from Python without requiring them to utilize Delphi in their development process.

The library is supported by Win32 x86, Win64 x86, Linux64 x86, Android64, macOS64, and macM1 architectures, and Python cp3.6, cp3.7, cp3.8, cp3.9, and cp3.10. 

Can Delphi Improve the UI experience?

Python GUI modules for Delphi provide the interface with a modern, clean look. The inherent capabilities of the platform are equivalent to any graphical element you could need. Furthermore, because of its robust capabilities, it can create apps for multiple platforms that have a slick, modern appearance. DelhiVCL and DelphiFMX prioritize quality, and their connection with matching operating systems adds additional security. This technique makes creating UIs visually for Python programs simpler than using existing UI packages or building UI from scratch.

Check out the Delphi VCL & FMX Libraries, which make creating Python GUIs for Windows simple!

The post How to Outsmart Your Boss With A Python GUI Library first appeared on Python GUI.

]]>
https://pythongui.org/how-to-outsmart-your-boss-with-a-python-gui-library/feed/ 0 8020
How Technology Is Changing How We Treat Python UI https://pythongui.org/how-technology-is-changing-how-we-treat-python-ui/ https://pythongui.org/how-technology-is-changing-how-we-treat-python-ui/#respond Tue, 26 Jul 2022 14:25:29 +0000 https://pythongui.org/?p=8007 The use of console based I/O is no longer a requirement for modern computer applications. Instead, modern Python UI are more ergonomically designed graphical user interface due to the use of fast processors and potent...

The post How Technology Is Changing How We Treat Python UI first appeared on Python GUI.

]]>
The use of console based I/O is no longer a requirement for modern computer applications. Instead, modern Python UI are more ergonomically designed graphical user interface due to the use of fast processors and potent graphics hardware, making them user-friendly. These programs allow input through mouse clicks and allow the user to select options using radio buttons, dropdown lists, and other GUI components (or widgets). Such programs are developed using one of the many graphics libraries on the market. This post will discuss a mainstream library and explore how technology changes our treatment of Python UI with Python editor Windows

What is Tkinter?

How Technology Is Changing How We Treat Python UI a screenshot of two people discussing the contents of a laptop screen

Tkinter is the standard GUI library and can be used in many Python editor Windows. Python provides a quick and simple way to make GUI applications when used with Tkinter. Additionally, Tkinter offers the Tk GUI toolkit a potent object-oriented interface.

With Tkinter creating a GUI application is a relatively easy task. For this, you need to perform the following steps:

  • Import the Tkinter module.
  • Create the GUI application main window.
  • Third, add one or more of the widgets mentioned above to the GUI application.
  • Finally, enter the main event loop to take action against each event triggered by the user.

Tkinter has many advantages. Because it is a cross-platform library, the same code runs on Windows, macOS, and Linux. Moreover, Tkinter uses native operating system components to render visual elements, and applications created with it appear to belong on the platform used to run them.

Despite being a popular Python GUI framework, Tkinter has some issues. One noteworthy complaint is that UIs created with Tkinter can appear dated. Tkinter might not be what you’re looking for if you want a sleek, contemporary interface. Additionally, Tkinter requires a significant amount of coding, whereas other technologies enable users to design the user interfaces for their Python apps visually. Two such libraries that are strengthened when used with RAD studio are VCL and FMX from Delphi. Let us take a deeper look into Delphi and its libraries.

How can you create stunning UIs with Delphi?

How Technology Is Changing How We Treat Python UI - a laptop on a table  showing the Delphi VCL and FMX libraries download page

With the power of Delphi’s GUI and desktop app development environment for Python,  you can create a powerful, modern GUI and deliver top-notch solutions for your customers’ needs.

The Python DLL is wrapped by a collection of free Delphi components referred to as Python for Delphi (P4D). P4D makes it simple to run Python scripts while enabling the creation of new, powerful Python modules and types.

The ability to add Python’s simplicity as a scripting language to Delphi applications is one of P4D’s best features. It also comes with a sizable library of adaptable tutorials and demos that can be used to build practical apps. Simply put, P4D gives you access to various real-world applications that can be tailored to your specific needs and used in Python GUI.

What is the Importance of DelphiFMX in Python UI?

The Python for Delphi Library is the foundation for the Delphi FireMonkey framework. The DelphiFMX framework package can easily be downloaded and installed from pip to build graphical user interfaces for Windows, macOS, Linux, and Android. DelhpiFMX uses DirectX or OpenGL GPU acceleration – a requirement for contemporary software. Moreover, it has numerous other components, such as buttons, lists, menus, and panels, with examples in its official GitHub repository.

FireMonkey Stencils can be used to create multi-build device applications, designers, and developers with Delphi, RAD Studio, or C++ Builder. The Framework’s styles and UI components offer countless design possibilities, and FMX Stencils improve developer and designer communication.

Furthermore, designers can quickly and easily create application UI mockups and prototypes by converting the vector components into Sketch and Illustrator symbols, Photoshop smart vector objects, and SVGs. The labels for the symbols and intelligent vector objects follow FMX naming conventions, ensuring that designers and developers speak the same language and preventing misunderstanding-related issues.

What makes DelphiVCL the Next Big Thing in Python UI?

The DelphiVCL GUI development library is an Embarcadero product that might help you avoid bad Python programming experiences.  It uses the VCL framework and concentrates on Python native Windows development. Using the library’s intuitive interface, you can build clear and sturdy user interfaces for your applications. Additionally, this free component package facilitates the development of new Python modules and types in addition to the execution of Python programs.

The VCL is a collection of visual components that helps programmers of the Delphi and C++ languages create Windows applications more quickly. The VCL comes with a number of visual, non-visual, and utility classes that can be used to build Windows, web, database, and console applications.

Python’s DelphiVCL module gives Python GUI programs access to Delphi’s VCL for reliable and fast native Windows visual widgets. The Python4Delphi library links Python and Delphi’s VCL (Visual Component Library).

Lags or crashes severely harm the user experience. However, you can eliminate this by using Delphi’s VCL and FMX Python modules and create high-performance user interfaces for various platforms. 

How can RAD Studio help in how we approach the creation of a Python UI?

RAD Studio is Embarcadero’s integrated development environment (IDE) for creating robust Windows and cross platform applications. It provides a comprehensive set of tools streamlining and simplifying the application development life cycle.

With RAD Studio, you can create a robust GUI by simply dragging and dropping components from the Tool Palette to your forms. Moreover, you can create applications that utilize the extensive Visual Component Library using the designers (VCL) that you can use for various Windows versions and customize your applications.

RAD Studio automatically generates a large portion of your application code as soon as you start a project. The text-based Code Editor offers functions like refactoring, synchronized editing, code completion, recorded keystroke macros, and custom key mappings to assist you in finishing the remaining application logic. In addition, code-folding and syntax highlighting make reading and navigating your code simpler.

Moreover, you can configure compiler settings, compile and run your application, and view compiler messages from within the IDE. MSBuild is integrated and called by RAD Studio as a built engine. The RAD Studio Command Prompt on the Start menu or the command line are options for starting MSBuild. The MSBuild executable’s path is automatically set in the command console window that the RAD Studio Command Prompt opens, and the environment variable BDS is set to the location of your installation directory.

Furthermore, with RAD Studio, you can save compiler options along with a number of other Project > Options in named build configurations that you can then apply to particular projects. The IDE comes with the ability to use Debug and Release build configurations, making it easier to debug your code and smoothing the development process, with the final application shipped using the ‘release mode’ which doesn’t contain any additional symbols and artifacts necessary for debugging. The release mode application package is extremely streamlined and thanks to the optimizing compiler only contains actual live code in it with any unused instructions removed.

Finally, with RAD Studio’s integrated debugger, you can step through code to watch variables, change data values, control program execution, and find and fix runtime and logic errors.

Can you have a better Python UI experience with Delphi?

How Technology Is Changing How We Treat Python UI - a laptop showing a RAD Studio offer screen

Python GUI components for Delphi provide a sleek and contemporary interface appearance. Every graphical component you might require is comparable to the platform’s native features. Additionally, thanks to its strong functionality, it is possible to build applications for various platforms with a sleek, contemporary look. DelhiVCL and DelphiFMX prioritize quality, and their integration with corresponding operating systems adds an extra layer of security. With this technology, it is easier to design UIs for python apps visually than to use other UI libraries or build UI manually.

Click here and start building sophisticated GUIs for your application using the market’s most powerful Python GUI modules.

The post How Technology Is Changing How We Treat Python UI first appeared on Python GUI.

]]>
https://pythongui.org/how-technology-is-changing-how-we-treat-python-ui/feed/ 0 8007
Why Is Python Best for Programming Data Visualization? https://pythongui.org/why-is-python-best-for-programming-data-visualization/ https://pythongui.org/why-is-python-best-for-programming-data-visualization/#respond Fri, 22 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7754 The graphic display of statistical information is known as data visualization. Programming data visualization tools offer a straightforward approach to examining and comprehending trends, outliers, and patterns in data by utilizing visual components like charts,...

The post Why Is Python Best for Programming Data Visualization? first appeared on Python GUI.

]]>
The graphic display of statistical information is known as data visualization. Programming data visualization tools offer a straightforward approach to examining and comprehending trends, outliers, and patterns in data by utilizing visual components like charts, graphs, and maps.

The data visualization tools Python has available and their related technologies are crucial to evaluating vast volumes of data and making data-driven choices in the age of big data. This article will focus on what data visualization is, its advantages, and why Python is best for the said application.

What Is the importance of programming data visualization?

Why Is Python Best for Programming Data Visualization?

Businesses need data visualization to help them rapidly see data patterns, which would otherwise be difficult. Analysts can see ideas and novel patterns thanks to the graphical depiction of data sets. In addition, making sense of the quintillion bytes of data generated daily is hard without data visualization.

Data visualization expands to all industries where data is present since every professional field benefits from knowing their data. Information is the most critical leverage for every organization. One may make arguments and use knowledge by using visualization. To visualize and comprehend data, one can use a dashboard, graph, infographics, map, chart, video presentation, etc. In addition, decision-makers may use data visualization to interrelate data to gain more significant insights and benefit from its relevance.

How can One benefit from data visualization?

Business stakeholders can concentrate on the areas that need attention by analyzing reports. The visual mediums aid analysts in comprehending the crucial information required for their line of work. Whether it’s a business report or a business model, a graphic depiction of the data helps businesses make better analyses and decisions that enhance revenues.

People analyze images more quickly than they do long, laborious analytical forms or reports. Decision-makers may move fast based on fresh data insights if the data is well-communicated, speeding both decision-making and corporate growth.

Business users may utilize data visualization to understand their massive data sets. They gain by spotting fresh patterns and mistakes. They can focus on locations that show red flags or progress. The business advances as a result of this procedure.

Why use Python for programming data visualization graphs and content?

Why Is Python Best for Programming Data Visualization? Using graphs to make data more consumable

By putting data in a visual context and attempting to comprehend it, data visualization seeks to reveal patterns, trends, and connections that would not otherwise be visible. Python has a number of excellent graphing packages with a wide range of functionality. Python provides a great library for you whether you want to make interactive or fully customized plots.

A few well-known plotting libraries in Python include Matplotlib – low-level and flexible, Pandas Visualization – easy-to-use interface based on Matplotlib, Seaborn – high-level interface and great default styles, plotnine – based on R’s ggplot2 and uses Grammar of Graphics, Plotly – which can create interactive plots and Bokeh

Which library Is the most popular for Python data visualization?

A large number of available modules may be intimidating if you’re new to Python visualization. Additionally, specific libraries could be better suited for a given circumstance than others. You should be able to distinguish between the varied features of each library and make an informed decision.

How to use Matplotlib as a graph tool for Python

Matplotlib is the most well-liked and outstanding Python library for data visualization to date. Almost everyone involved in data science has at some point used Matplotlib. Delphi may be used to create a simple yet effective user interface for this advanced data visualization engine.

NumPy arrays are the foundation of the user-friendly, low-level data visualization package of the Matplotlib library. It includes a number of visualizations, including scatter plots, line plots, and histograms. 

Enter the following command in the terminal to install this.

pip install matplotlib

The matplotlib library uses various plots for data visualization. These include scatter plots, line charts, bar charts, and histograms. For example, to plot a histogram, the following code lines can be used: 

import pandas as pd
import matplotlib.pyplot as plt
   
# reading the database
data = pd.read_csv("tips.csv")
  
# Scatter plot with day against tip
plt.scatter(data['day'], data['tip'], c=data['size'], 
s=data['total_bill'])
# Adding Title to the Plot
plt.title("Scatter Plot")
  
# Setting the X and Y labels
plt.xlabel('Day')
plt.ylabel('Tip')
plt.colorbar()
plt.show()

The colorbar() function is included in the code to demonstrate the flexibility of using the library and make the output more appealing.

Seaborn for Python is great for programming data visualization

On top of Matplotlib, Seaborn is a high-level interface. It offers stunning design themes and color schemes to create more appealing graphs.

Enter the following command in the terminal to install Seaborn.

pip install seaborn

Seaborn is developed on top of the Matplotlib library. Therefore, it is relatively easy to use Seaborn and Matplotlib together. To use the customization feature of Matplotlib, we simply need to use the Seaborn Plotting function as usual. Just like Matplotlib, the Seaborn library uses different plots. For example, scatter plots, line plots, bar plots, and histograms.

An example code to a histogram:

# importing packages
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# reading the database
data = pd.read_csv("tips.csv") 
sns.histplot(x='total_bill', data=data, kde=True, hue='sex')
plt.show()

Use Bokeh as a graph tool with Python

The third library on our list is Bokeh. The primary reason for Bokeh’s fame is its dynamic chart presentation. Bokeh produces its plots using HTML and JavaScript, which employs contemporary web browsers, to present attractive, succinct designs of innovative visuals with high-level interaction. The installation command for this library is 

pip install bokeh

Just like the other two libraries, this library also uses plots like scatter plots, line charts, and bar charts. The additional interactivity feature to the plots is one of Bokeh’s primary characteristics. The legend is interactive, thanks to the click policy parameter. Interactivity comes in two flavors. Below is an example of a plot using the Bokeh library:

# importing the modules
from bokeh.plotting import figure, output_file, show
import pandas as pd
  
  
# instantiating the figure object
graph = figure(title = "Bokeh Bar Chart")
  
# reading the database
data = pd.read_csv("tips.csv")
  
# plotting the graph
graph.vbar(data['total_bill'], top=data['tip'], 
legend_label = "Bill VS Tips", color='green')
  
graph.vbar(data['tip'], top=data['size'], 
legend_label = "Tips VS Size", color='red')
  
graph.legend.click_policy = "hide"
  
# displaying the model
show(graph)

Python has several charting libraries, including Matplotlib, Seaborn, and many additional data visualization tools with various capabilities for building educational, unique, and visually appealing charts to show data most simply and powerfully.

So, what are you waiting for? Click here to begin programming data visualization using Python.

The post Why Is Python Best for Programming Data Visualization? first appeared on Python GUI.

]]>
https://pythongui.org/why-is-python-best-for-programming-data-visualization/feed/ 0 7754
How To Write A Python Script Remotely Over SSH https://pythongui.org/how-to-a-write-python-script-remotely-using-ssh/ https://pythongui.org/how-to-a-write-python-script-remotely-using-ssh/#respond Thu, 21 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7797 When it comes to working in an organization, it’s quite common to write/develop code and deploy applications on your server. Secure Shell (SSH) is the communication protocol to gain access to a whole remote computer/server...

The post How To Write A Python Script Remotely Over SSH first appeared on Python GUI.

]]>
When it comes to working in an organization, it’s quite common to write/develop code and deploy applications on your server. Secure Shell (SSH) is the communication protocol to gain access to a whole remote computer/server either on a local network or any server deployed in some other part of the world. PyScripter has a feature to create an SSH Client connection to an SSH server which then allows you to create your Python script remotely. Let’s get into the details of how to work with remote Python scripts and files using the PyScripter Python IDE.

Prerequisites

Two types of SSH servers

  • Local network server
  • Remote server

Working with a Python script on the local network server

Let’s create a GNU/Linux SSH server. The setup I have is a Debian-based OS – PureOS running on my machine. I have a windows virtual machine running in which I installed PyScripter IDE. So the GNU/Linux-based PureOS will serve as an SSH server and the Windows virtual machine will serve as an SSH client in the local network. You can have a setup of two different machines connected to the same LAN or WiFi. Most of the recent operating systems have SSH pre-installed in them. On the GNU/Linux-based OS check whether an SSH server is already running with the following command:

systemctl status ssh
How To A Write Python Script Remotely Using SSH - an SSH window

If the server is already running, you’ll get a result similar to the above image where Active: active (running) with green color. If the server is inactive you’ll get a result similar to the below image;

How To A Write Python Script Remotely Using SSH - stopping the SSH service

To switch on the server enter the following below command and recheck the status using the above status command.

systemctl start ssh

Now your server should be running. Please check the IP address of your server using the following command;

ip addr | grep inet
How To A Write Python Script Remotely Using SSH - finding the IP address

The IP address is highlighted in the above image. Also, check the port number on which the SSH server is active using the following command;

sudo lsof -i -P -n | grep sshd | grep IPv4
ssh_port_status-4252776

The TCP port number(22) on which SSH is running is highlighted in the above image. We also need the username of your server. You can use the whoami command to check your username.

whoami-5559017

How to connect to the SSH server from your local machine

Now let’s log in to the SSH server from the SSH client. I’ll use the Windows OS in my Virtual Machine as an SSH client. You can use a separate Windows machine that’s connected to the same LAN or Wi-Fi to create an SSH client. We can check whether OpenSSH client is already installed by opening the Settings > Apps > Apps & features > Optional features or otherwise add/install that feature as it’s shown in the below image;

How To A Write Python Script Remotely Using SSH - how to set up OpenSSH to edit Python scripts on a remote server

Now, it’s time to login the SSH server as a client from the PyScripter installed Windows machine. We shall utilize the username, ip address and port number of the GNU/Linux Server which we noted down earlier. Please login to the server using the following command;

ssh USERNAME@IP_ADDRESS -p PORT_NUMBER

My IP address will change here as I changed my Wi-Fi Hotspot compared to the above screenshots. Please observe the below image in my case where the IP address is changed from 192.168.0.108 to 192.168.85.1 as compared to the previous screenshot. The steps to log in to the SSH server are mentioned in the below figure;

How To A Write Python Script Remotely Using SSH - making the SSH connection

Now, we’re logged into the SSH server computer where we can create, delete and mange files of the server from our SSH Client from the PowerShell. We can also use any other command line tools like git bash to implement the SSH Client on Windows. Here we’re logging in with the server computer’s password which can be compromised. We shall generate a public-private keypair to login into server instead of a password. To generate a SSH key based login pair, we can use the ssh-keygen command as shown in the below figure;

How To A Write Python Script Remotely Using SSH - generating the SSH key

We should now copy the public key in the id_rsa.pub file of the current Windows Client to authorized_keys file of the GNU/Linux Server. We shall use the following command to do it;

cat ~/.ssh/id_rsa.pub | ssh username@ip_address "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys"

Observe the below image where “username” and “ip_address” are updated with my respective server details. We can then login to the Server without using any password.

How To A Write Python Script Remotely Using SSH - manipulating the public/private key pair

How to edit a Python script on a remote server using PyScripter

We’re now set to work with remote files in PyScripter. Please open PyScripter and choose the File > Open Remote File option as shown below;

How To A Write Python Script Remotely Using SSH - showing the menu options with the location of the open remote file option

Follow the below mentioned sequence of steps to connect to an SSH server;

How To A Write Python Script Remotely Using SSH - how to manage the SSH connection

After adding the Server, we can now open any of the files in the server computer in the PyScripter. We should choose one of the servers from the list of added servers and the path of the file in the server. Use the below image as a guide;

How To A Write Python Script Remotely Using SSH - opening the remote script

Let’s check the content of check.py file in the Server computer to cross-check when it’s opened with PyScripter. As you click “OK” in the above image, the remote check.py file will get opened. Please check out the below figure where we open the check.py file with both the terminal and PyScripter.

How To A Write Python Script Remotely Using SSH - the remote path

After editing the Python file, save it and it’ll save to Server. Now, you can successfully edit, run and save the file to Server from the PyScripter IDE. Let’s now implement the functionality of accessing the file from a remotely hosted Server.

How to work with the Python script on the remote server

In real-time work structures in an organization, we host an application on a Remote Server. I chose Digital Ocean hosting to create a Remote Server. Digital Ocean generously offered me a referral link using which you can have $100 credit for 2 months. Use the following link:

https://m.do.co/c/1e4060599604

DigitalOcean Referral Badge

Use the above referral link and create an account. Create a Server – “Droplet” as they call it. Choose the basic options to create the server to test working with the remote server files in the PyScripter IDE.

msedge_fcookiqv3z-2901620

We need to provide an SSH key when setting up the server for a password less login similar to what we’ve done with local server. Let’s create another SSH key-pair to use with the digital ocean server using the ssh-keygen utility.

How To A Write Python Script Remotely Using SSH - powershell commands to do the SSH magic
How To A Write Python Script Remotely Using SSH - where to find the authentication key

Finally, create the droplet and Digital Ocean’s droplet service will assign a public IP address to access the created server.

droplet-ip-4201631

Let’s now try to access it (server) using PowerShell. Please open the PowerShell as an administrator to add the identity of the above created Server (droplet) to the Client computer. Check the below image for instructions;

How To A Write Python Script Remotely Using SSH - the complications of a droplet server

Now we can successfully SSH and connect to the Server computer as you can observe in the below image;

How To A Write Python Script Remotely Using SSH - connecting to an Ubuntu instance

How to create a Python script on a remote Linux server using PyScripter

Let’s now create an empty Python file in the Server and write some code in it by opening it using PyScripter IDE. We can use a UNIX command “touch <filename>” to create a new file.

How To A Write Python Script Remotely Using SSH - updating the file's dates

Now, open the PyScripter to open the above created Python file in the server. We can access the remote file from the remote server as we’ve accessed the file in the local server. We can list the SSH connection of remote server using its Public IP address similar to that we’ve done with local server. Open ( File > Open Remote File > pyscripter_wav8aidngn-2768675 > pyscripter_6vsewllz3f-6710287 ) and then fill the server connection details in the Edit SSH Servers form/window.

How To A Write Python Script Remotely Using SSH more details of the SSH server

Now the file at a given path in the remote server will open and we can work on it in the PyScripter IDE.

How To A Write Python Script Remotely Using SSH - executing thecheck.py script

Save the edits using “Ctrl + S” shortcut and the file will be automatically saved in the remote server with changes. To demonstrate the saved changes, let’s check the content of the file in the remote server using the PowerShell connection. We shall use a UNIX based command “cat <filename>” to view the content of the file in the terminal (PowerShell).

How To A Write Python Script Remotely Using SSH - a command line shell showing the results of executing a Python script remotely

Summary of the things we learned about how to edit a Python script remotely

PyScripter IDE can become your goto IDE to work with remote files. You can do all the operations like open, create, edit, update and save the remote file right from your comfort of your favourite PyScripter IDE. There are various other features come along with PyScripter IDE to make it as your default IDE to work. We’re currently working Debug extensions adapter using which we can create debuggers for other programming languages. PyScripter can then be used to run other language codes like JavaScript, C language etc. Please download it at: PyScripter – Free Download – Embarcadero and give it a try. If you face any difficulty in following the above steps, please feel free to ask questions in the comments.

The post How To Write A Python Script Remotely Over SSH first appeared on Python GUI.

]]>
https://pythongui.org/how-to-a-write-python-script-remotely-using-ssh/feed/ 0 7797
5 Examples Of Best Python Graphs https://pythongui.org/5-examples-of-best-python-graphs/ https://pythongui.org/5-examples-of-best-python-graphs/#respond Wed, 20 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7913 Anyone attempting to uncover and convey insights from data needs to be proficient in data visualization. Visualization is essential to the machine learning process at every stage of analysis. Python is frequently used for plotting...

The post 5 Examples Of Best Python Graphs first appeared on Python GUI.

]]>
Anyone attempting to uncover and convey insights from data needs to be proficient in data visualization. Visualization is essential to the machine learning process at every stage of analysis. Python is frequently used for plotting graphs because it is one of the most important programming languages in this area. Thus, programming the creation of graphics is a very common task today. Python4Delphi’s Matplotlib or Seaborn libraries make it simple to resolve (P4D) and make the best Python graphs. Thus, in this article, we will look at the top 5 Python graph examples using the best data visualization tools Python has to offer.

What is a Barplot?

5 Examples Of Best Python Graphs - an image of a laptop showing a bar chart

A bar plot is used to display categorical data. Categorical data are displayed as rectangular bars with heights proportional to the values they represent in a bar plot. Moreover, it is frequently used to compare the values of various data categories using various data visualization tools Python.

What is categorical data?

A categorical data set is nothing more than grouping data into various logical categories, such as tall, medium, short, etc., for data on a person’s height. You must figure out the number of each category to create a bar plot.

Users must first install all of the necessary libraries we will use. Python’s pip command is used to accomplish this. Importing these packages should then be the first step in your script.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Let’s make a dataset with 10 distinct categories and give each one a value.

Use the np.random.randn() function generates a random array, passing it the array’s size, upper and lower bounds as arguments.

# create data
x = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
y = np.random.randint(low=0, high=90, size=10)
print(y)

Here is the output of the program:

[47, 0, 27,  23, 42,  4, 46, 76, 33, 71]

As you can see, the output y contains an array of values that were chosen at random. We then use the plt.bar() function passing the two arguments x value and y value, to plot a barplot in Matplotlib:

# simple bar chart
plt.bar(x, y)
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar plot of categories')
plt.show()

Matplotlib is a powerful Python library that you can use in various applications and is the basis for many other Python libraries. Check out this article to learn how to make 2d graphs with Matplotlib.

What is a line plot?

5 Examples Of Best Python Graphs - an image of a laptop with a stacked line graph on the screen

An informational chart known as a line plot shows data as a series of data points connected by straight line segments.

Line plots are one of the most frequently used charts that show how one or more data points have changed direction over time. For example, dateTime would be the x-axis in this instance, and the measured quantity, such as stock price, weather, monthly sales, etc., would be on the y-axis. A line plot is frequently the first option when displaying any time series data.

We will first import the packages needed to make line plots. These imports will be the same as the ones we just saw for bar plots.

Let’s use the np.linspace() function to create a dataset with 50 values between 1 and 100. This will appear on the x-axis, and the log of x will appear on the y-axis.

Using plt.plot, the line graph of y against x is produced (x,y). It connects every point in a straight line:

# simple line plot
x = np.linspace(1,100,5)
y = np.log(x)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('logx')
plt.title('Basic line plot')
plt.xlim(0,100)
plt.ylim(0,5)plt.show()

How can you create a pie chart in Python?

5 Examples Of Best Python Graphs - an image of the PyScripter Python IDE

The pie chart displays the data distribution based on the percentage of the pie that is occupied. After making the necessary imports, the plt.pie() command in Python can be used to plot a pie chart.

Let’s see a simple example:

import matplotlib.pyplot as plt
import numpy as np

y = np.array([45, 15, 25, 15])
labels = ["Peaches", "Bananas", "Cherries", "Apricots"]

plt.pie(y, labels=labels)
plt.show()

Why are scatter plots one of the best Python graphs?

5 Examples Of Best Python Graphs - the Delphi VCL and Delphi FMX Python GUI library download page

You can graph two data sets along two axes to create a scatter plot. It helps to depict how the two variables are related to one another.

A positive (or negative) linear relationship may exist if the value on the y-axis appears to rise as the x-axis rises (or falls). In contrast, if the points are randomly spaced out without any discernible pattern, it might suggest that there is no dependent relationship.

The scatterplot in Python Matplotlib can be made using either pyplot.plot() or pyplot.scatter(). With the aid of these features, you can enhance your scatter plot by altering the points’ size, color, or shape.

Therefore, the question of what distinguishes plt.scatter() from plt.plot() frequently arises. With pyplot.plot(), any property you apply (color, shape, or size of points) will be applied to all of the points, whereas with pyplot.scatter(); you have more control over how each point looks.

In other words, you can use plt.scatter() to make each dot (datapointcolor, ) ‘s shape and size depend on a different variable—the same variable, or even (y). In contrast, the properties you set when using pyplot.plot() will be applied to every point in the chart.

The same imports we made earlier for numpy, pandas, and matplotlib are required here. First, let’s generate fictitious data with the np.random.randint() function. You must state how many points you need for the arguments. Additionally, you can specify the required random variable’s lower and upper bounds.

Then, employ Matplotlib’s plt.scatter() function to create a scatter plot. The variables x and y must be given as arguments.

# simple scatterplot
x = range(50)
y = range(50) + np.random.randint(0, 30, 50)
plt.scatter(x, y)
plt.title('Basic scatter plot')
plt.xlabel('X value')
plt.ylabel('Y value')
plt.show()

What is a heat map? Does it qualify as one of the best Python graphs?

5 Examples Of Best Python Graphs - a screen with a collection of different Python graphs

Multivariate data graphically represented as a matrix of columns and rows is known as a heat map. Heat maps are a very helpful tool when describing the correlation between several numerical variables and displaying patterns and anomalies.

What is meant by correlation?

The degree of a variable’s relationship with other variables is measured by its correlation, a dimensionless unit. It gauges the linear relationship between variables’ strength and direction. Its value, which ranges from 0 to 1, represents strength, and the + and – signs, represent direction.

The values used in the heatmap plot below were generated randomly using NumPy. Although there are many possible parameters, we will concentrate on the fundamental plot here.

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

np.random.seed(0)
sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, vmin=0, vmax=1)
plt.show()

Seaborn is a user-friendly library offering strong tools for creating better and more beautiful visualizations. In addition, users can modify the Seaborn plots to meet individual needs and can use Python to create heatmaps for various applications. Check out this article to learn more about how you can use these libraries with real-wold data.

Can you plot these best Python graphs?

5 Examples Of Best Python Graphs - a person looking at a laptop held in their hands. The screen shows the Python4Delphi project page.

A free set of components called Python for Delphi (P4D) integrates the Python DLL into Delphi and Lazarus (FPC). P4D makes it simple to run Python scripts and develop new Python modules and types. For example, you can use the Matplotlib library or send the data to Delphi and create the chart if you already have a Python application and need to create charts. You can also produce this chart using Matplotlib and then show in the Delphi Windows GUI application.

You can use Python4Delphi in a number of different ways, such as:

  • Create a Windows GUI around your existing Python app.
  • Add Python scripting to your Delphi Windows apps.
  • Add parallel processing to your Python apps through Delphi threads.
  • Enhance your speed-sensitive Python apps with functions from Delphi for more speed.

Now that you know how to plot the five best Python graphs, you can start doing data visualizations of your own using Python libraries and P4D! 

 

The post 5 Examples Of Best Python Graphs first appeared on Python GUI.

]]>
https://pythongui.org/5-examples-of-best-python-graphs/feed/ 0 7913
Where To Write Code In Python? https://pythongui.org/where-to-write-code-in-python/ https://pythongui.org/where-to-write-code-in-python/#respond Tue, 19 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7836 Given the tech industry’s tremendous growth and demand, it’s worth taking a closer look at Python’s unique benefits and applications. Python has become one of the twenty-first century’s most exciting and profitable programming languages. It...

The post Where To Write Code In Python? first appeared on Python GUI.

]]>
Given the tech industry’s tremendous growth and demand, it’s worth taking a closer look at Python’s unique benefits and applications. Python has become one of the twenty-first century’s most exciting and profitable programming languages. It created everything from Netflix’s recommendation system to the software that runs self-driving cars. Moreover, Python’s rising popularity can be attributed to its straightforward syntax, which appeals to experienced and inexperienced developers. However, because of its adaptability and growing community, it appeals to many developers. Furthermore, in recent years, its employment in simpler domains has grown in favor. Thus, it has become more important for developers to know about a good Python program maker and where to write code in Python.

Because of the rising demand for Python worldwide, many of the top Python IDEs have been created. PyScripter is a free, open-source Python IDE that comes with a lot of features that are covered by the MIT license. This article will discuss the importance and characteristics of a good Python program maker.

Why is Python an important programming language?

Python is everywhere and has proven it’s worth time and time again. While maintaining simplicity and readability, it can provide scalability, stability, fast processing, and I/O performance.

Python’s popularity is growing due to its simple syntax, which appeals to experienced and inexperienced programmers. In addition, many developers like it because of its adaptability and growing community. As a result, Python is known as the “Swiss Army Knife” of programming languages. It’s not picky about platforms as a programming language, and it works equally well on Windows, Linux, and macOS.

Many IDEs make Python development even easier and more intuitive. It comes as a result of the high demand for Python around the world.

What is an IDE and is that where to write code in Python?

Where To Write Code In Python? An image of a laptop showing the PyScripter project page

IDE refers to the Integrated Development Environment. It’s a coding tool that makes it easy to write, test, and debug your code through its code highlighting, resource management, compilers, debugging tools, and all the other software development essentials. Therefore even while the IDE is a well-defined notion, it is beginning to be redefined as other tools, such as notebooks, gain more and more functionality previously only available in IDEs.

Most integrated development environments (IDEs) handle a wide range of programming languages and provide many additional features. As a result, they may be large, and downloading and installing them may take a long time. In addition, you may need advanced knowledge to use them effectively.

IDEs help organize the various components of a computer program. It’s not always straightforward to pick the best-integrated development environment (IDE) for your needs. There are a plethora of options available. There are a lot of interesting IDEs out there, each with its unique set of features that can help you code faster, be more productive, and prevent mistakes. Most quality coding software can debug and execute code. The top also uses source control systems.

So, one of the most essential questions in Python programming is where to code in Python or which IDE to use.

Which IDE is the best for writing Python code?

Where To Write Code In Python? An image of the PyScripter benefits page.

PyScripter began as a lightweight IDE to supplement the great Python for Delphi (P4D) components by providing a reliable scripting solution for various GUI and Delphi applications.

It has now grown into an amazing, fully-featured, stand-alone Python IDE, thanks to the support of Morgan Martinez, a P4D developer, and many early users. 

Moreover, PyScripter has a modern user interface and is currently only available for Microsoft Windows operating systems. In addition, PyScripter is written in a compiled language. Consequently, this makes it faster than most other IDEs, and it has a diverse set of features that make it a useful Python programming environment.

PyScripter aspires to build a Python IDE that can compete with commercial Windows-based IDEs for other languages. Furthermore, PyScripter is an excellent, Feature-rich, lightweight tool that is adaptable and expandable. Moreover, it is significantly faster and more responsive on Windows than most other bloated text editors, general-purpose IDEs.

What features does PyScripter offer which make it where to write code in Python?

PyScripter has several distinguishing features that make it stand out from its competition. To begin with, its syntax highlighting feature makes the user’s life much easier. Moreover, some other features include brace highlighting, code folding, split-view file editing, syntax checking as you type, search and replace, and the use of Python source code tools ((un)tabify, (un)comment, (un)indent, and so on) are all possible with this functionality. Additionally, the user is fully supported for encoded Python source files and context-sensitive Python keyword help. Finally, PyScripter also handles files dropped from Explorer, which might save you a lot of time.

PyScripter has a built-in Python interpreter, making code development easier with its quick call hints and code completion. Moreover, it keeps track of command history and allows you to run scripts without saving them. PyScripter also supports a remote Python debugger, which allows for Python debugging. As a result, developers may see variables, the watch window, and the call stack. Moreover, programmers can use conditional breakpoints or thread debugging to help with debugging. Debugger indications are also beneficial when the programmer cannot locate the error in his code.

In addition, Not only can one run their files without saving them, but they can also debug without saving, which is a bonus. PyScripter ensures automatic test generation, allowing you to perform automated unit testing. This IDE also includes a fantastic unit testing GUI (which you can learn more about here). Moreover, its unit tests window offers an advanced graphical user interface for running unit tests, a standard Python module.

PyScripter offers several other technical features that you can find here.

Finally, PyScripter is always rated highest compared to its competitors because of its ease of use and premium features. Moreover, PyScripter will charge customization expenses if you require unique features in your system to meet your specific business demands. These costs will vary depending on your needs and feature requirements.

Do you know all about the best Python IDE?

Where To Write Code In Python? An image of a person using the PyScripter Python IDE

Python is crucial because, as is evident by the rise of analytics and business intelligence. In addition, it is increasingly being used in a wide range of computing and scientific applications. 

A solid Python IDE makes managing your coding projects quick and easy. Pyscripter is the best IDE making development easier with advanced features like code recommendations and a debugger. Furthermore, it has many other features that make it an excellent Python programming environment.

You must be eager to try out all the features and start coding in the best IDE. Now you know where to write code in Python, go ahead and click here to get PyScripter the best Python IDE.

The post Where To Write Code In Python? first appeared on Python GUI.

]]>
https://pythongui.org/where-to-write-code-in-python/feed/ 0 7836
How To Use A Python Script https://pythongui.org/how-to-use-a-python-script/ https://pythongui.org/how-to-use-a-python-script/#respond Mon, 18 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7760 Python is a high-level, all-purpose programming language. It is extremely versatile and can be used to create desktop GUI programs, websites, and web applications. Also, handling routine programming tasks frees you up to concentrate on...

The post How To Use A Python Script first appeared on Python GUI.

]]>
Python is a high-level, all-purpose programming language. It is extremely versatile and can be used to create desktop GUI programs, websites, and web applications. Also, handling routine programming tasks frees you up to concentrate on the essential features of the application. Moreover, with Python, you can keep the code base readable and the application maintainable more easily thanks to Python’s straightforward syntax rules. How to use a Python script is one of the most crucial skills you can develop as a Python developer.

Naturally, this will be the only way to know if your code works as you planned. So, in this post, we will look at how to use a Python script properly and discuss the types of Python script files available and how they are different from one another.

What type of language is Python?

How To Use A Python Script - an image of a person using a laptop with the PyScripter IDE running on it

There are three main types of programming languages: compiled, scripts or scripting, and interpreted. The primary distinction is that scripting languages are always interpreted while programming languages are either completely compiled down to native machine instructions or are partially compiled to an intermediate ‘tokenized’ form of instructions which then require a runtime to convert those tokens into runnable machine-specific instructions. Python is mainly an “interpreted language,” but its features make it a competent “scripting language.”

What is the difference between a Python script which has a .py extension to one with a .pyc file extension?

Python scripts can be compiled from readable ‘.py’ text files which can be opened by any text editor. The Python scripts can also be compiled into ‘.pyc’ binary files which contain the script as intermediate tokenized instructions which are then converted to machine-specific instructions by the Python runtime. The ‘.pyc’ Python script files are more secure than .py text files since regular users can’t easily open the files and read the program but there are tools readily available which can ‘decompile’ the binary Python .pyc files back into text .py files.

Are Python scripts slower than compiled programs written in other computer languages?

Scripting languages are typically slower than fully compiled programming languages such as Delphi, C++, and C. They may less access to a computer’s native capabilities because they are intended to be able to run as many types of computers and operating system as possible and to do this they avoid some machine-specific functions. Python runtimes handle most of the commonly available hardware such as cameras and networking components but can’t always provide an abstraction for less common hardware or operating system features.

Since it functions as both a compiler and an interpreter, Python acts as both a scripting language and a programming language. For example, a standard Python interpreter can translate Python code into bytecodes like Java and C – the .pyc files we mentioned earlier.

For easy understanding, consider an example Python file, example.py, with the following basic code:

#!/usr/bin/env python3

print('This is an example!')

We will use this file for all the tutorials in this article.

Can you run Python scripts interactively?

How To Use A Python Script - a laptop at the download screen for Python script tools from Embarcadero

From an interactive session, Python scripts and modules can be executed. You have several options with this choice.

What occurs when you import a module is that you load its contents for access and use at a later time. The intriguing aspect of this procedure is that import executes the code as its last action.

You probably won’t notice that the code was executed if the module only contains definitions for classes, functions, variables, and constants. Still, you will see the code being executed if it also includes calls to other functions, methods, or statements that produce obvious results.

You should be aware that this option only functions once per session. Even if you change the module’s content after the initial import, subsequent import executions have no further effect. This is because import operations are costly and only occur once.

However, there is a single solution to this. 

You can find importlib, a module that offers import_module(), in the Python Standard Library.

You can execute any module or script by simulating an import operation with import_module(). Take a look at this example:

import importlib
importlib.import_module('example')

It is impossible to continue running a module using import after the initial import. Therefore, you can force the interpreter to re-import the module in this situation by using importlib.reload().

Using runpy.run_module() and runpy.run_path(), you can also run Python code interactively. Runpy is a module found in the Python Standard Library. Furthermore, run_module(), a function that enables you to run modules without importing them, can be found in this module. This function returns the global dictionary of the module that was executed.

runpy.run_module(mod_name='example')

In addition, the standard import mechanism is used to locate and execute the module in a fresh module namespace.

Moreover, the run_module() functions’ first argument must be a string with the name of the module without the .py extension.

Is running a Python script using the command-line easy?

How To Use A Python Script - a laptop on a table with two mugs, a cardboard file box with a ribbon holding it closed. The laptop is asking if the user would like to download PyScripter

Many lines of code can be written in Python interactive sessions, but everything you’ve written is lost once you close the session. Because of this, plain text files are typically used when writing Python programs. Those files will typically have the.py extension.

Furthermore, Python code files can be made using any plain text editor. Try PyScripter, a robust and user-friendly editor that will be covered in more detail later if you are new to Python programming.

Let’s first examine how to use the python command to run Python files. To do this, open a command line and press the enter key after typing “python” (or “python3” if you have both versions) and the path to your script:

$ python3 example.py

We get the expected output:

This is an example!

Furthermore, sometimes it’s useful to save the output of a script for later analysis. Here’s how you can do that:

$ python3 example.py > output.txt

Finally, if the file output.txt does not exist in the file system, it is made automatically. Contrary to this, if the file already exists in the system, then its contents will be overwritten with the new output.

Is it possible to run or use a Python script from a file manager?

Another way to run your Python scripts is by double-clicking the script’s icon in a file manager. Moreover, when you release your code for production, it might not be utilized frequently during the development phase.

However, before being able to run your scripts with a simple double-click, you must fulfill a few requirements. These requirements will vary depending on your operating system.

For instance, Windows links the programs python.exe and pythonw.exe with the file extensions .py and.pyw, respectively. By doing this, you can double-click on your scripts to run them.

You should be able to execute your scripts by double-clicking them in your file manager on Unix-like systems. Your script must have execution permissions to accomplish this.

You will likely only see the flash of a black window on your screen in either scenario when you have a script with a command-line interface.

How to use a Python script from an IDE or a text editor?

How To Use A Python Script - a laptop showing the webpage for the Delphi VCL and Delphi FMX UI libraries for Python

When creating larger and more complicated applications, you should use an advanced text editor or an integrated development environment (IDE).

These programs allow you to run your scripts directly from the environment. They frequently have a Run or Build command that can be accessed from the toolbar or the main menu. As was previously mentioned, PyScripter is one of your best options for this.

Embarcadero Delphi-based PyScripter aims to develop a Python IDE that can compete with the established Windows-based IDEs for other programming languages. PyScripter is a very helpful tool because it is compact, adaptable, and packed with features. Moreover, because it was designed from the ground up for Windows, it is noticeably quicker and more responsive than cumbersome text editors, all-purpose IDEs, or other Python cross-platform IDEs.

Moreover, code folding, brace highlighting, code completion, and syntax checking while you type are some of the many features of PyScripter. Additionally, Python source code tools make it easier for programmers to write code. A time-saving feature of PyScripter is the ability to drag and drop files from Explorer into this IDE. Moreover, PyScipter has great features like integrated debugging and unit testing.

Click here to learn more about this awesome IDE. In addition, Embarcadero Delphi has other interesting Python GUI tools that you can find here.

Are you ready to run your Python scripts with PyScripter?

How To Use A Python Script - a desktop screen showing the PyScripter download page in the foreground with a bokke blur applied. There are some people in the background who are sitting on chairs in discussion - they are blurred.

Running Python scripts and code is the first and most important skill you should learn if you want to get into the world of Python programming. It will be simpler for you to determine whether the code will work or not once you have a seat in the performance.

In addition to making managing your coding projects quick and easy, a good Python IDE like PyScripter also makes running those Python Scripts simple and hassle-free.

Click here and start using PyScripter to run your Python script and much more!

The post How To Use A Python Script first appeared on Python GUI.

]]>
https://pythongui.org/how-to-use-a-python-script/feed/ 0 7760
What Are The Top 5 Graph Tools For Python https://pythongui.org/what-are-the-top-5-graph-tools-for-python/ https://pythongui.org/what-are-the-top-5-graph-tools-for-python/#respond Fri, 15 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7859 Among the strongest features of Python is its endless capabilities of presenting data visually made possible by simple-to-use graph tools. The traditional matplotlib package is usually the first for the beginner Python programmer to learn....

The post What Are The Top 5 Graph Tools For Python first appeared on Python GUI.

]]>
Among the strongest features of Python is its endless capabilities of presenting data visually made possible by simple-to-use graph tools. The traditional matplotlib package is usually the first for the beginner Python programmer to learn. Matplotlib is also employed by the pandas package which is the de-facto tool used in data science. Another package called seaborn takes the plotting capabilities of matplotlib to the next level. They look particularly good when used in Python notebooks. There are alternative graph tools for Python, such as the Plotly, Bokeh and Altair packages.

Let’s start by downloading PyScripter – a great GUI for Python coding.

Why use Python graph tools?

Python is the programming language of choice for data science and machine learning. Data often comes from noisy sources, there are missing or incorrect values. In other cases, it is necessary to have an initial overview of the data before proceeding with its further processing. Data visualization is an essential first step in choosing appropriate methods of numerical analysis.

What kind of plots can one create using Python graph tools?

  • Line plot
  • Scatter plot
  • Histogram
  • Pie chart
  • Heat map
  • Contour plot
  • 3D plot
  • Animations

What is the most common Python graph tool?

Matplotlib is the traditional plotting package used in hundreds of thousands of Python packages.

Getting started

I shall start with the very basics. We need two lists of points – for the x- and the y-axis of a scatter plot.

import numpy as np
import matplotlib.pyplot as plt

X = [1,2,3,4,5]
Y = [6,7,8,9,10]

plt.plot(X,Y)
plt.show()
What Are The Top 5 Graph Tools For Python - a straight line plot

Plotting functions using the matplotlib graph tool for Python and NumPy

Let’s create a simple data set using the NumPy package and plot simple mathematical functions. We need a set of equally spaced points for the x-axis. This can be done using the arange function from NumPy. On the y-axis, we will plot some lines and curves. By the way – that IS the correct spelling of arange – think of it as “a range” not “arrange”.

I will define lambda functions. They are often considered advanced Python concepts, but they actually are very simple. A lambda function is a concise way of writing a function on one line. For example, I define the function multiply which takes two numbers a and b, and returns their product, a*b. Then I set the Y values that we want to plot by calling the multiply function and giving as parameters the list of points on the x-axis and a number.

I will define two lines, one for which every value of y is the same as x, and another one where y is twice as big as x.

import numpy as np
import matplotlib.pyplot as plt

X = np.arange(0,100)
multiply = lambda a,b: a*b
Y1 = multiply(X,1)
Y2 = multiply(X,2)

plt.plot(X,Y1)
plt.plot(X,Y2)
plt.show()
What Are The Top 5 Graph Tools For Python - two straight line plots

We can plot curves, as well. A simple parabola is defined by x2, so I can again use the multiply function to create the points.

Y3 = multiply(X,X)
What Are The Top 5 Graph Tools For Python - a curved line plot

How to change colours and line styles

Python automatically assigns different colours to lines, however, sometimes it is useful to change them. This can be done by specifying the name of the colour. A full list of colours is available online by searching for CSS colours.

plt.plot(X,Y1,color='lightgreen')
plt.plot(X,Y2,color='royalblue')
plt.plot(X,Y3,color='mediumorchid')

Lines can be plotted in different styles such as dotted or dashed. This is set by the parameter linestyle.

plt.plot(X,Y1,linestyle='dashed')
plt.plot(X,Y2,linestyle='dotted')
plt.plot(X,Y3,linestyle='dashdot')
What Are The Top 5 Graph Tools For Python - a curved line plot showing different line types

There is a shorter way of defining line type and/or colour. For example, a red dashed line is defined by

plt.plot(X,Y1,'r--')

A blue dotted line can be made using

plt.plot(X,Y2,'b:')

And a green dot-dash line is simply

plt.plot(X,Y3,'g-.')

The points can be individually drawn as markers. This is similar to the syntax above. There are many marker styles – points, squares, triangles and more.

plt.plot(X,Y1,'r.')
plt.plot(X,Y2,'bo')
plt.plot(X,Y3,'g^')
What Are The Top 5 Graph Tools For Python - curved line plots with symbols for the data points

Line thickness can be adjusted using the linewidth property.

plt.plot(X,Y1,linewidth=1)
plt.plot(X,Y2,linewidth=2)
plt.plot(X,Y3,linewidth=3)
What Are The Top 5 Graph Tools For Python a curved line plot with differing line thicknesses

How to set labels?

import numpy as np
import matplotlib.pyplot as plt

X = np.arange(0,20)

multiply = lambda a,b: a*b
Y1 = multiply(X,1)
Y2 = multiply(X,2)
Y3 = multiply(X,X)

plt.plot(X,Y1,label='Y = X')
plt.plot(X,Y2,label = 'Y = 2*X')
plt.plot(X,Y3,label = 'Y = X$^2$')

plt.legend()
plt.title('Plotting simple functions')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
What Are The Top 5 Graph Tools For Python - three curved lines from a function

How to best plot large amounts of data?

Large amounts of data are usually processed using the pandas package. It utilises matplotlib to make some basic plots of the data, including line plots, histograms, and bar graphs. Advanced examples are available in the documentation of pandas.

I have downloaded a small part of the famous iris data set in CSV format. It contains various data about a large number of properties of three species of iris flowers, including sepal length and width and petal length and petal width.

Loading data with pandas

The code below loads the data about the iris flowers into a data frame. It automatically assigns the names of the columns as given in the CSV file. Pandas employs the plotting methods from matplotlib to easily create graphs. I will plot the sepal length and width as a histogram.

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("iris.csv")

print(data)

data["sepal_length"].plot(kind = "hist", label = "sepal_length")
data["sepal_width"].plot(kind = "hist", label = "sepal_width")

plt.legend()
plt.show()

The output looks like this:

     sepal_length  sepal_width  petal_length  petal_width    species
0             5.1          3.5           1.4          0.2     setosa
1             4.9          3.0           1.4          0.2     setosa
2             4.7          3.2           1.3          0.2     setosa
3             4.6          3.1           1.5          0.2     setosa
4             5.0          3.6           1.4          0.2     setosa
..            ...          ...           ...          ...        ...
145           6.7          3.0           5.2          2.3  virginica
146           6.3          2.5           5.0          1.9  virginica
147           6.5          3.0           5.2          2.0  virginica
148           6.2          3.4           5.4          2.3  virginica
149           5.9          3.0           5.1          1.8  virginica

[150 rows x 5 columns]
What Are The Top 5 Graph Tools For Python - side by side bar graphs of different sepal lengths

Pandas is rich in features and it would take several more articles to go into all possible details. More information and examples can be found in the documentation of pandas.

How to plot multiple plots at once?

While matplotlib is the traditional Python graph tool, but there are plenty of parameters to set. Pandas significantly simplifies the process.

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("iris.csv")

data.plot(subplots=True)

plt.legend()
plt.show()
What Are The Top 5 Graph Tools For Python - different plots at the same time

How to make plots even more pleasing?

The pandas graphs are quite okay and tell clearly the distribution of the data, however, there is room for improvement. The seaborn package brings in significant improvements.

The data distribution can be visualised as a histogram using the following code.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

iris = pd.read_csv("iris.csv")

sns.set_style("whitegrid")
sns.distplot(iris['sepal_length'])

plt.show()
What Are The Top 5 Graph Tools For Python a hybrid graph of bars and a line

A more detailed plot of the correlation between the data is also very simple to do.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

iris = pd.read_csv("iris.csv")
sns.pairplot(data = iris)

plt.show()
What Are The Top 5 Graph Tools For Python - multiple plot types

What alternatives are there to matplotlib?

What is Plotly like?

Plotly was originally written for Javascript. It can make graphs, as well as interactive plots. It has an amazing set of features, including plotting data on geographical maps. The code below creates a local server and opens the view in the browser where the user can rotate the globe and hover with the mouse for more details. This Python graph tool is very handy, and it is not necessary to know any Javascript at all.

import plotly.express as px

df = px.data.gapminder().query("year==2007")
fig = px.scatter_geo(df, locations="iso_alpha", color="continent",
                     hover_name="country", size="pop",
                     projection="orthographic")
fig.show()
What Are The Top 5 Graph Tools For Python a map of the world

What are the benefits of Bokeh?

Bokeh is a professional tool for advanced users. It also produces interactive plots. There is a detailed tutorial on their webpage, creating Jupyter notebooks to test out. It is definitely worth trying.

How about Altair?

Altair is user-friendly, yet very powerful. Below I am using again the iris data set.

Internally, Altair prepares a json-style string that defines the plot. It can save the output as an HTML file with the graph embedded.

import pandas as pd
import altair as alt
import matplotlib.pyplot as plt

data = pd.read_csv("iris.csv")

chart = alt.Chart(data).mark_bar().encode(
    x='petal_length',
    y='petal_width',
)

chart.save('chart.html')
What Are The Top 5 Graph Tools For Python - lots of bars on a chart

Conclusion

There are many graph tools for Python. They offer a wide variety of tools and settings for the plots. It is mostly up to personal preference which one you will like best. It is excellent for the beginner Python coder.

Check out these five graph tools in PyScripter today.

The post What Are The Top 5 Graph Tools For Python first appeared on Python GUI.

]]>
https://pythongui.org/what-are-the-top-5-graph-tools-for-python/feed/ 0 7859
How To Use Data Visualization Tools In Python https://pythongui.org/how-to-use-data-visualization-tools-in-python/ https://pythongui.org/how-to-use-data-visualization-tools-in-python/#respond Thu, 14 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7894 The ability to create graphics programmatically is a very sought-after skill set due to the rising demand for Data Science and Analytics skill sets. Combining specific well-known Python data visualization modules with Python4Delphi will help...

The post How To Use Data Visualization Tools In Python first appeared on Python GUI.

]]>
The ability to create graphics programmatically is a very sought-after skill set due to the rising demand for Data Science and Analytics skill sets. Combining specific well-known Python data visualization modules with Python4Delphi will help you quickly resolve the issue (P4D). P4D is a collection of free, powerful data visualization tools in Python that you can use to interact with Delphi scripts, modules, and types to construct Windows GUIs quickly. So, naturally, in this article, we will learn how to use the best data visualization tools Python has available along with some best practices. So, let’s get started.

Why is data visualization essential today?

How To Use Data Visualization Tools In Python - a laptop showing a data visualization of some graphs

Data visualization is a multidisciplinary field that deals with the graphic representation of data. It is an effective communication method when the info is varied and may be confusing. Furthermore, data visualization is essential because it makes the data understandable to a wider audience, whether it takes the shape of charts, graphs, or other representations. So, developers must know how to use data visualization tools Python.

Users of data for business can gain insight into vast amounts of data through data visualization. As developers or users, we benefit from identifying fresh patterns and flaws. As users we can concentrate on areas that signal danger or advancement. The company advances thanks to this procedure.

What are the best libraries for data visualization in Python? 

How To Use Data Visualization Tools In Python - an image of several people sitting around a table with a large screen behind them showing a data visualization with a stacked bar graph

Python has numerous libraries that provide the best data visualizations, but some of the best include Matplotlib, Bokeh, and Plotly.

Matplotlib is a comprehensive and popular Python library for creating static, animated, and interactive visualizations. Matplotlib creates publication-quality figures in various physical formats and cross-platform interactive settings. The Python and IPython shells, web application servers, and several graphical user interface toolkits (in this post, Python GUI by Delphi’s VCL using P4D!) all support the use of Matplotlib.

For contemporary web browsers, Bokeh is an interactive visualization library. It allows for high-performance interactivity over large or streaming datasets and offers elegant, concise construction of versatile graphics. Anyone who wants to create interactive plots, dashboards, and data applications quickly and simply can do so with the aid of Bokeh.

A browser-based, interactive, open-source data visualization library for Python is called Plotly or plotly.py. It is a high-level, declarative charting library built on top of plotly.js. Plotly.js comes with more than 30 different chart types, including financial, scientific, and 3D graphs. Plotly is MIT licensed software.

How can you use Matplotlib with P4D?

The Python Matplotlib library provides multiple tools for working with graphics. Using this library, you can design graphics, legends, style sheets, color schemes, and manipulate images.

Thanks to matplotlib, users also can create, adapt, and extend existing functionalities.

Is it possible to create annotated heatmaps with Python? Is there an example?

Yes, this is just one of the many possible real-life use cases that Maplotlob is used for.

Let’s see a code example:

import numpy as np
import matplotlib.pyplot as plt


category_names = ['Strongly disagree', 'Disagree',
                  'Neither agree nor disagree', 'Agree', 'Strongly agree']
results = {
    'Question 1': [10, 15, 17, 32, 26],
    'Question 2': [26, 22, 29, 10, 13],
    'Question 3': [35, 37, 7, 2, 19],
    'Question 4': [32, 11, 9, 15, 33],
    'Question 5': [21, 29, 5, 5, 40],
    'Question 6': [8, 19, 5, 30, 38]
}


def survey(results, category_names):
    """
    Parameters
    ----------
    results : dict
        A mapping from question labels to a list of answers per category.
        It is assumed all lists contain the same number of entries and that
        it matches the length of *category_names*.
    category_names : list of str
        The category labels.
    """
    labels = list(results.keys())
    data = np.array(list(results.values()))
    data_cum = data.cumsum(axis=1)
    category_colors = plt.get_cmap('RdYlGn')(
        np.linspace(0.15, 0.85, data.shape[1]))

    fig, ax = plt.subplots(figsize=(9.2, 5))
    ax.invert_yaxis()
    ax.xaxis.set_visible(False)
    ax.set_xlim(0, np.sum(data, axis=1).max())

    for i, (colname, color) in enumerate(zip(category_names, category_colors)):
        widths = data[:, i]
        starts = data_cum[:, i] - widths
        ax.barh(labels, widths, left=starts, height=0.5,
                label=colname, color=color)
        xcenters = starts + widths / 2

        r, g, b, _ = color
        text_color = 'white' if r * g * b < 0.5 else 'darkgrey'
        for y, (x, c) in enumerate(zip(xcenters, widths)):
            ax.text(x, y, str(int(c)), ha='center', va='center',
                    color=text_color)
    ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1),
              loc='lower left', fontsize='small')

    return fig, ax


survey(results, category_names)
plt.show()

How do I start visualizing data with Python in Windows?

With so many online tools and libraries for data visualization, the entry barrier for producing engaging data visualization is lower than ever.

However, Python has so many options available that choosing where to start can be challenging. Any Python data visualization module can be combined with Embarcadero’s Delphi using Python4Delphi (P4D), allowing you to start developing Windows GUI applications.

If you know how to use P4D and Matplotlib, the only other tool you’ll need is an advanced IDE. Without a doubt, PyScripter is the most widely used Python scripting tool.

PyScripter is a lightweight IDE to add to the existing excellent Python for Delphi (P4D) components. It provides a state-of-the-art scripting solution for Delphi applications making it a popular choice amongst veteran developers.

Are you ready to use data visualization tools in Python?

How To Use Data Visualization Tools In Python - a desk with a laptop on it showing the download screen for the Embarcadero Python tools, Delphi and RAD Studio

The sheer number of available modules may be overwhelming if you’re new to Python visualization. Additionally, some libraries might be better suited for a given circumstance than others. You should be able to distinguish between the varied features of each library and make an informed decision.

You have now learned how to use Python for Delphi to run the three key data visualization libraries, and you can use plots produced by the Plotly library and Python4Delphi to solve various real-world problems.

PyScripter offers all the features one would anticipate from a contemporary Python IDE in a compact package. Additionally, it is natively compiled for Windows to use little memory while performing at its best. The IDE is also open-source and was created entirely in Delphi with Python scripts for extensibility. Most Python data analysts favor PyScripter because of its many outstanding features.

Now that you understand the finest data visualization library in Python click here and start using P4D today.

The post How To Use Data Visualization Tools In Python first appeared on Python GUI.

]]>
https://pythongui.org/how-to-use-data-visualization-tools-in-python/feed/ 0 7894
What Are Native Python Development Tools? https://pythongui.org/what-are-native-python-development-tools/ https://pythongui.org/what-are-native-python-development-tools/#respond Fri, 08 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7359 In the application design and development cycle, each programming language has its own significance and applications. Python is growing rapidly and is quickly becoming one of the most popular programming languages in use today. However,...

The post What Are Native Python Development Tools? first appeared on Python GUI.

]]>
In the application design and development cycle, each programming language has its own significance and applications. Python is growing rapidly and is quickly becoming one of the most popular programming languages in use today. However, if you are a beginner setting up an effective development environment can be tricky (here is a step by step guide to help you get started with Python). It’s not always simple to develop good habits and find the necessary tools. The tools you employ will be defined by the project’s aim, dependencies, and system requirements. IDEs, libraries, and packages are all available as Python native development tools. 

In this article, we’ll talk about what are Python native development tools and take a look at the most important Python development tools.

Why is a Python IDE important?

What Are Native Python Development Tools? An image of a person pointing to a laptop screen with the PyScripter IDE running in it

IDE is an abbreviation for Integrated Development Environment. It’s a coding tool that makes it simple to write, test, and debug code by using highlighting, resource management, compilers, debugging tools, and other software development necessities. Even though the IDE is a well-defined concept, it is being redefined as other tools, such as notebooks, gain functionality that was previously only available in IDEs. This tool combines several technologies designed specifically for software development.

So, right from the start, your IDE will be critical. IDEs are typically chosen based on a developer’s preferences, but some are better suited for specific purposes than others. It’s also worth noting that switching between the two is a breeze. It’s as easy as opening a text document in Microsoft Word or Notepad, so deciding which to use isn’t difficult. You’ll probably switch between a few until you find something that works for you.

Having said that, PyScripter is a well-known and well-liked IDE among Python developers.

Why is Pyscripter the best of the native Python development tools?

What Are Native Python Development Tools? An image of laptop balanced in a person's lap. The laptop is showing the PyScripter project page.

PyScripter began as a lightweight integrated development environment (IDE) intended to complement the existing Python for Delphi (P4D) components by providing a robust scripting solution for Delphi applications.

It has grown into one of the greatest, full-featured, stand-alone Python IDEs thanks to the help of P4D developer Morgan Martinez and a few early users. It’s written in Delphi using P4D and the SynEdit component, although Python programmes can be added.

PyScripter is has quite a modern user interface, but is currently only available for Microsoft Windows. It is faster than some of the other IDEs because it is written in a compiled language, and it has a diverse set of features that make it a useful Python programming environment.

PyScripter’s goal is to create a Python IDE capable of competing with commercial Windows-based IDEs for other languages. PyScripter is a fantastic tool. Rich in features, lightweight, adaptable, and expandable. Since it was fundamentally built for Windows, it is significantly faster and more responsive than bloated text editors, general-purpose IDEs, or other Python cross-platform IDEs.

PyScripter includes a Python interpreter with quick call hints and code completion. This software remembers command history and lets you run scripts without saving them. This IDE also includes a remote Python debugger for Python debugging. As a result, the user may see variables, the call stack, and the watch window. Thread debugging and conditional breakpoints can also aid in Debugging. Debugger indicators are also useful when the programmer is unable to locate the error in his code. You can not only damage your files by not saving them, but you can also debug them without saving, which is a useful feature.

Pyscripter has many other features including brace highlighting, code folding, code completion, and syntax checking as you type (there are many others which you can learn about in the documentation). A programmer must investigate this software in order to comprehend it. Furthermore, programmers can utilize Python source code tools to make programming easier. Finally, you can drag and drop files from Explorer into this IDE, potentially saving you time.

Thus PyScripter is unrivalled in terms of Python native development tools. So if you wish to download PyScripter head on over to their page now by clicking the link here.

Why are Python packages and libraries important native Python development tools?

What Are Native Python Development Tools? A laptop showing the download page for the VCL and FMX libraries

Python’s libraries are among the most well-documented and up-to-date code resources available, and its object-oriented, dynamically typed, interpreted, interactive programming language excels at rapid, iterative development. The number of Python packages and libraries grows year after year. Companies invest in developing a Python library in order to attract developer users. As a beginner you will find some specialised libraries for your use, but there are some useful packages to be aware of. DelphiVCL and DelphiFMX are two such examples.

What is DelphiVCL?

Python for Delphi (P4D) is a free component set for Delphi and Lazarus that includes Python DLL support (FPC). They make it easier to run Python programs and create new Python modules and types.

DelphiVCL for Python focuses on native Windows development and exclusively employs the VCL framework for Windows, whereas DelphiFMX for Python uses the cross-platform FireMonkey framework to provide a comprehensive and versatile GUI framework for Windows, Linux, macOS, and Android.

What is DelphiFMX?

FireMonkey (FMX) Stencils can be used by designers working with developers in RAD Studio, Delphi, or C++Builder to create multi-device apps. They improve communication between designers and developers, making it even easier to take advantage of the FMX Framework’s limitless creative possibilities with UI components and styles.

FireMonkey is Delphi’s cross-platform GUI library (FMX). It uses OpenGL or DirectX GPU hardware acceleration to create clean, modern, and high-performance user interfaces. DelphiFMX Python module also supports Python development on Windows, macOS, Linux, and Android. Check out this article to get an introduction to DelphiVCL.

What other Python development tools are out there?

What Are Native Python Development Tools? A screenful of icons on a laptop

PyCharm is a professional development IDE. JetBrains, a company known for producing excellent software development tools, created it. PyCharm comes in two flavours: Community and Professional. PyCharm has all of the major features that a good IDE should have, including code completion, code inspections, error highlighting and fixes, debugging, a version control system, and code refactoring. All of these features are standard.

Scientific development uses another common IDE called Spyder. This open-source IDE includes basic features like syntax highlighting and auto-completion, as well as many scientific libraries. It is open-source and free, and installation is a breeze thanks to the Python package manager.

Atom, Jupyter Notebook, and Sublime Text are some other Python development tools. Similarly, Python libraries such as TensorFlow, Requests, and Numpy each serve a specific purpose. However, PyScripter, DelphiVCL, and DelphiFMX remain popular development tools among users.

Are you ready to use the best Python development tools?

What Are Native Python Development Tools? A laptop with the PyScripter download page displaying.

A good set of tools is essential for any excellent developer. A developer spends most of his time writing in an IDE. He’ll most likely be working on numerous projects at once, so having a system in place to keep track of them is essential.

Python is unrivaled in terms of its simplicity, sophistication, and versatility. After three decades, its perch atop the computer language pyramid is more than secure. It’s a reliable workhorse that can handle almost any situation. If a developer-only has time to learn one language, Python is the one to learn.

Python development tools such as IDEs, virtual environments, and libraries provide you additional flexibility. In a favourable growth environment, you will feel more confident and productive. When you are comfortable with your setup programming, Python becomes much more enjoyable and engaging, and this is when you gain success.

Now that you’ve learned a lot about Python programming tools, click here to begin your journey with one of the greatest.

The post What Are Native Python Development Tools? first appeared on Python GUI.

]]>
https://pythongui.org/what-are-native-python-development-tools/feed/ 0 7359
The Best Python Debugging Tools – PyScripter vs. JupyterLab https://pythongui.org/the-best-python-debugging-tools-pyscripter-vs-jupyterlab/ https://pythongui.org/the-best-python-debugging-tools-pyscripter-vs-jupyterlab/#respond Thu, 07 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7495 Python is a favorite language amongst developers. It is a powerful and versatile language used to construct various applications, including internet apps, software and game creation, network programming, and graphical user interfaces (GUIs). Python’s popularity...

The post The Best Python Debugging Tools – PyScripter vs. JupyterLab first appeared on Python GUI.

]]>
Python is a favorite language amongst developers. It is a powerful and versatile language used to construct various applications, including internet apps, software and game creation, network programming, and graphical user interfaces (GUIs). Python’s popularity has increased due to its simplicity, simple syntax, active community, and free Python IDEs such as JupyterLab, PyCharm, PyScripter, Visual Studio Code, etc. Developers use various tools during the writing, creation, and testing software. However, not all Python debugging tools are created equal. Thus, many aspiring developers that are learning Python are also looking for the best Python development tool.

Therefore, in this article, we will compare the very best Python debugging tools in the market, PyScripter, and JupyterLab, comparing their advantages and capabilities and finding out which is the best.

How can we accurately compare these two IDEs and their Python debugging tools?

The Best Python Debugging Tools - PyScripter vs. JupyterLab - a laptop showing the download page for PyScripter

PyScripter and JupyterLab are the two most popular IDEs in the Market. They offer numerous advantages that make them the best Python debugging tools, but each has advantages and disadvantages. If you’re new to Python, this step-by-step guide to Python Scripting will get you started. So without any further delays let us compare the two Python IDEs:

Are PyScripter and JupyterLab lightweight IDEs?

Integrated development environments (IDEs) are programs that aid in developing other programs. Furthermore, IDEs attempt to incorporate all programming tasks into a single application. One of the primary advantages of an IDE is that it provides a centralized interface for all of the tools required by a developer. However, not all IDEs are the same.

A lightweight IDE is faster, more elegant, and eases the design process for developers. In addition, a lightweight IDE works on a project level, loads much more data at the start, analyzes the project structure if needed, and so on. Thus choosing a good IDE is a critical task. Thankfully, all of the best IDEs are lightweight, including JupyterLab and PyScripter. 

However, JupyterLab’s IDE works in a lightweight web-based interactive computing environment and does not require the Python Jupyter server to start on its host. In contrast, PyScripter is a native lightweight IDE which makes it superior to JupyterLab, thus making it a favorite amongst developers.

Which of these two Python IDEs is easy to use and set up?

Ease of use and setup is essential when it comes to IDEs. Therefore, developers find themselves at odds when selecting the IDE to use. There are many good IDEs and text editors available in the market. However, none comes close to matching the superiority of PyScripter.

JupyterLab is a lightweight IDE. However, it is lightweight only when running on a web client. In addition, natively running JupyterLab will also run the Python Jupyter server, which defeated its lightweight characteristic. Consequently, making JupyterLab a lightweight IDE requires an extensive first-time setup that many aspiring developers cannot do.

In contrast, PyScripter is a ready-to-install IDE making it extremely popular amongst developers. 

Do the Python debugging tools support Python Code autocomplete?

A programmer might sometimes take hours to remedy an error when programming or coding. Autocomplete tools are quite helpful since they allow people to complete code faster while decreasing mistakes. Using an IDE with code autocomplete to develop a project in Python may make things a lot simpler. Moreover, an IDE can assist you in formatting your code to make it more readable and understandable.

Both JupyterLab and PyScripter support Code Autocomplete, making it popular. However, JupyterLab does not have the Autocomplete feature enabled by default. This gives the impression that JupyterLab does not support Autocomplete to aspiring developers. In contrast, PyScripter has a fantastic autocomplete feature that is enabled by default. This feature makes it easy to use, making it a favorite amongst developers.

Does the IDE Support an Interactive Developing Environment?

Python is an interpretive language, meaning each line of code is run one after another.  As we all know, the computer cannot understand our language and can only grasp machine language, also known as binary language. As a result, the Python interpreter translates user-written Python code into a language that computer hardware or systems can comprehend every time you execute your Python script. One of the interpreter’s advantages is that you can initiate an interactive session with it and input Python code to see what it performs. This is a fantastic approach to testing out new programming concepts.

Most IDEs require you to run Python to see the output of a specific piece of code. JupyterLab, on the other hand, can evaluate Python statements inline, providing you with immediate feedback on the interactive use of the interpreter while saving your changes. Similarly, PyScripter evaluates inline Python statements without the need for breakpoints. It also provides immediate feedback, but it is lightweight and faster than JupyterLab.

Do PyScripter and JupyterLab have an embedded debugger?

The Python debugger is a source code debugger for Python applications that may be used interactively. For example, it may set conditional thresholds and single-stepping. It also allows you to inspect stack frames, see source code, and run any Python code in any stack frame’s context. Debugging is crucial because it enables software engineers and developers to fix bugs before releasing a program to the public. It’s an add-on to testing, which entails determining how an error affects a program. As a result, Python debugging tools are essential for Python programming. It is something that distinguishes good Python programming software from bad.

By default JupyterLab and PyScripter have integrated Python debugging tools. However, PyScripter offers an integrated Python debugger, variables, and watch windows, and the call stack is all accessible to the user. Moreover, the programmer can use conditional breakpoints or thread debugging to help with debugging. Furthermore, PyScripter includes a visual debugger that allows to interactively set breakpoints, step into functions, and inspect variables. In addition, debugger hints are also beneficial when the programmer cannot locate the error in his code. You may not only run your files without saving them, but you can also debug them without saving, which is an excellent addition.

This makes PyScripter a superior choice to JupyterLab.

Is file management a feature in the Python IDE?

File management tools are utility software that manages files of the computer system. Since files are a vital part of the system, all the data is stored in the files. Therefore, this utility software help to browse, search, arrange, find information and quickly preview the system’s files.

However, some IDEs include file management as a function. JupyterLab, for instance, allows you to work with documents and activities like Jupyter notebooks, terminals, and custom components in a flexible, integrated, and extendable way. Similarly, with PyScripter, you may use tabs and splitters to organize different documents and activities in the work area. It also has a single architecture for viewing and manipulating data formats. JupyterLab can show rich kernel output in various file formats, including pictures, CSV, JSON, Markdown, PDF, Vega, Vega-Lite, and others.

Which is these two Python IDEs has the best Python debugging tools?

The Best Python Debugging Tools - PyScripter vs. JupyterLab - a laptop showing the PyScripter source code download page

Developers use integrated development environments to facilitate their work. They help make the coding process more streamlined and straightforward, especially for complex codes. 

Furthermore, choosing an IDE software depends on the project’s scope and other factors such as programming language, version control system, etc. Of course, businesses must also consider their budget and personal preferences. However, As proven by the emergence of analysts and data scientists, Python is a robust programming language that can be used to build a variety of applications. Python’s popularity has risen as a result of this. Furthermore, a solid Python IDE makes it simple to manage your coding development.

PyScripter is the best IDE and contains a debugger and numerous sophisticated features such as code recommendations. In addition, because it is developed in a compiled language, it is significantly quicker than other Python IDEs. It also supports numerous other features which makes it superior and explains its high ratings.

Now that you know what makes PyScripter the best IDE click here and join the PyScripter community to experience the best free Python IDE.

The post The Best Python Debugging Tools – PyScripter vs. JupyterLab first appeared on Python GUI.

]]>
https://pythongui.org/the-best-python-debugging-tools-pyscripter-vs-jupyterlab/feed/ 0 7495
What You Need And Where To Go To Write Code In Python https://pythongui.org/what-you-need-and-where-to-go-to-write-code-in-python/ https://pythongui.org/what-you-need-and-where-to-go-to-write-code-in-python/#respond Wed, 06 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7724 Given the tech industry’s tremendous growth and demand, it’s worth taking a closer look at Python’s unique benefits and applications. Python has become one of the twenty-first century’s most exciting and profitable programming languages. It...

The post What You Need And Where To Go To Write Code In Python first appeared on Python GUI.

]]>
Given the tech industry’s tremendous growth and demand, it’s worth taking a closer look at Python’s unique benefits and applications. Python has become one of the twenty-first century’s most exciting and profitable programming languages. It created everything from Netflix’s recommendation system to the software that runs self-driving cars. Moreover, Python’s rising popularity can be attributed to its straightforward syntax, which appeals to experienced and inexperienced developers. However, because of its adaptability and growing community, it appeals to many developers. Furthermore, in recent years, its employment in simpler domains has grown in favor. Thus, it has become more important for developers to know about a good Python program maker and where to write code in Python.

Because of the rising demand for Python worldwide, many of the top Python IDEs have been created. PyScripter is a free, open-source Python IDE that comes with a lot of features that are covered by the MIT license. This article will discuss the importance and characteristics of a good Python program maker.

Why is Python an important programming language?

Python is everywhere and has proven its worth time and time again. While maintaining simplicity and readability, it can provide scalability, stability, fast processing, and I/O performance.

Python’s popularity is growing due to its simple syntax, which appeals to experienced and inexperienced programmers. In addition, many developers like it because of its adaptability and growing community. As a result, Python is known as the “Swiss Army Knife” of programming languages. It’s not picky about platforms as a programming language, and it works equally well on Windows, Linux, and macOS.

Many IDEs make Python development even easier and more intuitive. It comes as a result of the high demand for Python around the world.

Is an IDE another name for a Python program maker?

What You Need And Where To Go To Write Code In Python - an image of the PyScripter IDE

IDE refers to the Integrated Development Environment. It’s a coding tool that makes it easy to write, test, and debug your code through its code highlighting, resource management, compilers, debugging tools, and all the other software development essentials. Therefore even while the IDE is a well-defined notion, it is beginning to be redefined as other tools, such as notebooks, gain more and more functionality previously only available in IDEs.

Most integrated development environments (IDEs) handle a wide range of programming languages and provide many additional features. As a result, they may be large, and downloading and installing them may take a long time. In addition, you may need advanced knowledge to use them effectively.

IDEs help organize the various components of a computer program. It’s not always straightforward to pick the best-integrated development environment (IDE) for your needs. There are a plethora of options available. There are a lot of interesting IDEs out there, each with its unique set of features that can help you code faster, be more productive, and prevent mistakes. Most quality coding software can debug and execute code. The top also uses source control systems.

So, one of the most essential questions in Python programming is where to code in Python or which IDE to use.

Which of the Python tools is the best for writing Python code?

What You Need And Where To Go To Write Code In Python- an image showing the download page for PyScripter

PyScripter began as a lightweight IDE to supplement the great Python for Delphi (P4D) components by providing a reliable scripting solution for various GUI and Delphi applications.

It has now grown into an amazing, fully-featured, stand-alone Python IDE, thanks to the support of Morgan Martinez, a P4D developer, and many early users. 

Moreover, PyScripter has a modern user interface and is currently only available for Microsoft Windows operating systems. In addition, PyScripter is written in a compiled language. Consequently, this makes it faster than most other IDEs, and it has a diverse set of features that make it a useful Python programming environment.

PyScripter aspires to build a Python IDE that can compete with commercial Windows-based IDEs for other languages. Furthermore, PyScripter is an excellent, Feature-rich, lightweight tool that is adaptable and expandable. Moreover, it is significantly faster and more responsive on Windows than most other bloated text editors, general-purpose IDEs.

What features does PyScripter offer?

PyScripter has several distinguishing features that make it stand out from its competition. To begin with, its syntax highlighting feature makes the user’s life much easier. Moreover, some other features include brace highlighting, code folding, split-view file editing, syntax checking as you type, search and replace, and the use of Python source code tools ((un)tabify, (un)comment, (un)indent, and so on) are all possible with this functionality. Additionally, the user is fully supported for encoded Python source files and context-sensitive Python keyword help. Finally, PyScripter also handles files dropped from Explorer, which might save you a lot of time.

PyScripter has a built-in Python interpreter, making code development easier with its quick call hints and code completion. Moreover, it keeps track of command history and allows you to run scripts without saving them. PyScripter also supports a remote Python debugger, which allows for Python debugging. As a result, developers may see variables, the watch window, and the call stack. Moreover, programmers can use conditional breakpoints or thread debugging to help with debugging. Debugger indications are also beneficial when the programmer cannot locate the error in his code.

In addition, Not only can one run their files without saving them, but they can also debug without saving, which is a bonus. PyScripter ensures automatic test generation, allowing you to perform automated unit testing. This IDE also includes a fantastic unit testing GUI (which you can learn more about here). Moreover, its unit tests window offers an advanced graphical user interface for running unit tests, a standard Python module.

PyScripter offers several other technical features that you can find here.

Finally, PyScripter is always rated highest compared to its competitors because of its ease of use and premium features. Moreover, PyScripter will charge customization expenses if you require unique features in your system to meet your specific business demands. These costs will vary depending on your needs and feature requirements.

Do you know all about the best Python IDE?

What You Need And Where To Go To Write Code In Python - an image of a person writing code on a screen

Python is crucial because, as is evident by the rise of analytics and business intelligence. In addition, it is increasingly being used in a wide range of computing and scientific applications. 

A solid Python IDE makes managing your coding projects quick and easy. Pyscripter is the best IDE making development easier with advanced features like code recommendations and a debugger. Furthermore, it has many other features that make it an excellent Python programming environment.

You must be eager to try out all the features and start coding in the best IDE. So, go ahead and click here to write code in PyScripter efficiently.

The post What You Need And Where To Go To Write Code In Python first appeared on Python GUI.

]]>
https://pythongui.org/what-you-need-and-where-to-go-to-write-code-in-python/feed/ 0 7724
The Best Python Debugging Tools – PyScripter vs VS Code https://pythongui.org/the-best-python-debugging-tools-pyscripter-vs-vs-code/ https://pythongui.org/the-best-python-debugging-tools-pyscripter-vs-vs-code/#respond Tue, 05 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7480 One of the most widely used programming languages is Python. It offers a lot of debugging tools that are far more efficient and practical than putting a print statement after every couple of lines of...

The post The Best Python Debugging Tools – PyScripter vs VS Code first appeared on Python GUI.

]]>
One of the most widely used programming languages is Python. It offers a lot of debugging tools that are far more efficient and practical than putting a print statement after every couple of lines of code. In addition, debugging IDEs such as Visual Studio Code, PyScripter among others, have built-in Python debugging tools making it easy for developers to debug a code inside an all-in-one environment.

Code debugging is one of the most critical and time-consuming chores a developer must undertake. When your code performs strangely, crashes, or simply returns incorrect results, there is some problem in the code. Every IDE has its features and tools that make some IDEs more suitable than others for various development tasks.

This article will look at two Python debugging IDEs, PyScripter and Visual Studio Code, showcasing their benefits and features and determining which debugging IDE is the best.

What are the benefits of using an IDE with built-in Python debugging tools?

The Best Python Debugging Tools - PyScripter vs VS Code. An image showing a Python IDE in action

Without IDEs, developers would have to spend a significant amount of time customizing numerous development tools, which would be stressful and time-consuming. In addition, developers may have such skills merged into one location using an IDE, eliminating the need to switch between separate tools.

By encouraging holistic thinking, IDEs aid in streamlining development chores. They may think of activities covering the complete development lifecycle rather than separate jobs. IDEs also increase productivity since they can read codes, verify grammar, and receive feedback when syntax problems occur. They also have features and tools that help them manage resources, take shortcuts, and avoid blunders.

How are PyScripter and Visual Studio Code (VS Code) different?

The Best Python Debugging Tools - PyScripter vs VS Code - an image of a desk with an all-in-one computer on it showing a Python4Delphi overview. In the background are two monochrome pictures of leaves.

Is Python debugging Included in the IDEs?

The Python debugger is a source code debugger that may be used interactively to debug Python programs. It might, for example, set conditional thresholds and single-step. You may also inspect stack frames, see source code, and run any Python function in the context of any stack frame. Before releasing a product to the public, software engineers can utilize debugging to fix bugs. Python debugging tools are essential for Python programming because they help distinguish between good and bad Python programming software.

Syntactic and semantic mistakes are the two forms of programming faults in any code produced in any programming language. Syntactic mistakes happen when a command is mistyped, when a variable or function is used without being defined, or when the indentations in your code are incorrect. These mistakes are usually simple to remedy if you follow Python Traceback’s instructions. 

On the other side, there are mistakes known as semantic errors. These problems occur when your code executes but produces incorrect results or when your code performs differently than planned. Debugging is the only method to find and repair the fault in your code causing the error. So when most of us encounter a bug, the first thing we do is use a slew of print statements to monitor the execution of the code and locate the error.

In PyScripter, the user has access to a built-in Python debugger. This section offers debugger hints, which are helpful when a programmer cannot locate a flaw in his code. Furthermore, you may not only run but also debug your files without having to save them, which is a benefit. On the other hand, Visual Studio Code also has an integrated debugger but is a little tricky to use, favoring PyScripter.

Do the IDEs accept third-party software?

Third-party softwares or external Tools are defined in PyScripter and can work alone or in conjunction with the IDE editor. PyScripter may be smoothly integrated with your favorite Python tools or command-line programs if you choose tools with substantial flexibility. You may define or alter external tools using the “Tools|Configure Tools” menu item. The PyScritper.ini file stores the tool definitions. PyScripter includes external tools such as PyLint, TabNanny, Profile, etc. To learn more about PyScripter’s external tools, you can look at this documentation.

On the other hand, Visual Studio Code allows you to incorporate various tools. These technologies might aid coding productivity and data science project management.

Do the IDEs provide syntax highlighting?

Syntax highlighting uses colors and fonts to distinguish language sections in programming languages. Programmers use syntax highlighting to help them understand code more quickly and discover various forms of syntax errors. In addition, it allows you to see what each component of the statement or command performs, such as which part is a function and which part is a variable like a string.

Significant chunks of comments or code can be easily overlooked depending on what the reader is looking for. Syntax highlighting can also help programmers see errors. For example, string literals are frequently marked in different colors. Finding a missing delimiter, for example, is much easier thanks to the text’s contrasting color. Bracket matching is another important feature of many popular editors. It’s simple to tell if a bracket has been left out or to identify the match of the bracket the pointer is on by highlighting the pair in a different color.

PyScripter’s code highlighting feature is also available in Visual Studio Code.

Which of the two Python IDEs is lightweight?

Lightweight software, also known as lite software or lightweight application, is a computer program with a tiny memory footprint (RAM utilization) and low CPU usage, resulting in low system resource usage. The program should avoid software and code bloat and seek the most efficient algorithm.

PyScrtipter is an extremely light software, unlike Visual Studio Code, which needs a device with an efficient and fast processor to run smoothly.

Which Python IDE is better than the other?

The Best Python Debugging Tools - PyScripter vs VS Code - an image of a person looking at a laptop which is showing the PyScripter Python IDE

PyScripter is the best IDE, including a debugger and advanced features like code suggestions. It is substantially faster than other Python IDEs since it is written in a compiled language, which is why it is a lightweight program. In addition, it has additional features that make it an excellent Python programming environment. Naturally, the feature comparison above reveals that PyScripter is the superior package overall. It wins due to its lighter weight and smooth debugging tool performance. Even though both of these IDEs have essential features, PyScripter has a few extra. This also explains why it’s such a popular choice, with 96 percent of four and five-star reviews on SourceForge.

Click here and join us to experience the greatness of PyScripter, the most incredible Python debugging IDE available.

The post The Best Python Debugging Tools – PyScripter vs VS Code first appeared on Python GUI.

]]>
https://pythongui.org/the-best-python-debugging-tools-pyscripter-vs-vs-code/feed/ 0 7480
How To Make A Web Crawler In Python https://pythongui.org/how-to-make-a-web-crawler-in-python/ https://pythongui.org/how-to-make-a-web-crawler-in-python/#respond Fri, 01 Jul 2022 10:00:00 +0000 https://pythongui.org/?p=7743 Have you ever pondered the methods used by search engines like Google and Bing to gather the information they display in their search results? This is because search engines index every page in their archives...

The post How To Make A Web Crawler In Python first appeared on Python GUI.

]]>
Have you ever pondered the methods used by search engines like Google and Bing to gather the information they display in their search results? This is because search engines index every page in their archives so they can respond to queries with the most pertinent results. Search engines can manage this process thanks to web crawlers. Python is perhaps the fastest-growing language today being widely used in various domains, including data science and machine learning. Thus, this job calls for using the best web scraping tools Python has to offer. Therefore, developers, today must know how to make a web crawler in Python.

Web crawlers are unquestionably essential if you need to collect important data from the internet while saving significant time. Web crawling is generally the process of gathering data from the internet. This process is carried out automatically using tools like Python rather than by hand collecting the data. Naturally, this article will teach you the essentials of the best web scraping tools Python has to offer. So let’s dive right in!

What is web crawling, and why is it important?

How To Make A Web Crawler In Python - a screen showing a Python web crawler being written

Web crawling uses a program or automated script to index data on web pages. These automated scripts or programs are also called web crawlers, spiders, spider bots, or simply crawlers.

Web crawlers copy pages for a search engine to process and index, enabling users to conduct more effective searches. A crawler’s objective is to discover the subject matter of websites. This makes it possible for users to quickly and easily access any information on one or more pages.

The digital revolution has made data widely available, with new data being added every day. According to IBM, we continue to produce twice as much data as we consume every two years, which claimed that 90 percent of the world’s data had been generated in just the previous two years.

Nevertheless, almost 90% of data is unstructured, and web crawling is essential to index all unstructured data so that search engines can return accurate results. If you are a beginner who wants to get started with Python, here is a step-by-step guide to Python scripts to help you get started.

What is the difference between web crawling and web scraping tools for Python?

How To Make A Web Crawler In Python - What is the Difference Between Web Crawling and Web Scraping

Data is king when it comes to web scraping. For example, the information fields you want to take from particular websites. It makes a significant difference because, with scraping, you typically know the target websites; you may not know the precise URLs of the individual pages, but at least you know the domains.

With crawling, you most likely aren’t familiar with the precise URLs or the domains. Crawling helps locate URLs for later use.

In short, web scraping is extracting data from one or more websites, in comparison, crawling focuses on locating URLs or links on the internet.

Web crawling and scraping usually need to be combined in web data extraction projects. To scrape the data from those HTML files, you must first crawl—or discover—the URLs and download the HTML files. In other words, you extract data and use it for something, like storing it in a database or processing it further.

How to use scrapy in Python to make a web crawler

How To Make A Web Crawler In Python - What is the Difference Between Web Crawling and Web Scraping

Scrapy, a Python web crawler library, provides a robust framework for extracting, processing, and saving data.

Scrapy utilizes the use of Spiders which are independent crawlers that are given instructions. Moreover, by enabling developers to reuse their code, Scrapy makes it simpler to create and scale large crawling projects.

Scrapy is a powerful Python library that can be easily installed using the Python Package Installer (pip). Installing Scrappy is very simple and you can install it using the following command. The command works for Windows, Linux as well as macOS:

pip install scrapy

Spiders are classes in the scraping tool Scrapy that describe how a particular website (or a group of websites) will be scraped, including how to crawl the website (follow links, for example) and how to extract structured data from its pages (i.e., scraping items). In other words, spiders are where you specify the specific methods for parsing and crawling pages for a particular website (or, in some cases, a group of sites). Let us take a look at an example to get a better grasp of Scrapy:

import scrapy

class ScrapyTheSpider(scrapy.Spider):
    #name of the spider
    name = 'PythonGUI'

    #list of allowed domains
    allowed_domains = ['pythongui.org/']

    #starting url for scraping
    start_urls = ['http://pythongui.org/']

    #setting the location of the output csv file
    custom_settings = {
        'FEED_URI' : 'TempFolder/PythonGUI.csv'
    }

    def parse(self, response):
        #Remove XML namespaces
        response.selector.remove_namespaces()

        #Extract article information
        titles = response.xpath('//item/title/text()').extract()
        authors = response.xpath('//item/creator/text()').extract()
        dates = response.xpath('//item/pubDate/text()').extract()
        links = response.xpath('//item/link/text()').extract()

        for item in zip(titles,authors,dates,links):
            retrievedInfo = {
                'title' : item[0],
                'author' : item[1],
                'publish_date' : item[2],
                'link' : item[3]
            }

            yield retrievedInfo

To ensure better data analysis, you can use the Scrapy package to crawl data from some services. You can then use the data and show it in a Delphi Windows GUI program by following these easy instructions here.

Python for Delphi (P4D) is a free component that integrates the Python DLL into Delphi. The P4D set of libraries makes it simple to run Python scripts and develop new Python modules and types. Python extensions can be developed as DLLs, among other things.

Additionally, PyScripter, the best IDE currently on the market, can be used to write all of your code. PyScripter offers all the features of a contemporary Python IDE in a compact package. Moreover, It is natively compiled for Windows to use little memory while performing at its best. The IDE was entirely created in Delphi and is extensible using Python scripts.

Are you ready to create your own web crawler Python project? 

How To Make A Web Crawler In Python - Are You Ready to Create Your Own Web Crawlers - an image of a laptop downloading PyScripter

Crawling the web for information has proven to be a successful method for gathering data for analysis and decision-making. It is now a crucial tool in the data science toolbox. Data scientists need to be able to collect information from websites and store it in various formats for later analysis.

Web crawlers can extract anything visible object on a web page. Moreover, any web page that is publicly available on the internet can be crawled for information. However, every web page has a unique structure and set of web components, so you must program your web crawlers and spiders to extract web pages following those specifics.

Google and Bing frequently use web crawlers, also known as spiders, in their search engines. They serve the function of indexing website content so that those websites can be found in search engine results.

Projects that would have taken hours can now be finished in minutes with Scrapy or other libraries like Beautiful Soup. Using your preferred IDE, PyScipter, and the libraries BeautifulSoup and Python4Delphi in Delphi and C++Builder.

Click here and get Python4Delphi which allows you to build Python GUIs for Windows by using Delphi.

The post How To Make A Web Crawler In Python first appeared on Python GUI.

]]>
https://pythongui.org/how-to-make-a-web-crawler-in-python/feed/ 0 7743
What Is The Best Python Coding software – PyScripter vs IDLE https://pythongui.org/what-is-the-best-python-coding-software-pyscripter-vs-idle/ https://pythongui.org/what-is-the-best-python-coding-software-pyscripter-vs-idle/#respond Thu, 30 Jun 2022 10:00:00 +0000 https://pythongui.org/?p=7490 An integrated development environment (IDE) is a software application that provides extensive software development capabilities to computer programmers. An IDE typically includes a source code editor, build automation tools, and a debugger. Furthermore, they integrate...

The post What Is The Best Python Coding software – PyScripter vs IDLE first appeared on Python GUI.

]]>
An integrated development environment (IDE) is a software application that provides extensive software development capabilities to computer programmers. An IDE typically includes a source code editor, build automation tools, and a debugger. Furthermore, they integrate popular developer tools into a single graphical user interface (GUI). Furthermore, most modern Python coding software includes intelligent code completion. Python is a popular programming language among programmers. It is a powerful and versatile programming language that is used in a variety of domains. As a result of the increased use of Python, selecting a good IDE for development has become a critical task. However, there are several contenders, such as PyScripter, Visual Studio Code, IDLE, and PyCharm.

This article will compare PyScripter and IDLE, two famous IDEs among Python programmers today, to finally establish which of the two is the best Python programming software.

What makes PyScripter better than IDLE?

What Is The Best Python Coding software - PyScripter vs IDLE a laptop showing the PyScripter download information page

Developers prefer PyScripter and IDLE for writing Python scripts because of their lightweight nature and positive reviews. However, each has its advantages and disadvantages. Let’s take a look at them to determine which is the better Python programming IDE:

Are the Python IDEs lightweight? 

In computing, lightweight software is a computer program with a small memory footprint or RAM usage and low CPU usage, resulting in common system resource usage. As a result, a lightweight IDE is always preferred for Python programming.

PyScripter is a Python IDE that is feature-rich and lightweight. It offers power and versatility while being a lightweight IDE, making it a superior choice to IDLE.

Do both Python coding software IDEs Offer an autocomplete feature?

Syntactic code completions are primarily generic, providing quick and straightforward functional completions without knowing the context. Augmented Coding algorithms recognize the developer’s code context and suggest what the following line of code should be, reducing keystrokes.

PyScripter has a fantastic autocomplete feature as well as automatic code formatting. IDLE offers code auto-completion, but IDLE does not have code completion enabled by default. This gives the impression that the IDE does not support Code Autocomplete for aspiring developers. In contrast, PyScripter offers this feature by default and allows users to disable the feature easily. This time-saving and ease of use makes PyScripter a favorite amongst developers.

Which of the Python tools has theme support?

Theme support in an IDE is a feature that many developers overlook. The ability to select from various themes allows developers to personalize the appearance of their IDE. Moreover, this results in a better and more wholesome user experience.

PyScripter comes with many eye-catching editor themes (editor syntax coloring), both dark and light. You can also use the View, Select style menu command to choose between dark and light styles for the application’s user interface. Next, open the Editor Options, navigate to the Color Theme tab, select the theme you want, and click the “Apply Theme” button to change the editor theme. Furthermore, you may discover that, while you like the color scheme of a theme, the background is too dark or too light for your tastes. It is pretty simple to change the darkness of a theme.

IDLE, unfortunately, does not support any themes, so it cannot be personalized. 

Are PyScripter and IDLE community-based Python coding software?

No. PyScrupter is a community-driven project, IDLE is not. Individuals can take part in and feel ownership of their development when the community leads it. Communities value development projects that include community participation, build consensus, and instill a strong sense of community ownership.

As a Python developer, you will inevitably face challenges. Moreover, if you’re not sure what’s wrong, you should look up the error message online. A developer community supported by the IDE can be beneficial because it usually solves the problem more quickly and efficiently. Because Pyscripter, unlike IDLE Text, is a community-driven project, it is more beneficial for Python developers.

Does the Python coding software IDE have a built-in Terminal console?

The console’s user interface (the terminal), also known as command lines or consoles, is where you type and run text-based commands. Without using a graphical user interface, terminals allow us to complete and automate tasks on a computer. As a result, it is an essential component of an IDE. For example, PyScripter has a built-in terminal, whereas IDLE does not.

Which Python IDE has better Syntax highlighting support? 

Syntax highlighting is one of the most critical features in many Python coding software packages, and it can be beneficial when coding. The syntax of the Python programming language is well defined and will help you see the various elements of the code more easily. This is especially helpful when learning Python coding because remembering all of the different syntax rules can be challenging. Furthermore, the Python coding software can help you keep track of what you’re doing and avoid mistakes by highlighting specific code structures.

Brace highlighting, code folding, code completion, and syntax checking as you type are just a few of PyScripter’s many valuable features. A programmer should investigate this to master this software. In addition, python source code utilities further simplify programming. Finally, this IDE can handle files dropped from Explorer, which could save you time.

However, IDLE supports some but not all of PyScripter’s code highlighting features.

Do the IDEs offer real-time collaboration? 

Programs that allow programmers to collaborate on code remotely are collaborative coding tools. Real-time code collaboration has advanced rapidly in recent years, affecting how developers collaborate within teams working on the same code base. This incredible feature is found in PyScripter but not in IDLE.

Are there embedded Python debugging tools in the IDEs?

Embedded debugging is critical for software developers and programmers. Embedded Python debugger tools are code embedded in a program that makes it easier for computer programmers to browse their code and check for mistakes or “bugs.” If there are any errors, an embedded Python debugger will locate them and determine their form of error. This makes them easier to repair.

PyScripter includes built-in Python debugging tools, variables, watch windows, and access to the call stack. To aid debugging, the programmer can utilize conditional breakpoints or thread debugging. When a programmer cannot discover an error in his code, debugger suggestions can help. Not only can you execute your files without saving them, but you can also debug them without saving them, which is a great feature.

IDLE also has an inbuilt debugger, making for a pleasant programming experience.

Do both Python coding software IDEs support web development? 

A web development IDE is a powerful tool that includes features like autocomplete, grammar checking, debugger, suggestion, and seeing a live web page within the Python coding software to better understand the output. However, there is no predetermined list of features that should be included in an IDE’s arsenal.

IDLE is not a web development IDE, although PyScripter is.

Which Python programming software IDE should you choose?

What Is The Best Python Coding software - PyScripter vs IDLE - a man holidng a laptop showing the Python tools page
What Is The Best Python Coding software – PyScripter vs IDLE

Now that you have seen a thorough comparison of two well-reputed IDEs currently available and their features, you can always decide which IDE to pick based on your requirements. PyScripter appears to have everything that IDLE offers, but this excellent IDE has more to offer!

PyScripter is a handy tool because it is small, adaptable, and extensible with many capabilities. In addition, it is significantly faster and more responsive than clunky text editors, general-purpose IDEs, or other Python cross-platform IDEs because it is created from the ground up for Windows.

Click here and start using PyScripter, the best Python programming IDE, for the best possible development experience.

The post What Is The Best Python Coding software – PyScripter vs IDLE first appeared on Python GUI.

]]>
https://pythongui.org/what-is-the-best-python-coding-software-pyscripter-vs-idle/feed/ 0 7490
The 3 Best Python Testing Tools And Why You Need Them https://pythongui.org/the-3-best-python-testing-tools-and-why-you-need-them/ https://pythongui.org/the-3-best-python-testing-tools-and-why-you-need-them/#respond Wed, 29 Jun 2022 10:00:00 +0000 https://pythongui.org/?p=7351 Software testing is a time-consuming procedure with many steps. However, unit testing is an essential phase in the software development process since it assures that only the best product reaches the end-user. In addition, unit...

The post The 3 Best Python Testing Tools And Why You Need Them first appeared on Python GUI.

]]>
Software testing is a time-consuming procedure with many steps. However, unit testing is an essential phase in the software development process since it assures that only the best product reaches the end-user. In addition, unit testing is a technique for determining if programs and apps match the needs of their customers.

It is important to ensure no issues arise when the final product is made available to clients. Individual modules are run to check for problems during software unit testing. If you are new to scripting, then here is a step-by-step guide to Python scripting for absolute beginners. This article will focus on which tools are using for unit test in python development and the best Python testing tools for developers.

Why is unit testing important in Python development?

why-is-unit-testing-important-in-python-development-6772525

The primary goal of unit testing is to guarantee that each component functions properly and as intended. Only if the individual pieces are in good operating order can the complete system function properly. The software developers themselves undertake unit testing. Independent software testers sometimes carry out these tests.

Adjustments to the existing design and code are inevitable when adding new features to any software. This can be costly and dangerous. Furthermore, using the unit testing technique may save time, allowing the complete process to run more smoothly.

Thus, unit testing improves code quality dramatically. In addition, it assists developers in identifying the tiniest faults that may exist in units before integration testing.

In addition, unit testing aids in the early detection of a wide range of software faults. Before moving further, software engineers can address those issues first. The key benefit of handling errors early using unit testing is that no other software parts are affected later in the project. This results in more efficiency, less downtime, and lower expenses than would otherwise be incurred if the entire design process.

What is PyScripter?

what-is-pyscripter-1316064

PyScripter began as a lightweight IDE designed to supplement the excellent Python for Delphi (P4D) components by providing a robust scripting solution for Delphi applications (visit this link to download Pyscripter). Thanks to the cooperation of P4D developer Morgan Martinez and a few early users, it has now grown into a full-featured stand-alone Python IDE. It’s written in Delphi with P4D and the SynEdit component, but it may be extended with Python scripts. Moreover, it has a modern user interface and is presently only available for Microsoft Windows. In addition, PyScripter was designed using a compiled language. This makes its graphics faster than those of some other IDEs. Furthermore, it includes a wide range of capabilities that make it a productive Python programming environment.

Furthermore, with PyScripter, many Python IDEs are readily available. And there are a lot of nice ones, such as Spyder, SPE, and Eric3, not to mention IDLE, which comes with the standard Python distribution. So it’s understandable to wonder why to bother developing yet another Python IDE. The quick explanation is that it’s just for fun! The long answer is the need to produce a Python IDE that can compete with commercial Windows-based IDEs for other languages. PyScripter has many features that this article can’t cover, so we recommend that you visit this article here to learn more.

Why should developers use PyScripter for unit testing?

PyScripter, in the eyes of many developers, is one of the greatest Python IDEs available today. Its main features include a syntax highlighting editor, Python interpreter, debugger, project manager, and more. However, the most notable feature is that PyScripter has native support for integrated unit testing. Moreover, it has established itself as one of the best Python testing tools for software development among Python developers.

PyScripter ensures automatic test generation, allowing you to perform automated unit testing. This IDE also includes a fantastic unit testing GUI. Moreover, its unit tests window offers an advanced graphical user interface for running unit tests, a standard Python module. Check out the official documentation for more information.

Refresh and Run are two of the most significant toolbar commands on this window.

PyScripter’s unit tests from the currently active module are loaded by refreshing the unit test window. It’s worth noting that this requires you to import the module into the integrated interpreter. After loading a module, use the offered tree view to choose (check) the tests you want to execute. Double-clicking on the name of a test or a test class will send you to the test method or class declaration in the source code.

Run is simple to use because it executes the selected tests. The color next to the test in the tree view indicates its status after running. For example, green denotes success, purple denotes assertion failure, and red represents a Python exception (i.e., any other error). Right below the tree view is the aggregate statistics, and you can read information about the mistakes that occurred by clicking on the failed tests.

Which other Python tools offer unit testing? 

which-other-python-tools-offer-unit-testing-8925091

Apart from PyScripter, there are many other Python testing tools available in the market, but none can rival the capabilities of PyScipter. Let’s take a look at which tools are using for unit test in python development:

Robot Framework (RF)

Robot Framework (RF) is an open-source acceptance testing, acceptance test-driven development (ATDD), and robotic process automation framework (RPA). Its core is written in Python, but it’s also compatible with Jython (a Java implementation of Python) and IronPython (Python for .NET framework). Python version 2.7.14 or higher is required to run it.

RF uses KDT (Keyword-driven testing), allowing us to easily create test cases using human-readable keywords (no coding experience required). RF supports all operating systems (Windows, Linux, and macOS) and applications (web, mobile, and desktop apps). In addition, it provides HTML reporting data that is easy to understand (including screenshots). With a rich ecosystem and numerous APIs, it is a highly extensible framework that can be integrated with virtually any third-party tool.

However, RF does not have built-in support for Parallel testing. Moreover, It forces you to work according to a predetermined methodology, resulting in a very high learning curve. Additionally, it is challenging to customize reports.

RF is the solution for you if you want to implement a keyword-driven framework approach that allows manual testers and business analysts to create automation tests. It comes with various extensions and libraries and is simple to use. However, due to RF’s inability to support various adjustments, PyScripter becomes the best alternative.

TestProject 

TestProject is a completely free automation framework that includes cloud and local HTML reports. With the Python open-source SDK and TestProject, you can quickly develop test automation for mobile, web, or generic purposes. It requires Python 3.6 or later, as well as the Pytest and Unittest frameworks.

TestProject generates a Single Agent executable. This allows the integration of all third-party libraries required to run and develop test automation for mobile, web, and generic tests. Furthermore, it generates free Automatic reports in HTML/PDF format and provides access to execution history via a RESTful API. Moreover, TestProject consists of a built-in runner and reporting feature, as well as support for Mac, Linux, Windows, and Docker.

However, because the TestProject agent can only run one test at a time, you’ll need to use Docker Agents for parallel testing. Furthermore, many features enabled as part of the hybrid cloud are unavailable when working offline. In contrast to the seamless collaboration on the hybrid cloud, you will need to implement collaboration independently. This allows you to save tests on a shared network drive/git. Furthermore, with TestProject, it is also challenging to set up and configure across multiple browsers.

Conclusively, if you’re looking for a single framework to handle all your unit tests, PyScripter is the one for you. It’s also great for teams with a range of skill levels, from beginners to experienced automation experts.

Are you ready to write unit tests using PyScripter?

are-you-ready-to-write-unit-tests-on-using-pyscripter-8418560

I hope this article was able to help you understand what unit testing is. PyScripter’s features make it the best among other Python testing tools. As you learn more and your application grows, you should keep to PyScripter and leverage its advanced features more.

Now that you have a good overview of PyScripter click here now and start developing apps with unit testing.

The post The 3 Best Python Testing Tools And Why You Need Them first appeared on Python GUI.

]]>
https://pythongui.org/the-3-best-python-testing-tools-and-why-you-need-them/feed/ 0 7351
PyScripter vs. PyCharm – Best Python Coding Software? https://pythongui.org/pyscripter-vs-pycharm-best-python-coding-software/ https://pythongui.org/pyscripter-vs-pycharm-best-python-coding-software/#comments Tue, 28 Jun 2022 10:00:00 +0000 https://pythongui.org/?p=7467 Python is a powerful programming language that may be used to construct various applications, including internet apps, software and game creation, network programming, and graphical user interfaces (GUIs). Python’s popularity has increased due to its...

The post PyScripter vs. PyCharm – Best Python Coding Software? first appeared on Python GUI.

]]>
Python is a powerful programming language that may be used to construct various applications, including internet apps, software and game creation, network programming, and graphical user interfaces (GUIs). Python’s popularity has increased due to its simplicity, simple syntax, active community, and readily available free Python IDEs such as PyCharm, PyScripter, Visual Studio Code, and others. As a result, many individuals are studying Python these days since it is in demand, may lead to a well-paid profession, and broadens job opportunities.

PyScripter is a free, fully accessible Python coding software with many features provided under the MIT license. Kiriakos Vlahos created PyScripter, and the project’s SourceForge website has garnered over 1.2 million downloads since 2015. 

This article will compare PyScripter and PyCharm, highlighting their advantages and capabilities, and conclude which is the best coding IDE.

How can we compare PyScripter and PyCharm?

PyCharm Python coding software on Macbook

Do these two Python IDEs have syntax highlighting support?

Syntax highlighting refers to the use of colors and fonts in programming languages and other structured files to aid in differentiating language parts. Syntax highlighting is used by programmers to help them grasp code more quickly and to identify various types of syntax problems. It enables you to see what each component of the statement or command does; for example, you can see what portion is a function and what part is a variable like a string.

 Depending on what the reader is searching for, significant portions of comments or code can be readily ignored. Syntax highlighting also aids programmers in identifying problems. String literals, for example, are usually highlighted in a distinct color. As a result of the text’s contrasting hue, finding a missing delimiter is significantly easier. Another significant feature of many popular editors is brace matching. By highlighting the pair in a distinct color, it’s easy to determine if a bracket has been left out or to find the match of the bracket the pointer is on.

This code highlighting functionality that PyScripter provides is also accessible in PyCharm.

Which of these two Python IDEs has integrated Python debugging?

The Python debugger is a source code debugger for Python applications that may be used interactively. For example, it may set conditional thresholds and single-stepping. It also allows you to inspect stack frames, see source code, and run any Python code in any stack frame’s context. Software system developers can use debugging to correct flaws before releasing a program to the public. Python debugging tools are critical for Python programming, as they aid in the differentiation of excellent and terrible Python programming software.

The user has access to a built-in Python debugger in PyScripter. This contains debugger tips, which come in handy when a programmer cannot discover a mistake in his code. In addition, you can not only execute but also debug your files without saving them, which is an advantage. PyCharm, on the other hand, does have an integrated debugger but lacks debugger tips; as a result, tipping the scales in favor of PyScripter.

Do the Python IDEs support code autocompletion?

A programmer might sometimes take hours to remedy an error when programming or coding. Autocomplete tools are quite helpful since they allow people to complete code faster while decreasing mistakes. Using an IDE with code autocomplete to develop a project in Python may make things a lot simpler. 

Within the visible scope, basic code completion assists you in filling in the names of classes, methods, and keywords. PyScripter analyses the context and provides options that are available from the current caret location when you call code completion. PyScripter and PyCharm both offer an excellent autocomplete capability and automated code formatting.

Do the IDEs have an integrated Python interpreter?

Python is an interpretive language, which means it runs code line by line. As we all know, the computer cannot understand our language and can only grasp machine language, also known as binary language. As a result, the Python interpreter translates user-written Python code into a language that computer hardware or systems can comprehend. It happens every time you execute your Python script. One of the interpreter’s advantages is that you can initiate an interactive session with it and input Python code to see what it performs. This is a fantastic approach to testing out new programming concepts.

PyScripter has an integrated Python Interpreter, which lets users run Python code without saving them and offers code completion. PyCharm also provides the feature, but nowhere near as PyScripter which is also very simple.

Do they support external Python tools?

External Tools may be defined in PyScripter, and either operate alone or interact with the IDE editor. Selecting such tools with significant flexibility allows you to seamlessly integrate your favorite Python tools or command-line applications with PyScripter. The “Tools|Configure Tools..” menu item allows you to define or change external tools. The tool definitions are saved in the PyScritper.ini file. External tools in PyScripter include  PyLint, TabNanny, Profile, etc. To know more about PyScripter external tools check out the help.

PyCharm, on the other also allows you to integrate a variety of tools. These tools may help improve coding efficiency and coping with data science projects. Anaconda, IPython, and Kite are some of the most important integration tools for PyCharm. 

Which Is the best Python coding software IDE?

PyScripter or PyCharm the best Python coding software on Macbook

An integrated development environment (IDE) can tell the difference between excellent and terrible programming. As proven by the emergence of analysts and data scientists, Python is a strong programming language that can be used to build a variety of applications. Python’s popularity has risen as a result of this. Furthermore, a solid Python IDE makes it simple to manage your coding development. Choosing very powerful, current IDE software to assist deliver a better, more hand-holding experience is beneficial

PyScripter is the best IDE and contains a debugger and numerous sophisticated features such as code recommendations. Because it is developed in a compiled language, it is significantly quicker than other Python IDEs. It contains a lot of extra features that make it a great Python development environment. Naturally, the comparison of features above shows that PyScripter is a superior package overall, as it offers more features than PyCharm. Despite the fact that both of these IDEs contain all of the fundamental functions, PyScripter includes a few more. This also helps to explain why it’s a popular favorite with high ratings.

Now that you know which is the best Python coding IDE, click here and experience PyScripter, the best of the best!

The post PyScripter vs. PyCharm – Best Python Coding Software? first appeared on Python GUI.

]]>
https://pythongui.org/pyscripter-vs-pycharm-best-python-coding-software/feed/ 2 7467
PyScripter vs. Sublime Text – Best Python Development Tools? https://pythongui.org/pyscripter-vs-sublime-text-best-python-development-tools/ https://pythongui.org/pyscripter-vs-sublime-text-best-python-development-tools/#respond Mon, 27 Jun 2022 10:00:00 +0000 https://pythongui.org/?p=7473 Developers use various tools during the writing, creation, and testing software. Text editors, code libraries, bug tracking software, compilers, and test platforms are the most common development tools. A development environment that is integrated combines...

The post PyScripter vs. Sublime Text – Best Python Development Tools? first appeared on Python GUI.

]]>
Developers use various tools during the writing, creation, and testing software. Text editors, code libraries, bug tracking software, compilers, and test platforms are the most common development tools. A development environment that is integrated combines several of these development-related technologies into a single framework. A developer who doesn’t use an IDE, on the other hand, must select, deploy, integrate, and monitor these tools individually. Furthermore, developers do not have to spend hours learning how to use them individually when using an IDE. Furthermore, new developers may use an IDE to learn about a team’s standard tools and practices. PyScripter and Sublime Text are excellent choices for programming in Python, everyone’s favorite language.

This article will ultimately compare two of these IDEs as we discuss their pros and cons and decide on the best Python development tools

What features do PyScripter and Sublime Text offer?

Comparative Analysis of Sublime Text and PyScripter

Users prefer PyScripter and Sublime Text for writing a Python script due to their lightweight nature, but each has advantages and disadvantages. If you are an absolute beginner to Python, check out this step-by-step guide to Python Scripting to help you get started. Let us compare these two Python IDEs:

How are these IDEs useful Python debugging tools?

Debugging is crucial because it allows software engineers and developers to fix bugs before releasing a program to the public. It’s an add-on to testing, which entails determining how an error affects a program. As a result, Python debugging tools are essential for Python programming. It is something that distinguishes good Python programming software from bad.

PyScripter offers an integrated Python debugger, variables, and watch windows, and the call stack is all accessible to the user. The programmer can use conditional breakpoints or thread debugging to help with debugging. Debugger hints are also beneficial when the programmer cannot locate the error in his code. You may not only run your files without saving them, but you can also debug them without saving, which is an excellent addition.

On the other hand, Sublime Text does not have any kind of debugger, so developers may have to look for some external tool to do the job.

Do these IDEs work as a Python code checker and Python syntax highlighter?

Syntax highlighting is available in many Python coding software packages, which can be extremely useful when coding. The Python programming language has a defined syntax, and the syntax highlighting feature in Python coding software will make it easier to see the various elements of the code. Using a tool which acts as a Python code checker is especially useful when learning coding because keeping track of all the different syntax rules can be difficult. Moreover, Python coding software (an IDE) can help you keep track of what you’re doing and avoid mistakes by highlighting specific code structures.

Split view/side-by-side file editing is one of PyScripter’s most basic but crucial features. It also provides full support for encoded Python source files to the user. Furthermore, PyScripter has some excellent features like brace highlighting, code folding, code completion, and syntax checking as you type. To master this software, a programmer should investigate this. In addition, Python source code utilities ((un)tabify, (un)comment, (un)indent, and so on) make programming even easier. Finally, this IDE can handle files dropped from Explorer, potentially saving you time.

However, Sublime Text supports some but not all of PyScripter’s code highlighting features.

Do these IDEs serve as Python testing tools?

Writing unit tests allows you to keep your code simple by only writing the code necessary to pass the test. In addition, having simple, easy-to-read, bug-resistant code in your first round of programming instills confidence in you as a developer, as well as in your employers.

PyScripter ensures that tests are generated automatically, allowing for automated unit testing. This IDE also has a fantastic unit testing interface. Furthermore, its unit tests window provides a sophisticated graphical user interface for running unit tests, a standard Python module. For more information, visit the official documentation.

Unfortunately, Sublime Text does not have any kind of unit testing GUI. However, unit testing on its own can be achieved by installing some relevant plugins in Sublime Text.

Do PyScripter and Sublime Text offer a Python code autocomplete feature?

Using an IDE with code autocomplete can make things a lot easier when making a Python project. You can find Python functions and classes quickly and easily with autocomplete without looking through documentation or examples. This saves you time and frustration while also writing code faster. Furthermore, an IDE can assist you in formatting your code to make it more readable and understandable.

PyScripter has a fantastic autocomplete feature and code formatting that is done automatically. Code autocompletion is also available in Sublime Text.

Can developers use these Python IDEs as a compiler and interpreter?

Python programs use both a compiler and an interpreter. Python interpreter is widely used in the source coding and computer programming industries. In addition, the Python interpreter also executes an interactive command. PyScripter includes a built-in Python interpreter that can be very useful. This interpreter allows users to run Python scripts without saving them while also providing code completion and call tips. In addition, PyScripter enables the user to view the entire command history (all commands that have been executed in the interactive Python session). Sublime also provides some assistance but not all like PyScripter.

Do the two Python IDEs provide access to a developer community?

You will inevitably encounter difficulties. If you’re not sure what’s wrong, the best option is to look up the error message online. A developer community supported by the IDE can be advantageous because it usually solves the problem faster and more efficiently. Since, Pyscripter, unlike Sublime Text, is a community-based project making it more beneficial for Python developers.

What are the other distinguishing qualities? 

The terminal is the console’s user interface, where you can type and run text-based commands. Thus, it is a critical component of an IDE. Sublime Text does not have a built-in terminal, whereas PyScripter does. PyScripter has some additional features that Sublime Text lacks. For example, Real-time collaboration, a beautiful and fluid interface, and theme support make it a superior choice.

Which is the best Python programming IDE?

Sublime Text the best Python programming software

A well-integrated development environment (IDE) can distinguish between a good and bad programming experience. Python is significant because it is becoming more widely used in various computing and scientific applications, as evidenced by the rise of analytics and business intelligence. Furthermore, a good Python IDE makes managing your coding development a breeze.

PyScripter, on the other hand, is the best IDE and includes several advanced features such as code suggestions and a debugger. It is also faster than some other Python IDEs because it is written in a compiled language. In addition, it has numerous other features making it an excellent Python programming environment. Naturally, the above discussion of features demonstrates that PyScripter is a better package in general, as it has more features. Even though both of these IDEs have all of the essential elements, PyScripter has some premium features. This also explains why it is a fan favorite and has high ratings.

Click here to join us and experience the superiority of PyScripter, the best Python IDE out there!

The post PyScripter vs. Sublime Text – Best Python Development Tools? first appeared on Python GUI.

]]>
https://pythongui.org/pyscripter-vs-sublime-text-best-python-development-tools/feed/ 0 7473
What Is The Best IDE For Python? https://pythongui.org/what-is-the-best-ide-for-python/ https://pythongui.org/what-is-the-best-ide-for-python/#respond Fri, 24 Jun 2022 10:00:00 +0000 https://pythongui.org/?p=7605 If you are an aspiring Python programmer, you are probably wondering what is the best IDE for Python projects. It’s no secret that Python is one of the most popular programming languages in the world....

The post What Is The Best IDE For Python? first appeared on Python GUI.

]]>
If you are an aspiring Python programmer, you are probably wondering what is the best IDE for Python projects. It’s no secret that Python is one of the most popular programming languages in the world. And with its growing popularity, the demand for quality Python coding software is also on the rise. So, how do you choose the best IDE for Python in 2022? What are the important factors you need to consider?

Click here to download PyScripter, a lightweight, free, feature-rich IDE for Python coding.

What is an integrated development environment (IDE)?

An Integrated Development Environment (IDE) is a desktop application that provides tools and functionality for software development. IDEs typically include a source code editor, a debugger, and a compiler or interpreter. Python developers need an IDE to provide features like code completion, syntax highlighting, and error detection. IDEs also offer built-in support for popular Python libraries and frameworks, making it easier to develop complex applications using pre-existing functions and modules. Let’s dive deeper into the features of the best Python IDE.

Why do you need an IDE for Python development?

When it comes to Python development, you could survive without an IDE, but you will be missing out a lot. IDEs offer a variety of features that make Python development easier, including code completion, syntax highlighting, and error detection. They also provide built-in support for popular Python libraries and frameworks, making it easier to develop complex applications.

No matter what your needs are, there’s an IDE out there that’s perfect for you. So get started on your Python development journey today!

What are IDEs available for Python coding?

There are three main types of IDEs available for Python development: graphical interfaces, text-based and web-based. We have discussed some of the features of available IDEs here.

Some of the popular Python IDEs and code editors include

  • GUIs
    • PyScripter
    • Visual Studio Code
    • PyCharm
    • Eclipse PyDev
    • Atom
    • Sublime Text
    • Spyder
    • Thonny
  • Text editors
    • vim
    • Emacs
    • Notepad++
  • Web-based editors
    • AWS Cloud9
    • Jupyter notebooks
    • online Python interpreters

What do we mean by “text-based software”?

Text-based coding software provides lightweight development experience, particularly for experienced developers who are comfortable working with text editors such as Emacs, vim and Notepad++, for example. However, the Python interpreter has to be called separately to execute the code.

What about IDEs with a graphical interface?

Graphical IDEs like PyScripter and Visual Studio Code offer a visual interface for code editing and debugging. They usually support advanced features suitable for beginner and professional programmers alike. PyCharm stands out from the rest in that it also has a paid version suitable for professional developers. The others on the list are freely available. We recently reviewed Atom in detail. It is a good tool but too memory heavy. PyDev is a plug-in for Eclipse’s IDE. As such, the user has to run software with unneeded features.

Sublime Text is an advanced text editor that comes as a graphical desktop application. It runs Python code but other than that, it is fairly simple in features. A notable downside is that it has a free evaluation version, but if you want to use it long-term, you have to buy a licence. Spyder is a fairly old and robust IDE mostly aimed at data science and scientific work. Thonny is another simplified tool with limited features useful for the seasoned programmer.

Web-based environments

Web-based IDEs like Amazon’s Cloud9 provide a browser-based development environment, making it easy to develop Python applications from anywhere and switch from one computer to another without downloading, sending or copy-pasting anything. There are multiple online Python interpreters, essentially a web page with just a block of code and a block of output. The Python code is executed on the server. However, saving the code is usually not possible, meaning that your work is prone to data loss, and also you cannot use more than one file with source code for a big project.

Jupyter notebooks

Jupyter notebooks are more or less a different class of a programming environment. They run in a browser, either locally or on a remote server. The notebook contains Python code and text written in Markup which even supports LaTeX, which scientists and engineers use for writing equations and formulas. The code can be written and executed in separate cells, which preserve the content of the memory, so all variables are seen throughout the notebook. One major downside is that jupyter runs on UNIX systems, and also, they are rather clumsy and demand lots of resources from the computer.

What features are an absolute must?

When choosing an IDE for Python coding, it’s important to consider essential features for your needs. Some IDEs offer more features than others. If you’re looking for an IDE with many bells and whistles, PyScripter, PyCharm or Visual Studio Code might be best. Visual Studio is a universal IDE, so there are lots of options and features only needed for other programming languages. This means, though, that it is bloated with stuff you do not need which still takes up memory and might cause lagging on old computers.

If you’re looking for a lightweight text editor with just the essentials, Emacs or Vim is probably what fits you, though you will undoubtedly be missing out. The absolute beginner probably does not need all the possible features that an IDE can have. Features like collaborative work are probably something that advanced coders and professionals benefit from the most. Version control is a helpful feature that everybody should eventually pick up, though there are many other points to master first. Here we have discussed the most innovative things happening with Python programming software.

Some features that are an absolute must in a Python IDE include:

  • Code completion: Code completion is a feature that helps you write code faster by automatically completing code for you.
  • Syntax highlighting: Syntax highlighting is a feature that makes it easier to read and write code by colour-coding different parts of the code.
  • Error detection: Essentially, spellchecking for code, error detection is a feature that helps you find and fix errors in your code.
  • Support for popular libraries and frameworks: Many IDEs offer built-in support for popular Python libraries and frameworks, making it easier to develop complex applications.
  • Supported platforms: Some IDEs are available only for Windows, and others only for UNIX systems. Many are available for multiple operating systems.
  • Stability and performance: The most important feature of an IDE is to (ideally) never crash, or you will lose your precious work. Also, the purpose of an IDE is to assist the programmer, not to annoy them with slow responsiveness and lagging.

No matter what your needs are, there’s an IDE out there that’s perfect for you. So get started on your Python development journey today!

How to choose the best Python IDE for your needs?

When choosing an IDE for Python development, there are a few critical factors to consider. First, think about the type of development you’ll be doing. If you’re new to Python, a graphical IDE like PyScripter might be best. If you’re an experienced developer who is comfortable working with text editors, a text-based IDE like Emacs or Vim might be suitable, though they are missing lots of advanced features.

Another important factor to consider is the operating system you’re using. Some IDEs are only available for Windows, while others are available for both Windows and macOS. Make sure to choose an IDE that is compatible with your operating system.

Finally, consider the features you need. Some IDEs offer more features than others. If you’re looking for an IDE with a lot of bells and whistles, PyCharm or Visual Studio Code might be best. If you’re looking for a lightweight IDE with just the essentials, Emacs or Vim might be best.

What is the best Python coding software?

A good Python IDE for beginners, in fact the best Python IDE for anyone, allows the programmer to quickly and easily access all the needed tools, including a package manager and a debugger. Profiling tools and version control are also essential tools that Python programmers need to start using eventually.

Final thoughts on what makes the best Python IDE

Choosing the best IDE for Python can be a daunting task. There are many different options available, each with its own set of features and benefits. Ultimately, the goal is to find a tool that is easy to use and has all the features that you personally find necessary. The most important factors to consider are availability, simple package management, robustness and smooth performance.

Do not spend too long thinking. Download PyScripter now and start coding!

The post What Is The Best IDE For Python? first appeared on Python GUI.

]]>
https://pythongui.org/what-is-the-best-ide-for-python/feed/ 0 7605