使用Python.NET开发WinForms窗体遇System.NullReferenceException问题求助
Python.NET 启动WinForms窗体触发空引用异常的解决方法
我正在学习Python.NET模块,但刚开始就遇到了问题。我尝试执行以下简单代码:
import clr clr.AddReference("System") clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms") import System import System.Drawing import System.Windows.Forms class FormLogin(System.Windows.Forms.Form): def __init__(self): pass def main(): System.Windows.Forms.Application.Run(FormLogin()) if __name__ == "__main__": main()
不幸的是,运行时抛出了如下异常:
Traceback (most recent call last): File "C:\Users\MyUser\Desktop\Test\APP.py", line 21, in <module> main() File "C:\Users\MyUser\Desktop\Test\APP.py", line 18, in main System.Windows.Forms.Application.Run(FormLogin()) System.NullReferenceException: 对象引用未设置到对象的实例。 at System.Windows.Forms.Form.get_IsMdiChild() at System.Windows.Forms.Form.SetVisibleCore(Boolean value) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
解决办法
问题根源是:在Python.NET中继承.NET的Form类时,必须显式调用父类的构造函数,否则窗体的内部初始化逻辑不会执行,核心属性未实例化,从而触发空引用异常。
只需要修改FormLogin类的__init__方法,添加父类构造函数的调用即可:
import clr clr.AddReference("System") clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms") import System import System.Drawing import System.Windows.Forms class FormLogin(System.Windows.Forms.Form): def __init__(self): # 调用父类Form的构造函数,完成内部初始化 super(FormLogin, self).__init__() # 可选:添加窗体的基础设置,比如标题 self.Text = "登录窗口" def main(): System.Windows.Forms.Application.Run(FormLogin()) if __name__ == "__main__": main()
这样修改后,窗体就能正常启动,不会再抛出异常。
内容的提问来源于stack exchange,提问作者Itay Dvash
相关产品推荐
相关产品推荐

