473,761 Members | 5,848 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on Embedding Python GUI call from C code.

2 New Member
Hello,

I am trying to actually call a GUI from my C++ code which would have buttons and therefore can call functions from C++ again, ie extend the C++ code also.

I am faced with a peculiar problem. I actually tried out an embedding code (downloaded from the net) which actually calls any function which has a text display but when I try to call any code which opens cleanly in python prompt it crashes.

To make matters more concrete let me paste the code of C++ to Python call.

#include <Python.h>

int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;

if (argc < 3)
{
printf("Usage: exe_name python_source function_name\n ");
return 1;
}

// Initialize the Python Interpreter
Py_Initialize() ;

PyRun_SimpleStr ing("import sys");
PyRun_SimpleStr ing("sys.path.a ppend(\"./ui\")");
// Build the name object
pName = PyString_FromSt ring(argv[1]);

// Load the module object
pModule = PyImport_Import (pName);

// pDict is a borrowed reference
pDict = PyModule_GetDic t(pModule);

// pFunc is also a borrowed reference
pFunc = PyDict_GetItemS tring(pDict, argv[2]);

if (PyCallable_Che ck(pFunc))
{
PyObject_CallOb ject(pFunc, NULL);
} else
{
PyErr_Print();
}

// Clean up
Py_DECREF(pModu le);
Py_DECREF(pName );

// Finish the Python Interpreter
Py_Finalize();

return 0;
}


Now my understanding is that when this code is run, for any python module it should be able to call the function. I actually tried out the multiply function available and it gives correct results.

But if I do <program> Tkinter _test() , instead of a Tk window popping up the program crashes.

I would be very thankful if anyone can suggest where can I go wrong in this since I am a total newbie in GUI and Python.

Regards
Sumanta
Jun 24 '08 #1
2 2320
kaarthikeyapreyan
107 New Member
I am faced with a peculiar problem. I actually tried out an embedding code (downloaded from the net) which actually calls any function which has a text display but when I try to call any code which opens cleanly in python prompt it crashes.
What is your actual error ?
where does your program crash ? is the error during your c code compilation or during the execution of the c code after your executable is created ,and could you brief me more on what is inside this.
Expand|Select|Wrap|Line Numbers
  1. PyRun_SimpleString("sys.path.append(\"./ui\")");
Jun 25 '08 #2
bappai
2 New Member
What is your actual error ?
where does your program crash ? is the error during your c code compilation or during the execution of the c code after your executable is created ,and could you brief me more on what is inside this.
Expand|Select|Wrap|Line Numbers
  1. PyRun_SimpleString("sys.path.append(\"./ui\")");

Hello,

First of all I apologize for the late reply. I am totally new to the forum and so did not have an idea that a mail did not go to the userid if somebody replied.

Anyway, to answer the questions

1. the failure is never in the compilation part. I had downloaded cygwin (latest version) compiled Python 2.5.2 on that linked my program correctly and the problem arose during runtime when it crashed.

2. For the question as to what is there in CODE]PyRun_SimpleStr ing("sys.path.a ppend(\"./ui\")");[/code][/quote] , there is a small python script which I am pasting for your reference.

#!/usr/bin/python
# -*- coding: iso-8859-1 -*-

import Tkinter

class simpleapp_tk(Tk inter.Tk):
def __init__(self,p arent):
print "Second.... .\n"
Tkinter.Tk.__in it__(self,paren t)
print "Thirde.... .\n"
self.parent = parent
#self.initializ e()

def hello():
print "hello!"
def initialize(self ):
self.grid()

menubar = Tkinter.Menu(se lf)
#menubar.add_co mmand(label="Su manta Test", command=self.he llo)
# create a pulldown menu, and add it to the menu bar
filemenu = Tkinter.Menu(me nubar, tearoff=0)
filemenu.add_co mmand(label="Op en", command=self.he llo)
filemenu.add_co mmand(label="Sa ve", command=self.he llo)
filemenu.add_se parator()
filemenu.add_co mmand(label="Ex it", command=self.qu it)
menubar.add_cas cade(label="Fil e", menu=filemenu)

