当前位置:   article > 正文

pythonnet 的用法和配置 包括在python使用.net 和在C#.net使用python.

pythonnet

前面看过我文章的都知道本人喜欢用pythonnet,  温故而知新,先说python嵌入.net.

首先:  需要安装  安装.偷个懒.   贴上上次的下载脚本.   后面需要什么直接往后面添..

  1. import os
  2. def cmd(S="pause"):
  3. os.system(S)
  4. def P_install(S="mvtec-halcon==20111"):
  5. cmd(rf"pip install {S} -i https://pypi.doubanio.com/simple")
  6. IN_list=[
  7. "mvtec-halcon==20111","pythonnet",
  8. "pywin32","pyautogui","keyboard","Pyinstaller",
  9. "pillow","numpy","opencv-python"
  10. ]
  11. for i in IN_list:
  12. P_install(f"{i}")
  13. while True:
  14. cmd(rf"pip list"); CMD=input("请输入:");
  15. cmd(rf"pip install {CMD} -i https://pypi.doubanio.com/simple");

如果计算机只有一个python环境 并且3.5以上3.10以下理论上都可以用. 顺便提一下,3.7以下版本不支持f字符串,所以老版本需要占位符+.format(). #大概就有这么回事..

接下来:导入clr ,下来C#那一套命名空间就可以当作python自己的包导入进来了. 

  1. #--------------------------------------------------------------------------
  2. import clr
  3. import System
  4. from System import String, Char, Int32,UInt16, Int64, Environment, IntPtr
  5. print(f"{clr.AddReference('System')}")
  6. print(f"{clr.AddReference('System.Drawing')}")
  7. #---------------------------------------------------------------------------

导入以后,就可以开心的写程序了. 我先来,在python里用>NET,写一个图片格式转换.

  1. from tkinter import ttk
  2. from tkinter import messagebox
  3. from tkinter import *
  4. import tkinter as tk
  5. import tkinter.messagebox
  6. import os,sys,time
  7. import tkinter.filedialog
  8. from ctypes import *
  9. from tkinter import Tk,Frame
  10. def cmd(s="pause"):
  11. os.system(s)
  12. #--------------------------------------------------------------------------
  13. import clr
  14. import System
  15. from System import String, Char, Int32,UInt16, Int64, Environment, IntPtr
  16. print(f"{clr.AddReference('System')}")
  17. print(f"{clr.AddReference('System.Drawing')}")
  18. #---------------------------------------------------------------------------
  19. 文件名="11"
  20. R=f"{文件名}.bmp"
  21. W=f"{文件名}.jpg"
  22. System.Drawing.Bitmap(f"{R}").Save(f"{W}",System.Drawing.Imaging.ImageFormat.Jpeg);
  23. print("done!")
  24. time.sleep(2)
  25. #cmd()

可以看到主要就是这一句;

System.Drawing.Bitmap(f"{R}").Save(f"{W}",System.Drawing.Imaging.ImageFormat.Jpeg);

脚本同级目录放一张 "11.bmp"的图片. 运行之后 会生成 "11.jpg"的图,

尺寸从1282变成了98,尺寸缩小了十几倍.而图像精度几乎没有损失.

