我正在尝试使用 Python 打开一个对话框以接受对我的 C++ 应用程序的输入。
这是我正在尝试做的一个非常小的表示:
#include <iostream>
#include <Python.h>
int main()
{
/* Begin Python Ititialization - only needs to be done once. */
PyObject *ip_module_name = NULL;
PyObject *ip_module = NULL;
PyObject *ip_module_contents = NULL;
PyObject *ip_module_getip_func = NULL;
Py_Initialize();
PyEval_InitThreads();
ip_module_name = PyString_FromString( "get_ip" );
ip_module = PyImport_Import( ip_module_name );
ip_module_contents = PyModule_GetDict( ip_module );
ip_module_getip_func = PyDict_GetItemString( ip_module_contents, "get_ip_address" );
/* End Initialization */
PyGILState_STATE state = PyGILState_Ensure();
PyObject *result = PyObject_CallObject( ip_module_getip_func, NULL );
if( result == Py_None )
printf( "None\n" );
else
printf( "%s\n", PyString_AsString( result ) );
PyGILState_Release( state );
/* This is called when the progam exits. */
Py_Finalize();
}
但是,当我使用 PyObject_CallObject 调用该函数时,应用程序会出现段错误。我猜这是因为我使用的是 Tk 库。我尝试将我的应用程序与 _tkinter.lib、tk85.lib、tcl85.lib、tkstub85.lib、tclstub85.lib 链接,但这些都没有帮助。我好难过...
这是脚本:
import Tkinter as tk
from tkSimpleDialog import askstring
from tkMessageBox import showerror
def get_ip_address():
root = tk.Tk()
root.withdraw()
ip = askstring( 'Server Address', 'Enter IP:' )
if ip is None:
return None
ip = ip.strip()
if ip is '':
showerror( 'Error', 'Please enter a valid IP address' )
return get_ip_address()
if len(ip.split(".")) is not 4:
showerror( 'Error', 'Please enter a valid IP address' )
return get_ip_address()
for octlet in ip.split("."):
x = 0
if octlet.isdigit():
x = int(octlet)
else:
showerror( 'Error', 'Please enter a valid IP address' )
return get_ip_address()
if not ( x < 256 and x >= 0 ):
showerror( 'Error', 'Please enter a valid IP address' )
return get_ip_address()
return ip
编辑:添加了我的线程设置