嵌入在C ++线程中的Python Tkinter

时间:2018-12-25 17:45:29

标签: python c++ tkinter

我有一个C ++项目,我想向其中添加嵌入式python解释器。我实际上已经通过简单的脚本成功完成了此任务,但是当我尝试使用Tkinter进行操作时,它将打开一个空白窗口,并且从不绘制任何框架或内容。我很确定这与GIL有关,但是未能找到可以正常工作的呼叫组合。我已经制作了一个简单的示例,通过C ++文件和已编译程序运行的python脚本对此进行了说明。如果取消注释MyPythonThread行并注释掉在线程中运行它的两个行,则它将按预期工作。

无论我Py_Initialize来自哪个线程,似乎python都知道它是否在“主”线程中。

其他信息:我正在Mac OS X 10.13.6上进行测试,并安装了自制软件python 2.7.15。

//
// Compile with: g++ `python-config --cflags --libs` --std=c++11 test.cc
//

#include <cstdio>
#include <Python.h>
#include <thread>

void MyPythonThread(void)
{
    PyEval_InitThreads();
    Py_Initialize();

    const char *fname = "test.py";
    PySys_SetArgv( 1, (char**)&fname );
    auto fil = std::fopen(fname, "r");
    PyRun_AnyFileEx( fil, NULL, 1 );

}

int main(int narg, char * argv[])
{

    // This works
//  MyPythonThread();

    // This does not
    std::thread thr(MyPythonThread);
    thr.join();

    return 0;
}

这是它运行的python脚本:

#!/usr/bin/env python

import Tkinter as tk

window = tk.Tk()
top_frame = tk.Frame(window).pack()
b1 = tk.Button(top_frame, text = "Button").pack()

window.mainloop()

0 个答案:

没有答案