接下来:贴一个官方例子:

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import clr
  4. import System
  5. clr.AddReference("System.Windows.Forms")
  6. import System.Windows.Forms as WinForms
  7. from System.IO import File
  8. from System.Text import Encoding
  9. from System.Drawing import Color, Point, Size
  10. from System.Threading import ApartmentState, Thread, ThreadStart
  11. class Wordpad(WinForms.Form):
  12. """A simple example winforms application similar to wordpad."""
  13. def __init__(self):
  14. super().__init__()
  15. self.filename = ''
  16. self.word_wrap = True
  17. self.doctype = 1
  18. self.InitializeComponent()
  19. self.NewDocument()
  20. def InitializeComponent(self):
  21. """Initialize form components."""
  22. self.components = System.ComponentModel.Container()
  23. self.openFileDialog = WinForms.OpenFileDialog()
  24. self.saveFileDialog = WinForms.SaveFileDialog()
  25. self.mainMenu = WinForms.MainMenu()
  26. self.fileMenu = WinForms.MenuItem()
  27. self.menuFileNew = WinForms.MenuItem()
  28. self.menuFileOpen = WinForms.MenuItem()
  29. self.menuFileSave = WinForms.MenuItem()
  30. self.menuFileSaveAs = WinForms.MenuItem()
  31. self.menuFileSep_1 = WinForms.MenuItem()
  32. self.menuFileExit = WinForms.MenuItem()
  33. self.editMenu = WinForms.MenuItem()
  34. self.menuEditUndo = WinForms.MenuItem()
  35. self.menuEditRedo = WinForms.MenuItem()
  36. self.menuEditSep_1 = WinForms.MenuItem()
  37. self.menuEditCut = WinForms.MenuItem()
  38. self.menuEditCopy = WinForms.MenuItem()
  39. self.menuEditPaste = WinForms.MenuItem()
  40. self.menuEditSep_2 = WinForms.MenuItem()
  41. self.menuEditSelectAll = WinForms.MenuItem()
  42. self.formatMenu = WinForms.MenuItem()
  43. self.menuFormatFont = WinForms.MenuItem()
  44. self.menuFormatWordWrap = WinForms.MenuItem()
  45. self.aboutMenu = WinForms.MenuItem()
  46. self.menuHelpAbout = WinForms.MenuItem()
  47. self.richTextBox = WinForms.RichTextBox()
  48. self.statusBarPanel1 = WinForms.StatusBarPanel()
  49. self.statusBar = WinForms.StatusBar()
  50. self.fontDialog = WinForms.FontDialog()
  51. self.statusBarPanel1.BeginInit()
  52. # ===================================================================
  53. # File Menu
  54. # ===================================================================
  55. self.menuFileNew.Text = "&New"
  56. self.menuFileNew.Shortcut = WinForms.Shortcut.CtrlN
  57. self.menuFileNew.ShowShortcut = False
  58. self.menuFileNew.Index = 0
  59. self.menuFileNew.Click += self.OnClickFileNew
  60. self.menuFileOpen.Text = "&Open"
  61. self.menuFileOpen.Shortcut = WinForms.Shortcut.CtrlO
  62. self.menuFileOpen.ShowShortcut = False
  63. self.menuFileOpen.Index = 1
  64. self.menuFileOpen.Click += self.OnClickFileOpen
  65. self.menuFileSave.Text = "&Save"
  66. self.menuFileSave.Shortcut = WinForms.Shortcut.CtrlS
  67. self.menuFileSave.ShowShortcut = False
  68. self.menuFileSave.Index = 2
  69. self.menuFileSave.Click += self.OnClickFileSave
  70. self.menuFileSaveAs.Text = "Save &As"
  71. self.menuFileSaveAs.Index = 3
  72. self.menuFileSaveAs.Click += self.OnClickFileSaveAs
  73. self.menuFileSep_1.Text = "-"
  74. self.menuFileSep_1.Index = 4
  75. self.menuFileExit.Text = "E&xit"
  76. self.menuFileExit.Shortcut = WinForms.Shortcut.AltF4
  77. self.menuFileExit.ShowShortcut = False
  78. self.menuFileExit.Index = 5
  79. self.menuFileExit.Click += self.OnClickFileExit
  80. self.fileMenu.Text = "&File"
  81. self.fileMenu.Index = 0
  82. items = (self.menuFileNew, self.menuFileOpen,
  83. self.menuFileSave, self.menuFileSaveAs,
  84. self.menuFileSep_1, self.menuFileExit)
  85. self.fileMenu.MenuItems.AddRange(items)
  86. # ===================================================================
  87. # Edit menu
  88. # ===================================================================
  89. self.menuEditUndo.Text = "&Undo"
  90. self.menuEditUndo.Shortcut = WinForms.Shortcut.CtrlZ
  91. self.menuEditUndo.Index = 0
  92. self.menuEditUndo.Click += self.OnClickEditUndo
  93. self.menuEditRedo.Text = "&Redo"
  94. self.menuEditRedo.Shortcut = WinForms.Shortcut.CtrlY
  95. self.menuEditRedo.Index = 1
  96. self.menuEditRedo.Click += self.OnClickEditRedo
  97. self.menuEditSep_1.Text = "-"
  98. self.menuEditSep_1.Index = 2
  99. self.menuEditCut.Text = "Cut"
  100. self.menuEditCut.Shortcut = WinForms.Shortcut.CtrlX
  101. self.menuEditCut.Index = 3
  102. self.menuEditCut.Click += self.OnClickEditCut
  103. self.menuEditCopy.Text = "Copy"
  104. self.menuEditCopy.Shortcut = WinForms.Shortcut.CtrlC
  105. self.menuEditCopy.Index = 4
  106. self.menuEditCopy.Click += self.OnClickEditCopy
  107. self.menuEditPaste.Text = "Paste"
  108. self.menuEditPaste.Shortcut = WinForms.Shortcut.CtrlV
  109. self.menuEditPaste.Index = 5
  110. self.menuEditPaste.Click += self.OnClickEditPaste
  111. self.menuEditSelectAll.Text = "Select All"
  112. self.menuEditSelectAll.Shortcut = WinForms.Shortcut.CtrlA
  113. self.menuEditSelectAll.Index = 7
  114. self.menuEditSelectAll.Click += self.OnClickEditSelectAll
  115. self.menuEditSep_2.Text = "-"
  116. self.menuEditSep_2.Index = 6
  117. self.editMenu.Text = "&Edit"
  118. self.editMenu.Index = 1
  119. items = (self.menuEditUndo, self.menuEditRedo,
  120. self.menuEditSep_1, self.menuEditCut,
  121. self.menuEditCopy, self.menuEditPaste,
  122. self.menuEditSep_2, self.menuEditSelectAll)
  123. self.editMenu.MenuItems.AddRange(items)
  124. # ===================================================================
  125. # Format Menu
  126. # ===================================================================
  127. self.menuFormatWordWrap.Text = "Word Wrap"
  128. self.menuFormatWordWrap.Checked = self.word_wrap
  129. self.menuFormatWordWrap.Index = 1
  130. self.menuFormatWordWrap.Click += self.OnClickFormatWordWrap
  131. self.menuFormatFont.Text = "Fo&nt"
  132. self.menuFormatFont.Index = 0
  133. self.menuFormatFont.Click += self.OnClickFormatFont
  134. self.formatMenu.Text = "F&ormat"
  135. self.formatMenu.Index = 2
  136. items = (self.menuFormatWordWrap, self.menuFormatFont)
  137. self.formatMenu.MenuItems.AddRange(items)
  138. # ===================================================================
  139. # About menu
  140. # ===================================================================
  141. self.menuHelpAbout.Text = "&About"
  142. self.menuHelpAbout.Index = 0
  143. self.menuHelpAbout.Click += self.OnClickHelpAbout
  144. self.aboutMenu.Text = "&Help"
  145. self.aboutMenu.Index = 3
  146. self.aboutMenu.MenuItems.Add(self.menuHelpAbout)
  147. self.statusBarPanel1.Dock = WinForms.DockStyle.Fill
  148. self.statusBarPanel1.Text = "Ready"
  149. self.statusBarPanel1.Width = 755
  150. self.richTextBox.Dock = WinForms.DockStyle.Fill
  151. self.richTextBox.Size = System.Drawing.Size(795, 485)
  152. self.richTextBox.TabIndex = 0
  153. self.richTextBox.AutoSize = True
  154. self.richTextBox.ScrollBars = WinForms.RichTextBoxScrollBars.ForcedBoth
  155. self.richTextBox.Font = System.Drawing.Font("Tahoma", 10.0)
  156. self.richTextBox.AcceptsTab = True
  157. self.richTextBox.Location = System.Drawing.Point(0, 0)
  158. self.statusBar.BackColor = System.Drawing.SystemColors.Control
  159. self.statusBar.Location = System.Drawing.Point(0, 518)
  160. self.statusBar.Size = System.Drawing.Size(775, 19)
  161. self.statusBar.TabIndex = 1
  162. self.statusBar.ShowPanels = True
  163. self.statusBar.Panels.Add(self.statusBarPanel1)
  164. items = (self.fileMenu, self.editMenu, self.formatMenu, self.aboutMenu)
  165. self.mainMenu.MenuItems.AddRange(items)
  166. self.openFileDialog.Filter = "Text documents|*.txt|RTF document|*.rtf"
  167. self.openFileDialog.Title = "Open document"
  168. self.saveFileDialog.Filter = "Text Documents|*.txt|" \
  169. "Rich Text Format|*.rtf"
  170. self.saveFileDialog.Title = "Save document"
  171. self.saveFileDialog.FileName = "Untitled"
  172. self.AutoScaleBaseSize = System.Drawing.Size(5, 13)
  173. self.ClientSize = System.Drawing.Size(775, 537)
  174. self.Menu = self.mainMenu
  175. self.Text = "Python Wordpad"
  176. self.Controls.Add(self.statusBar)
  177. self.Controls.Add(self.richTextBox)
  178. self.statusBarPanel1.EndInit()
  179. def Dispose(self):
  180. self.components.Dispose()
  181. WinForms.Form.Dispose(self)
  182. def OnClickFileNew(self, sender, args):
  183. self.SaveChangesDialog()
  184. self.NewDocument()
  185. def OnClickFileOpen(self, sender, args):
  186. self.SaveChangesDialog()
  187. self.OpenDocument()
  188. def OnClickFileSave(self, sender, args):
  189. self.SaveDocument()
  190. def OnClickFileSaveAs(self, sender, args):
  191. self.filename = ''
  192. self.SaveDocument()
  193. def OnClickFileExit(self, sender, args):
  194. self.SaveChangesDialog()
  195. self.Close()
  196. def OnClickEditUndo(self, sender, args):
  197. self.richTextBox.Undo()
  198. def OnClickEditRedo(self, sender, args):
  199. self.richTextBox.Redo()
  200. def OnClickEditCut(self, sender, args):
  201. self.richTextBox.Cut()
  202. def OnClickEditCopy(self, sender, args):
  203. self.richTextBox.Copy()
  204. def OnClickEditPaste(self, sender, args):
  205. self.richTextBox.Paste()
  206. def OnClickEditSelectAll(self, sender, args):
  207. self.richTextBox.SelectAll()
  208. def OnClickFormatWordWrap(self, sender, args):
  209. value = not self.word_wrap
  210. self.richTextBox.WordWrap = value
  211. self.menuFormatWordWrap.Checked = value
  212. self.word_wrap = value
  213. def OnClickFormatFont(self, sender, args):
  214. if self.fontDialog.ShowDialog() == WinForms.DialogResult.OK:
  215. self.richTextBox.SelectionFont = self.fontDialog.Font
  216. def OnClickHelpAbout(self, sender, args):
  217. AboutForm().ShowDialog(self)
  218. def NewDocument(self):
  219. self.doctype = 1
  220. self.richTextBox.Rtf = ''
  221. self.richTextBox.Text = ''
  222. self.Text = 'Python Wordpad - (New Document)'
  223. self.filename = ''
  224. def OpenDocument(self):
  225. if self.openFileDialog.ShowDialog() != WinForms.DialogResult.OK:
  226. return
  227. filename = self.openFileDialog.FileName
  228. stream = File.OpenRead(filename)
  229. buff = System.Array.CreateInstance(System.Byte, 1024)
  230. buff.Initialize()
  231. data = []
  232. read = 1
  233. while read > 0:
  234. read, _ = stream.Read(buff, 0, 1024)
  235. temp = Encoding.ASCII.GetString(buff, 0, read)
  236. data.append(temp)
  237. data = ''.join(data)
  238. stream.Close()
  239. filename = self.filename = filename.lower()
  240. if filename.endswith('.rtf'):
  241. self.richTextBox.Rtf = data
  242. self.doctype = 2
  243. else:
  244. self.richTextBox.Text = data
  245. self.doctype = 1
  246. self.Text = 'Python Wordpad - %s' % filename
  247. self.richTextBox.Select(0, 0)
  248. def SaveDocument(self):
  249. filename = self.filename
  250. if not filename:
  251. if self.saveFileDialog.ShowDialog() != WinForms.DialogResult.OK:
  252. return
  253. filename = self.saveFileDialog.FileName
  254. filename = self.filename = filename.lower()
  255. self.Text = 'Python Wordpad - %s' % filename
  256. self.richTextBox.Select(0, 0)
  257. stream = File.OpenWrite(filename)
  258. if filename.endswith('.rtf'):
  259. data = self.richTextBox.Rtf
  260. else:
  261. data = self.richTextBox.Text
  262. data = System.Text.Encoding.ASCII.GetBytes(System.String(data))
  263. stream.Write(data, 0, data.Length)
  264. stream.Close()
  265. def SaveChangesDialog(self):
  266. if self.richTextBox.Modified:
  267. if WinForms.MessageBox.Show(
  268. "Save changes?", "Word Pad",
  269. WinForms.MessageBoxButtons.OK |
  270. WinForms.MessageBoxButtons.YesNo
  271. ) == WinForms.DialogResult.Yes:
  272. self.SaveDocument()
  273. return 1
  274. return 0
  275. class AboutForm(WinForms.Form):
  276. def __init__(self):
  277. super().__init__()
  278. self.InitializeComponent()
  279. def InitializeComponent(self):
  280. """Initialize form components."""
  281. self.Text = "Python Wordpad"
  282. self.components = System.ComponentModel.Container()
  283. self.btnClose = WinForms.Button()
  284. self.label1 = WinForms.Label()
  285. self.SuspendLayout()
  286. self.btnClose.Location = System.Drawing.Point(360, 181)
  287. self.btnClose.Name = "bnClose"
  288. self.btnClose.TabIndex = 1
  289. self.btnClose.Text = "&Close"
  290. self.btnClose.Click += self.OnClickClose
  291. self.label1.Location = System.Drawing.Point(20, 20)
  292. self.label1.Name = "label1"
  293. self.label1.Size = System.Drawing.Size(296, 140)
  294. self.label1.TabIndex = 2
  295. self.label1.Text = "Python Wordpad - an example winforms " \
  296. "application using Python.NET"
  297. self.AutoScaleBaseSize = System.Drawing.Size(5, 13)
  298. self.ClientSize = System.Drawing.Size(300, 150)
  299. self.Controls.AddRange((self.label1, self.btnClose))
  300. self.FormBorderStyle = WinForms.FormBorderStyle.FixedDialog
  301. self.MaximizeBox = False
  302. self.MinimizeBox = False
  303. self.Name = "AboutForm"
  304. self.ShowInTaskbar = False
  305. self.StartPosition = WinForms.FormStartPosition.CenterScreen
  306. self.Text = "About"
  307. self.ResumeLayout(False)
  308. def OnClickClose(self, sender, args):
  309. self.Close()
  310. def app_thread():
  311. app = Wordpad()
  312. WinForms.Application.Run(app)
  313. app.Dispose()
  314. def main():
  315. thread = Thread(ThreadStart(app_thread))
  316. thread.SetApartmentState(ApartmentState.STA)
  317. thread.Start()
  318. thread.Join()
  319. if __name__ == '__main__':
  320. main()

