使用pythonnet构造自定义表单

Constructor of custom form with pythonnet

我对从 DevExpress.v17.1 库扩展 XtraForm 的表单(在 C# 中创建)的自定义构造函数有疑问。它有两个构造函数:

protected BaseForm()
{
    InitializeComponent();
}

protected BaseForm(IClient client)
{
    InitializeComponent();
    ... many code
}

其中IClient是接口。 这种形式有很多依赖关系,它们都在库中编译。 当我扩展此表单并尝试通过代码创建实例时:

class TestApp(BaseForm):

def __init__(self):
    self.Text = "Hello World From Python"
    self.components = System.ComponentModel.Container()
    self.AutoScaleBaseSize = Size(5, 13)
    self.ClientSize = Size(392, 117)
    h = WinForms.SystemInformation.CaptionHeight
    self.MinimumSize = Size(392, (117 + h))

    # Create the button
    self.button = WinForms.Button()
    self.button.Location = Point(160, 64)
    self.button.Size = Size(150, 20)
    self.button.TabIndex = 2
    self.button.Text = "Click Me!"

    # Register the event handler
    self.button.Click += self.button_Click

    # Create the text box
    self.textbox = WinForms.TextBox()
    self.textbox.Text = "Hello World"
    self.textbox.TabIndex = 1
    self.textbox.Size = Size(126, 40)
    self.textbox.Location = Point(160, 24)

    # Add the controls to the form
    self.AcceptButton = self.button
    self.Controls.Add(self.button)
    self.Controls.Add(self.textbox)

def button_Click(self, sender, args):
    """Button click event handler"""
    print ("Click")
    WinForms.MessageBox.Show("Please do not press this button again.")

def run(self):
    WinForms.Application.Run(self)

def Dispose(self):
    self.components.Dispose()
    WinForms.Form.Dispose(self)

运行 初始化代码:

def main():
    form = TestApp()
    form.run()
    form.Dispose()

if __name__ == '__main__':
    main()

我有一个错误:

Traceback (most recent call last):
  File "C:/Users/v.khvorostianyi/PycharmProjects/CSharp/Test.py", line 141, in <module> 
    main()
  File "C:/Users/v.khvorostianyi/PycharmProjects/CSharp/Test.py", line 85, in main
    form = TestApp()
TypeError: no constructor matches given arguments

Python=3.6.2, pythonnet=2.3.0
.NET=4.6.1

项目需要进行自动化测试,这个表格是配合工作流程所必需的。 为什么我会出现这样的错误?

BaseForm 中的构造函数被 protected 访问修饰符隐藏,只能在 BaseForm 及其派生的 class 实例中访问。所以,form = TestApp()不能使用,因为空参数的构造函数被隐藏了。

至少有两种方法可以解决这个问题:

0。您可以在 BaseForm 构造函数中使用 public 访问修饰符。

public BaseForm()
{
    InitializeComponent();
}

public BaseForm(IClient client)
{
    InitializeComponent();
    //... many code
}

1。您可以尝试在派生的 class:

中使用 __new__ 方法重载 .net 构造函数
def __new__(cls):        
    return BaseForm.__new__(cls)