DelphiFeeds.com

  • Dashboard
  • Popular Stories
  • Trending Stories
  • Feeds
  • Login
Trending now

Easily Integrate Exception Handling Into Your Python GUI Apps Through Delphi

Delphi debugging tip: keep an eye on a object field of an object that will ...

Distinguer les processeurs Intel des processeurs Apple Silicon depuis nos programmes

Powerful Award-Winning Windows UI Toolkit For Delphi And C++Builder

Using Apilayer REST APIs from Delphi

Quickly Access Windows System Info In Your Delphi Application With Excellent Component Suite

Build Visual Stunning Apps Faster With Less Code Using RAD Studio Architect Edition

Introduction To Modern C++ With Tutorials

TMS WEB Core for Visual Studio Code v1.2 released!

Quickly Learn About High-Performance Python Generators With A Delphi Windows GUI App

Powerful Multi-sensor Imaging Tool For Processing And Analyzing Hyperspectral Images Built In Delphi

How to write Delphi apps to run and look great on Windows, macOS and Linux

Using Apilayer REST APIs from Delphi

Quickly Define Powerful Client-Side Aggregating Formulas With FireDAC Using TFDQuery In Delphi

VCL Grid goodies

Easily Pass Values Between Delphi And Python In Your Windows Delphi/C++ Builder Apps

1
Anbarasan Anbarasan 2 months ago in C++, cbuilder, Code, Delphi, object pascal, programming, Python, python gui 0

Want to build a Delphi/C++ builder Application that should exchange values between Delphi and Python Objects. Not sure how to do it? Python4Delphi has two powerful components to achieve this faster, you can use either one component for your application. In this post, we can see both ways.

  1. Python4Delphi Demo16 Example1 App shows how to assign a variable value between Delphi and Python using the TPythonDelphiVar component events. This can be achieved by events that set and gets data as a python object. Internally this component converts a value from Delphi to python and vice versa. You can find the Demo16 Example1  source on GitHub.
  2. Python4Delphi Demo16 Example2 App shows how to assign a variable value between Delphi and Python using TPythonModule, create a module, add few routines to that module, Import the module in a python script, and access the added routine. You can find the Demo16 Example2 source on GitHub.

Prerequisites: Download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out this video Getting started with Python4Delphi.

Components used in Python4Delphi Demo16 App:

  • TPythonEngine: A collection of relatively low-level routines for communicating with Python, creating Python types in Delphi, etc. It’s a singleton class.
  • TPythonGUIInputOutput: Inherited from TPythonInputOutput (which works as a console for python outputs) Using this component Output property you can associate the Memo component to show the Output.
  • TMemo: A multiline text editing control, providing text scrolling. The text in the memo control can be edited as a whole or line by line.

Example1: TPythonDelphiVar Inherited from TEngineClient, used to convert the python variable to the Delphi variable and vice versa. It has methods to set and get value as variant or PyObject. It contains property like Module(TPythonModule internally created by default) where the python variable(TPyVar) is created and later converted to and from the Delphi variant or PyObject.

You can find the Python4Delphi Demo16a sample project from the extracted repository ..Python4DelphiDemosDemo16Example1Demo16a.dproj. Open this project in RAD Studio 10.4.1 and run the application.

Implementation Details:

  • PythonEngine1 provides the connection to Python or rather the Python API. This project uses Python3.9 which can be seen in TPythonEngine DllName property. It Is assigned with InitScript which import sys module and prints the Python.Dll version, copyright information to Memo2. import sys print(“Python Dll: “, sys.version) print(sys.copyright) print()
  • PythonGUIInputOutput1 provides a conduit for routing input and output between the Graphical User Interface (GUI) and the currently
    executing Python script.
  • PythonDelphiVar1 component is intended for demonstrating how to assign value between Delphi components( like edit box, check box and group boxes) ->Python Delphi variable(Properties.Value) and back from (Properties.Value) -> Delphi components( like edit box, check box and group boxes) using event PythonDelphiVar1ExtGetData and PythonDelphiVar1ExtSetData respectively. The data is passed as Python Dictionary Type Object here. The CreateProperties and UpdateProperties routine creates a python dictionary object and Updates the python dictionary object when the value is changed in the UI.
procedure TForm1.PythonDelphiVar1ExtGetData(Sender: TObject;
  var Data: PPyObject);
begin
  with GetPythonEngine do
    begin
      // Return our object
      Data := FProperties;
      // Don't forget to increment it, otherwise we would loose property !
      Py_XIncRef(Data);
    end;
end;

procedure TForm1.PythonDelphiVar1ExtSetData(Sender: TObject;
  Data: PPyObject);
begin
  with GetPythonEngine do
    begin
      // Check if the transmitted object is a dictionary
      if not PyDict_Check(Data) then
        Exit;
      // Acquire property to the transmitted object
      Py_XIncRef(Data);
      // Release property of our previous object
      Py_XDecRef(FProperties);
      // Assisgn transmitted object
      FProperties := Data;
    end;
end;
  • Memo1, used for providing the Python Script to execute, and Memo2 for showing the output. 
  • On Clicking Execute Button the python script is executed.