这是完全把winform拿过来了啊??!!,以后写python 带UI的可以直接 py-winform.

 还没完:继续. 

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import clr
  4. import System
  5. clr.AddReference("System.Windows.Forms")
  6. import System.Windows.Forms as WinForms
  7. from System.Drawing import Color, Size, Point
  8. class Splitter(WinForms.Form):
  9. """A WinForms example transcribed to Python from the MSDN article:
  10. 'Creating a Multipane User Interface with Windows Forms'."""
  11. def __init__(self):
  12. super().__init__()
  13. # Create an instance of each control being used.
  14. self.components = System.ComponentModel.Container()
  15. self.treeView1 = WinForms.TreeView()
  16. self.listView1 = WinForms.ListView()
  17. self.richTextBox1 = WinForms.RichTextBox()
  18. self.splitter1 = WinForms.Splitter()
  19. self.splitter2 = WinForms.Splitter()
  20. self.panel1 = WinForms.Panel()
  21. # Set properties of TreeView control.
  22. self.treeView1.Dock = WinForms.DockStyle.Left
  23. self.treeView1.Width = self.ClientSize.Width // 3
  24. self.treeView1.TabIndex = 0
  25. self.treeView1.Nodes.Add("TreeView")
  26. # Set properties of ListView control.
  27. self.listView1.Dock = WinForms.DockStyle.Top
  28. self.listView1.Height = self.ClientSize.Height * 2 // 3
  29. self.listView1.TabIndex = 0
  30. self.listView1.Items.Add("ListView")
  31. # Set properties of RichTextBox control.
  32. self.richTextBox1.Dock = WinForms.DockStyle.Fill
  33. self.richTextBox1.TabIndex = 2
  34. self.richTextBox1.Text = "richTextBox1"
  35. # Set properties of Panel's Splitter control.
  36. self.splitter2.Dock = WinForms.DockStyle.Top
  37. # Width is irrelevant if splitter is docked to Top.
  38. self.splitter2.Height = 3
  39. # Use a different color to distinguish the two splitters.
  40. self.splitter2.BackColor = Color.Blue
  41. self.splitter2.TabIndex = 1
  42. # Set TabStop to false for ease of use when negotiating UI.
  43. self.splitter2.TabStop = False
  44. # Set properties of Form's Splitter control.
  45. self.splitter1.Location = System.Drawing.Point(121, 0)
  46. self.splitter1.Size = System.Drawing.Size(3, 273)
  47. self.splitter1.BackColor = Color.Red
  48. self.splitter1.TabIndex = 1
  49. # Set TabStop to false for ease of use when negotiating UI.
  50. self.splitter1.TabStop = False
  51. # Add the appropriate controls to the Panel.
  52. for item in (self.richTextBox1, self.splitter2, self.listView1):
  53. self.panel1.Controls.Add(item)
  54. # Set properties of Panel control.
  55. self.panel1.Dock = WinForms.DockStyle.Fill
  56. self.panel1.TabIndex = 2
  57. # Add the rest of the controls to the form.
  58. for item in (self.panel1, self.splitter1, self.treeView1):
  59. self.Controls.Add(item)
  60. self.Text = "Intricate UI Example"
  61. def Dispose(self):
  62. self.components.Dispose()
  63. WinForms.Form.Dispose(self)
  64. def main():
  65. app = Splitter()
  66. WinForms.Application.Run(app)
  67. app.Dispose()
  68. if __name__ == '__main__':
  69. main()

