代码链接见:下载地址
设计了X+Y求值的程序,X和Y值是在Python程序中设置好的。
拖拽了一个button按钮,在行动中设置如下程序
// Step 1: 执行 Python 代码,定义函数或获取结果
pyCom.run("import anylogic_test"); // 导入你的 Python 模块
Attempt attempt = pyCom.run("anylogic_test.get_x()"); // 获取返回值并转为字符串
int feedbackStrX = pyCom.runResults(int.class,"anylogic_test.get_x()"); //分配浮点型数据
if (attempt.isSuccessful()) {
traceln("attempt.getFeedback"+attempt.getFeedback());
traceln("Python 返回的值是:" +feedbackStrX);
} else {
traceln("Python 执行出错:" + attempt.isSuccessful());
}
attempt.getFeedback()返回的是String型数据。
拖拽了另外一个button按钮,在行动中设置如下程序
pyCom.run("import anylogic_test"); // 导入你的 Python 模块
Attempt attempt = pyCom.run("anylogic_test.get_result()"); // 获取返回值并转为字符串
int feedbackStr = pyCom.runResults(int.class,"anylogic_test.get_result()"); //分配浮点型数据
if (attempt.isSuccessful()) {
traceln("attempt.getFeedback"+attempt.getFeedback());
traceln("Python 返回的值是:" +feedbackStr);
} else {
traceln("Python 执行出错:" + attempt.isSuccessful());
}
设计了X+Y求值的程序,X和Y值是在手动输入。
拖拽了一个文本编辑框按钮,在行动中设置如下程序
// Step 1: 从 Edit Box 获取用户输入的值
String inputStr1 = editBoxX.getText();
int javaX;
try {
// 转换为整数
javaX = Integer.parseInt(inputStr1);
} catch (NumberFormatException e) {
traceln("❌ 输入不是有效的整数,请重新输入!");
return;
}
对输入的X值和Y值进行求和,完成代码如下:
// Step 1: 导入模块
pyCom.run("import anylogic_test");
// Step 2: 设置你想传给 Python 的值
// int javaX = 10;
// 或者从界面控件(如输入框)获取值
// Step 1: 从 Edit Box 获取用户输入的值
String inputStr1 = editBoxX.getText();
int javaX;
try {
// 转换为整数
javaX = Integer.parseInt(inputStr1);
} catch (NumberFormatException e) {
traceln("❌ 输入不是有效的整数,请重新输入!");
return;
}
String inputStr2 = editBoxX1.getText();
int javaY;
try {
// 转换为整数
javaY = Integer.parseInt(inputStr2);
} catch (NumberFormatException e) {
traceln("❌ 输入不是有效的整数,请重新输入!");
return;
}
// Step 3: 构建带参数的 Python 语句
String command = String.format("anylogic_test.get_p(%d)", javaX);
// Step 4: 执行并获取反馈
Attempt attempt = pyCom.run(command);
int feedbackStrp1 = pyCom.runResults(int.class,"anylogic_test.get_p(%d)", javaX); //分配浮点型数据
int feedbackStrp2 = pyCom.runResults(int.class,"anylogic_test.get_p(%d)", javaY); //分配浮点型数据
if (attempt.isSuccessful()) {
traceln("Python 返回结果:" + (feedbackStrp1 + feedbackStrp2));
} else {
traceln("❌ Python 执行出错:" + attempt.isSuccessful());
}