我正在与 Pythonnet 合作创建一个使用后端 Python 代码的 C# GUI。我刚刚学习连接的工作原理,需要将 Python 变量输入 C# 并将其显示在 C# 文本框中。如何获取 Python 中“outer”的计算值并将其显示在 textBox1 中?将输出发送到控制台时它工作正常,但我需要它在文本框中。
public Form1()
{
InitializeComponent();
Runtime.PythonDLL = @"C:\Program Files (x86)\Python312-32\python312.dll";
}
private void button1_Click(object sender, EventArgs e)
{
//THIS WORKS NOW!!
PyModule scope;
PythonEngine.Initialize();
using (Py.GIL())
{
scope = Py.CreateScope();
//scope.Exec("print('Hello World from Python!')");
dynamic np = Py.Import("numpy");
dynamic outer=(np.cos(np.pi * 2));
//This is the part that does not work.
//It says can't convert a PyObject to a string.
textBox1.Text = outer
//Console.WriteLine("Press enter to close...");
//Console.ReadLine();
}
尝试如下所示:
using Python.Runtime;
class Program
{
static void Main()
{
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
dynamic someValue = (np.cos(np.pi * 2))
var stringValue = new PyString(someValue)
Console.WriteLine(stringValue );
}
}
}