展示了 相对布局.

 再来一个:hello form.

  1. import clr
  2. clr.AddReference("System.Windows.Forms")
  3. import System.Windows.Forms as WinForms
  4. from System.Drawing import Size, Point
  5. class HelloApp(WinForms.Form):
  6. """A simple hello world app that demonstrates the essentials of
  7. winforms programming and event-based programming in Python."""
  8. def __init__(self):
  9. super().__init__()
  10. self.Text = "Hello World From Python"
  11. self.AutoScaleBaseSize = Size(5, 13)
  12. self.ClientSize = Size(392, 117)
  13. h = WinForms.SystemInformation.CaptionHeight
  14. self.MinimumSize = Size(392, (117 + h))
  15. # Create the button
  16. self.button = WinForms.Button()
  17. self.button.Location = Point(160, 64)
  18. self.button.Size = Size(820, 20)
  19. self.button.TabIndex = 2
  20. self.button.Text = "Click Me!"
  21. # Register the event handler
  22. self.button.Click += self.button_Click
  23. # Create the text box
  24. self.textbox = WinForms.TextBox()
  25. self.textbox.Text = "Hello World"
  26. self.textbox.TabIndex = 1
  27. self.textbox.Size = Size(1260, 40)
  28. self.textbox.Location = Point(160, 24)
  29. # Add the controls to the form
  30. self.AcceptButton = self.button
  31. self.Controls.Add(self.button)
  32. self.Controls.Add(self.textbox)
  33. def button_Click(self, sender, args):
  34. """Button click event handler"""
  35. print ("Click")
  36. WinForms.MessageBox.Show("Please do not press this button again.")
  37. def run(self):
  38. WinForms.Application.Run(self)
  39. def main():
  40. form = HelloApp()
  41. print ("form created")
  42. app = WinForms.Application
  43. print ("app referenced")
  44. app.Run(form)
  45. if __name__ == '__main__':
  46. main()

