Embedding Python in a Delphi Application

Figure 22.8 shows the first example from the PyDelphi tutorial.

Python interpreter inside a Delphi application
Figure 22.8. Python interpreter inside a Delphi application

To achieve this, you create a new project with the visual components shown in Figure 22.8. In addition, place two special Python-Delphi components on the form. These are invisible at runtime, but allow you to set up many properties from the Object Inspector rather than in code. The essential one is a PythonEngine, (highlighted in Figure 22.9).

The same form at design time
Figure 22.9. The same form at design time

The PythonEngine component has events that can be trapped for initialization and finalization, and—most usefully—an InitScript property of type TStrings. This is a list of strings that can be set at design time in an editor and can hold any Python code you want.

In addition, you add a PythonGUIInputOutput component. After setting a couple of properties, this redirects the output of the Python engine to the upper Rich Edit window in the form. The user can now type Python code into the lower window and execute it with a click on a button.

In addition to the usual header, you need one line of code behind the button:

procedure TForm1.Button1Click(Sender: TObject);
  PythonEngine1.ExecStrings( Memo1.Lines );

PyDelphi exposes almost the entire ...

Get Python Programming On Win32 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.