demo16a-1694429
Python4Delphi Demo16a

Example2: TPythonModule inherited from TMethodsContainer class allows creating modules by providing a name. You can use routines AddDelphiMethod, AddDelphiMethodWithKW to add a method of type PyCFunction. You can create events using the Events property.

You can find the Python4Delphi Demo16b sample project from the extracted repository ..Python4DelphiDemosDemo16Example2Demo16b.dproj. Open this project in RAD Studio 10.4.1 and run the application.

Implementation Details:

  • PythonEngine1 provides the connection to Python or rather the Python API. This project uses Python3.9 which can be seen in TPythonEngine DllName property.
  • PythonGUIInputOutput1 provides a conduit for routing input and output between the Graphical User Interface (GUI) and the currently
    executing Python script.
  • PythonModule1 with Module name props is created. During PythonModule1Initialization a three DelphiMethods(GetProperty,SetProperty,GetPropertyList) are added to the Module. Logically a python module is created and its methods were created using this PythonModule. Later this can be imported into your python script wherever necessary.
function TForm1.GetProperty(pSelf, Args : PPyObject) : PPyObject; cdecl;
var
  key : PAnsiChar;
begin
  with GetPythonEngine do
    if PyArg_ParseTuple( args, 's:GetProperty',@key ) <> 0 then
      begin
        if key = 'Title' then
          Result := VariantAsPyObject(cbTitle.Text)
        else if key = 'Name' then
          Result := VariantAsPyObject(edName.Text)
        else if key = 'Informatician' then
          Result := VariantAsPyObject(cbInformatician.Checked)
        else if key = 'PythonUser' then
          Result := VariantAsPyObject(cbPythonUser.Checked)
        else if key = 'Age' then
          Result := VariantAsPyObject(edAge.Text)
        else if key = 'Sex' then
          Result := VariantAsPyObject(rgSex.ItemIndex)
        else
          begin
            PyErr_SetString (PyExc_AttributeError^, PAnsiChar(Format('Unknown property "%s"', [key])));
            Result := nil;
          end;
      end
    else
      Result := nil;
end;

function TForm1.SetProperty(pSelf, Args : PPyObject) : PPyObject; cdecl;
var
  key : PAnsiChar;
  value : PPyObject;
begin
  with GetPythonEngine do
    if PyArg_ParseTuple( args, 'sO:SetProperty',@key, @value ) <> 0 then
      begin
        if key = 'Title' then
          begin
            cbTitle.Text := PyObjectAsVariant( value );
            Result := ReturnNone;
          end
        else if key = 'Name' then
          begin
            edName.Text := PyObjectAsVariant( value );
            Result := ReturnNone;
          end
        else if key = 'Informatician' then
          begin
            cbInformatician.Checked := PyObjectAsVariant( value );
            Result := ReturnNone;
          end
        else if key = 'PythonUser' then
          begin
            cbPythonUser.Checked := PyObjectAsVariant( value );
            Result := ReturnNone;
          end
        else if key = 'Age' then
          begin
            edAge.Text := PyObjectAsVariant( value );
            Result := ReturnNone;
          end
        else if key = 'Sex' then
          begin
            rgSex.ItemIndex := PyObjectAsVariant( value );
            Result := ReturnNone;
          end
        else
          begin
            PyErr_SetString (PyExc_AttributeError^, PAnsiChar(Format('Unknown property "%s"', [key])));
            Result := nil;
          end;
      end
    else
      Result := nil;
end;
  • Memo1, used for providing the Python Script to execute, and Memo2 for showing the output. 
  • On Clicking Execute Button the python script is executed.
demo16b-8573027
Python4Delphi Demo16b

Head over and check out the Python4Delphi project to easily build Python GUIs for Windows.

Trending Stories

  • Easily Integrate Exception Handling Into Your Python GUI Apps Through...

  • Delphi debugging tip: keep an eye on a object field...

  • Distinguer les processeurs Intel des processeurs Apple Silicon depuis nos...

  • Powerful Award-Winning Windows UI Toolkit For Delphi And C++Builder

  • Using Apilayer REST APIs from Delphi

Embarcadero GetIt

  • Brook Framework

    Microframework which helps to develop web Pascal applications.

  • Trial - TMS Scripter

    Add the ultimate flexibility and power into your apps with native Pascal or Basic scripting and […]

  • Trial - TMS VCL Chart

    DB-aware and non DB-aware feature-rich charting components for business, statistical, financial […]

  • Trial - TMS VCL Cloud Pack

    TMS VCL Cloud Pack is a Delphi and C++Builder component library to seamlessly use all major cloud […]

  • Trial - TMS VCL UI Pack

    Create modern-looking & feature-rich Windows applications faster with well over 600 components […]

  • Learn Delphi Programming
  • Learn C++
  • Embarcadero Blogs
  • BeginEnd.net
  • Python GUI
  • Firebird News
  • Torry’s Delphi Pages
Copyright DelphiFeeds.com 2021. All Rights Reserved
Embarcadero
Login Register

Login

Lost Password

Register

Lost Password