这个运行结果就不展示了. 运行起来就可以看到.

还没完, 这个脚本展示了 WPF, 可以和  xaml  单独写

  1. import clr
  2. import sys
  3. if sys.platform.lower() not in ['cli','win32']:
  4. print("only windows is supported for wpf")
  5. clr.AddReference(r"wpf\PresentationFramework")
  6. from System.IO import StreamReader
  7. from System.Windows.Markup import XamlReader
  8. from System.Threading import Thread, ThreadStart, ApartmentState
  9. from System.Windows import Application, Window
  10. class MyWindow(Window):
  11. def __init__(self):
  12. stream = StreamReader("DynamicGrid.xaml")
  13. window = XamlReader.Load(stream.BaseStream)
  14. Application().Run(window)
  15. if __name__ == '__main__':
  16. thread = Thread(ThreadStart(MyWindow))
  17. thread.SetApartmentState(ApartmentState.STA)
  18. thread.Start()
  19. thread.Join()

当然还有xaml.

  1. <Window
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="WpfApplication1" Height="300" Width="300">
  5. <Grid>
  6. <Grid.RowDefinitions>
  7. <RowDefinition Height="*"/>
  8. <RowDefinition Height="Auto"/>
  9. <RowDefinition Height="*"/>
  10. </Grid.RowDefinitions>
  11. <Grid.ColumnDefinitions>
  12. <ColumnDefinition Width="*"/>
  13. <ColumnDefinition Width="Auto"/>
  14. <ColumnDefinition Width="*"/>
  15. </Grid.ColumnDefinitions>
  16. <Label Content="Left" Grid.Column="0" Background="LightBlue" />
  17. <GridSplitter
  18. VerticalAlignment="Stretch"
  19. HorizontalAlignment="Stretch"
  20. Grid.Column="1"
  21. Width="5"
  22. Grid.RowSpan="3"/>
  23. <Label Content="Right" Grid.Column="2" Grid.Row="2" Background="LightBlue" />
  24. <Label Content="Top" Grid.Column="2" Background="LightGreen"/>
  25. <GridSplitter
  26. HorizontalAlignment="Stretch"
  27. VerticalAlignment="Stretch"
  28. Grid.Row="1"
  29. Width="Auto"
  30. Height="5"
  31. Grid.ColumnSpan="3"/>
  32. <Label Content="Bottom" Grid.Column="0" Grid.Row="2" Background="LightGreen" />
  33. </Grid>
  34. </Window>

