Python For Delphi 示例
samson <[email protected]> hide details 3:22 pm (50 minutes ago)
reply-to [email protected]
to "python.cn" <[email protected]>
date Aug 4, 2007 3:22 PM
subject [CPyUG:29962] [原創]Python For Delphi 示例 (最好的Python GUI實現方法)
mailed-by googlegroups.com
最近用Python For Delphi有了一段時間,感覺這麼好的東西不與大家分享簡直是暴斂天物了,而且前一段看大家討論GUI的問題相當多,爲 了讓大家少走點彎路,所以萌發了寫此文的念頭。
因時間有限,在此只做一個簡要的實例,在該實例中,可以通過delphi操作Python中的list對象。其實P4D功能十分強大,遠不止這些,還可 以用Delphi寫出供Python調用的模塊,這樣的模塊性能可是相當的高哦。 希望能夠藉此文拋磚引玉,勾起大家使用P4D的願望。
1.1. 步驟
0。安裝delphi7,安裝python25
1。安裝P4D控件
2。創建一個窗體,放置PythonEngine,PythonGUIInputOutput,Memo三個控件
3。PythonEngine的IO屬性指到PythonGUIInputOutput,PythonGUIInputOutput的Output屬性指到Memo
4。在主窗體的FormActivate事件中,添加如下代碼(注意還需要增加Uses):
uses
VarPyth;
procedure TForm1.FormActivate(Sender: TObject);
var
PyModule: variant;
i: integer;
begin
PyModule:=Import('hello');
memo1.Lines.Add(Format('模塊初始化時接口對象長度:%s',
[PyModule.IntfListDemo.Length]));
PyModule.main();
memo1.Lines.Add(Format('調用Python後接口對象長度:%s',
[PyModule.IntfListDemo.Length]));
memo1.Lines.Add('接口對象內容');
for i:=0 to PyModule.IntfListDemo.Length-1 do
begin
memo1.Lines.Add(PyModule.IntfListDemo.GetItem(i));
end;
for i:=PyModule.IntfListDemo.Length-1 downto 0 do
begin
PyModule.IntfListDemo.RemoveItem(i);
memo1.Lines.Add(Format('操縱Python對象後,接口對象長度:%s',
[PyModule.IntfListDemo.Length]));
end;
PyModule.IntfListDemo.AppendStr('重新');
PyModule.IntfListDemo.AppendStr('初始化');
PyModule.IntfListDemo.AppendStr('Python');
PyModule.IntfListDemo.AppendStr('變量');
memo1.Lines.Add('接口對象內容');
for i:=0 to PyModule.IntfListDemo.Length-1 do
begin
memo1.Lines.Add(PyModule.IntfListDemo.GetItem(i));
end;
end;
5。創建hello.py程序,與delphi程序在同一個目錄下。代碼如下:
切換行號顯示
1 # -*- coding: utf-8 -*-
2 class MyP4DStrList(list):
3 def CopyFrom(self,SrcList):
4 self.Clear()
5 for i in SrcList:
6 self.append(i)
7 def Clear(self):
8 for x in range(len(self)): del self[0]
9 def GetItem(self,index):
10 return self[index]
11 def RemoveItem(self,index):
12 del self[index]
13 def AppendStr(self,StrToAppend):
14 self.append(StrToAppend)
15 def RemoveStr(self,StrToRemove):
16 self.remove(StrToRemove)
17
18 IntfListDemo=MyP4DStrList()
19
20
21 def main():
22 IntfListDemo.append('hello')
23 IntfListDemo.append('world')
24 IntfListDemo.append('with')
25 IntfListDemo.append('P4D')
26
27
28
29 if __name__ == '__main__':
30 main()
---------------------