python用 PythonNet 从 Python 调用 WPF 类库 UI 用XAML

pythonnet 是pythonhe.net通用的神器不多介绍了.

这次这基本上跟python没有关系了.

和winform一样先导包

python 复制代码
import clr
clr.AddReference("PresentationFramework.Classic, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
clr.AddReference("PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
 
from System.Windows import Application
from System.Windows import Window
from System.Windows import MessageBox
from System.Windows import LogicalTreeHelper
from System.Windows.Markup import XamlReader
from System.Threading import Thread
from System.Threading import ApartmentState
from System.Threading import ThreadStart
from System import *
 

哈哈哈 有没有感觉和 C#一样.

cs 复制代码
using System;
using SC = System.Console;

是不是一模一样;

接下来: 写个类. 当然你可以用C# VB.net单独做 成DLL也没关系. 重要的是先把婚结了 孩子生出来. 不对 先把东西生产出来.

python 复制代码
class MainWindow(Window):
 
  def __init__(self):
    Window.__init__(self)
 
    #  XAML
    xaml = """
    <Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <Grid>  
      <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
      </Grid.RowDefinitions>
      <Button Name="Button1" Grid.Row="0">Button 1</Button>
      <Button Name="Button2" Grid.Row="1">Button 2</Button>
      </Grid>
    </Page>
    """
    page = XamlReader.Parse(xaml)
 
    # connect Button1
    self.Button1 = LogicalTreeHelper.FindLogicalNode(page, "Button1")
    self.Button1.Click += self.Button1_Click
 
    # connect Button2
    self.Button2 = LogicalTreeHelper.FindLogicalNode(page, "Button2")
    self.Button2.Click += self.Button2_Click
 
    # 
    self.Title = "Python WPF App with XAML!"
    self.Width = 350
    self.Height = 300
    self.Content = page
 
  def Button1_Click(self, sender, e):
    MessageBox.Show(self.Button1.Content + " is clicked!")
 
  def Button2_Click(self, sender, e):
    MessageBox.Show(self.Button2.Content + " is clicked!")
python 复制代码
def STAMain():
  app = Application()
  app.Run(MainWindow())
 
def main():
  t = Thread(ThreadStart(STAMain))
  t.ApartmentState = ApartmentState.STA
  t.Start()
  t.Join()
 
if __name__ == "__main__":
  main()

界面一定要线程里面; 要不然python解释器会卡死.

当然 你也可以这么干;用C#界面类库打包写成DLL在用python调用. python只管传参数.

对于性能要求不高的场合就很合适.

相关推荐
小宁爱Python1 分钟前
从零搭建 RAG 智能问答系统3:聊天信息持久化和登录注册
python
天才少女爱迪生1 小时前
LLVM(Low Level Virtual Machine)介绍
python·数据挖掘
碳酸的唐4 小时前
A* 工程实践全指南:从启发式设计到可视化与性能优化
python·神经网络
倔强青铜三7 小时前
苦练Python第64天:从零掌握多线程,threading模块全面指南
人工智能·python·面试
分布式存储与RustFS8 小时前
告别复杂配置:用Milvus、RustFS和Vibe Coding,60分钟DIY专属Chatbot
wpf·文件系统·milvus·对象存储·minio·rustfs·vibe
Q26433650239 小时前
【有源码】基于Hadoop生态的大数据共享单车数据分析与可视化平台-基于Python与大数据的共享单车多维度数据分析可视化系统
大数据·hadoop·python·机器学习·数据分析·spark·毕业设计
计算机毕业设计木哥9 小时前
计算机毕设选题推荐:基于Hadoop和Python的游戏销售大数据可视化分析系统
大数据·开发语言·hadoop·python·信息可视化·spark·课程设计
小蕾Java9 小时前
PyCharm 2025:使用图文教程!
ide·python·pycharm
至此流年莫相忘9 小时前
配置Python环境之Conda
python·conda