python 里使用.NET 说完了.

 接下来说一下 C# 中如何嵌入python .主要说环境怎么配. 毕竟对C# 中如何嵌入python 不熟, 况且就算真的有需求 命令行 或者网络 应该更容易上手些... 环境配置过程在注释中体现.直接上例子:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Python.Runtime; // 这个是 nuget下载的,并不是python安装目录里那个dll
  7. using System.Net;
  8. using SC= System.Console;
  9. namespace CsPyNET
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. /*
  16. 操作系统: Win10 64位:
  17. python解释器: Python3.8.8_64位 VS2015.
  18. 配置管理器:解决方案也得是64位;
  19. 项目->属性->[目标框架].NET Fraemwork 4 {快捷键::alt+PP}
  20. 工具->NuGet包管理器->管理解决方案的NuGet程序包(N) {快捷键:alt+TNN}. [浏览->底下搜索框搜 pythonnet 出现很多选项]
  21. pythonnet_py38_win.2.5.2
  22. 安装这个:到当前项目.
  23. 安装后:在.sln同级目录packages文件夹下会下载对应文件.
  24. 引用该文件
  25. //using Python.Runtime;
  26. C:\Users\Administrator\AppData\Local\Programs\Python\Python38\Lib\site-packages\pythonnet\runtime
  27. */
  28. // 这是我的pythonn安装路径.
  29. /*
  30. "https://pythonnet.github.io/"
  31. "将 Python 嵌入到 .NET 中 - Python.NET 文档 https://pythonnet.github.io/pythonnet/dotnet.html"
  32. */
  33. string dllPath = @"C:\Users\Administrator\AppData\Local\Programs\Python\Python38\python38.dll";
  34. string pythonHomePath = @"C:\Users\Administrator\AppData\Local\Programs\Python\Python38";
  35. string[] py_paths =
  36. {
  37. "DLLs",
  38. "Lib",// "原文是lib 我的3.8只有Lib路径,所以改成 Lib"
  39. "Lib/site-packages",
  40. "Lib/site-packages/win32" ,
  41. "Lib/site-packages/win32/lib",
  42. "Lib/site-packages/Pythonwin"
  43. };
  44. string pySearchPath = $"{pythonHomePath};";
  45. foreach (string p in py_paths)
  46. {
  47. pySearchPath += $"{pythonHomePath}/{p};";
  48. }
  49. // 此处解决BadPythonDllException报错
  50. // Runtime.PythonDLL = dllPath; //
  51. Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", dllPath);
  52. // 配置python环境搜索路径解决PythonEngine.Initialize() 崩溃
  53. PythonEngine.PythonHome = pythonHomePath;
  54. PythonEngine.PythonPath = pySearchPath;
  55. PythonEngine.Initialize();
  56. using (Py.GIL())
  57. {
  58. dynamic np = Py.Import("numpy");
  59. dynamic cv2= Py.Import("cv2");
  60. PyObject ar = np.array(new int[] { 1, 2, 3, 4 });
  61. SC.WriteLine(ar);
  62. SC.WriteLine(cv2.__version__);
  63. }
  64. SC.WriteLine("");
  65. SC.ReadKey();// ############### wait ############# //##################################################################################################
  66. }//Main
  67. //##################################################################################################
  68. }//Program
  69. }//CsPyNET

结束.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/478455
推荐阅读
相关标签
  

闽ICP备14008679号