# create more pulldown menus
editmenu = Tkinter.Menu(me nubar, tearoff=0)
editmenu.add_co mmand(label="Cu t", command=self.he llo)
editmenu.add_co mmand(label="Co py", command=self.he llo)
editmenu.add_co mmand(label="Pa ste", command=self.he llo)
menubar.add_cas cade(label="Edi t", menu=editmenu)

helpmenu = Tkinter.Menu(me nubar, tearoff=0)
helpmenu.add_co mmand(label="Ab out", command=self.he llo)
menubar.add_cas cade(label="Hel p", menu=helpmenu)

# display the menu
self.config(men u=menubar)

#self.entryVari able = Tkinter.StringV ar()
#self.entry = Tkinter.Entry(s elf,textvariabl e=self.entryVar iable)
#self.entry.gri d(column=0,row= 0,sticky='EW')
#self.entry.bin d("<Return>", self.OnPressEnt er)
#self.entryVari able.set(u"Ente r text here.")

#button = Tkinter.Button( self,text=u"Cli ck me !",
# command=self.On ButtonClick)
#button.grid(co lumn=1,row=0)

#self.labelVari able = Tkinter.StringV ar()
#label = Tkinter.Label(s elf,textvariabl e=self.labelVar iable,
# anchor="w",fg=" white",bg="blue ")
#label.grid(col umn=0,row=1,col umnspan=2,stick y='EW')
#self.labelVari able.set(u"Hell o !")

#self.grid_colu mnconfigure(0,w eight=1)
self.resizable( True,False)
self.update()
self.geometry(s elf.geometry())

self.canvas=Tki nter.Canvas(sel f, bg="white", width=400, height=400,
bd=0, highlightthickn ess=0)
self.canvas.pac k()

#self.entry.foc us_set()
#self.entry.sel ection_range(0, Tkinter.END)

def OnButtonClick(s elf):
self.labelVaria ble.set( self.entryVaria ble.get()+" (You clicked the button)" )
self.entry.focu s_set()
self.entry.sele ction_range(0, Tkinter.END)

def OnPressEnter(se lf,event):
self.labelVaria ble.set( self.entryVaria ble.get()+" (You pressed ENTER)" )
self.entry.focu s_set()
self.entry.sele ction_range(0, Tkinter.END)

def simple_fn():
print "Hello and Welcome"
app = simpleapp_tk(No ne)

# The problem comes when the simpleapp_tk call is made and inside
#there when Tkinter is called.
# app.title('my app')
# app.mainloop()


#if __name__ == "__main__":
# app = simpleapp_tk(No ne)
# app.title('my application')
# app.mainloop()
Jun 27 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
1835
by: Tommy Nordgren | last post by:
I want to write an application that embeds and extends (at least) the Python and Perl interpreters. Now i want to find as much as possible about the Python tools used for extending and embedding Python. To be more specific: My app should: 1. Parse an input file. 2. Call a script in some scripting language, to generate an output file, for example in C++. For task 2 I need to call an embedded interpreter, and also provide call backs from...
4
2150
by: Hoop | last post by:
Hi, I have been working in getting Boost.Python running on my PC, seems to work now. I have what I believe is somewhat of basic question here. I am starting on an application that will developed in VS2005, probably using C++/CLI. I want to be able to exchange data in between Python and C++. The user when running the C++ app will be able to call a python script, set some values, that will then be communicated to running application, it
1
1344
by: Thomas Troeger | last post by:
Dear all, I've successfully embedded the Python interpreter into a set of C/C++ application programs that use a larger library project with information from http://docs.python.org/api/api.html and http://docs.python.org/ext/ext.html. Now I want to wrap classes and functions from the associated libraries so that I can write new applications completely in Python, but I'm not entirely sure how to start because I have some problems...
0
2114
by: Tim Spens | last post by:
--- On Fri, 6/27/08, Tim Spens <t_spens@yahoo.comwrote: I think I know where the problem is but I'm unsure how to fix it. When I call Register_Handler(...) from python via callback.setHandler1(callback1) this only seems to affect pythons ability to trigger an "event" in c. PyObject *Handler is always NULL even after I call Register_Handler(...). I thought there was some magic here that was assigning the pointer *Handler to my python...
0
9336
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10111
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9902
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9765
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8770
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6603
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3866
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.