从windows窗体调用Python脚本

2024-10-01 15:44:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个铁蟒新手,需要一些帮助。我有一个用visualbasic2010速成版创建的windows窗体,它包含两个文本框('txtNumber'和'txtResult')和一个按钮('btnSquare)。我想做的是能够调用下面的Python脚本('方块字.py')单击表单上的按钮

class SquarePython:

    def __init__(self, number):

        self.sq = number*number

此脚本应将输入到“txtNumber”的数字平方,然后将结果输出到“txtResult”。我知道这几乎太简单了,但我只需要知道基本知识。以下是我目前在VB代码中所拥有的内容

^{pr2}$

提前谢谢。在


Tags: pyself脚本表单numberwindows窗体按钮
1条回答
网友
1楼 · 发布于 2024-10-01 15:44:51

如果你不介意的话,我会用C来回答。但无论如何,它与VB版本非常相似。对于您的代码,访问SquarePython非常简单

ScriptEngine py = Python.CreateEngine();

ScriptScope scope = py.ExecuteFile("Square.py");

dynamic square = scope.GetVariable("SquarePython");

int result = (int)square(5);

Console.WriteLine(result.sq); //prints 25 as you might expected

但为了简单起见,我会稍微修改一下python代码,如下所示

^{pr2}$

所以你不必每次计算都要创建一个对象。检索变量并调用square方法的代码如下:

ScriptEngine py = Python.CreateEngine();

ScriptScope scope = py.ExecuteFile("Square.py");
//get variable and then create and object. Could be stored somewhere between computations
dynamic squareInstance = scope.GetVariable("SquarePython")(); 

int result = (int) squareInstance.Square(5);

Console.WriteLine(result);

注意:如果需要将^{cd3>}关键字转换为VB.NET版在

相关问题 更多 >

    热门问题