【问题标题】:Using C application with a Python GUI使用带有 Python GUI 的 C 应用程序
【发布时间】:2017-09-06 19:36:51
【问题描述】:

我用 C 语言构建了一个简单的应用程序,我希望它有一个 GUI。我希望 GUI 在 Python 中(因为它更容易),但我不确定如何让用户响应从 Python 到 C,或者即使有可能。

我想要的是打开一个 tkinter 窗口,询问用户是否要播放文件,如果他们单击是,则播放文件。

这是我的 C 脚本 (main_file.c):

#include <window.h>
#include <stdio.h>
#include <conio.h>
#include <python.h>

int Play()
{
    PlaySound("Sound1.wav", NULL, SND_ASYNC);

    while(1)
    {
        continue;
    }
    return 0;
}

int main()
{
    char filename[] = "GUI.py";
    FILE* fp;

    Py_Initialize();

    fp = _Py_fopen(filename, "r");
    PyRun_SimpleFile(fp, filename);

    Py_Finalize();
    return 0;
}

还有我的 GUI.py 文件:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.option()

    def option(self):
        self.opt = tk.Button(self)
        self.opt["text"] = "Do You Want To Play File"
        self.opt["command"] = self.play
        self.opt.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy)
        self.quit.pack(side="bottom")

    def play(self):
        #This part needs to tell C to use Play() function

root = tk.Tk()
app = App(master=root)
app.mainloop()

问题是我不知道如何让 Python 告诉 C 使用 Play() 函数。

我在 Windows 10 上使用 MinGW。

【问题讨论】:

  • 为什么不全部使用 Python?其余的是 C 基础知识,可以通过不同的方式实现。那么,您在初学者的 C 书籍和 Python 文档中没有发现的具体问题是什么?
  • 您想要的是为 C 函数创建 python 包装器。您可以在此处阅读有关包装器的信息:intermediate-and-advanced-software-carpentry.readthedocs.io/en/…
  • @Mariusz 我去看看。
  • @Olaf 看看 GUI.py 中的第 19 行有我的 具体问题 或阅读我的问题的倒数第二行。
  • @Simon:阅读How to Ask 并遵循建议。我不会计算行数等。正如我已经写过的,调用 C 程序只是为了播放声音是没有任何意义的。你让你的生活变得比必要的困难得多,你的代码也更难维护。

标签: python c python-3.x user-interface python-c-api


【解决方案1】:

编译 main_file.c 并将其作为可执行文件运行:os.system(r'PATH_TO_EXE')

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 2011-08-02
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2023-03-12
    相关资源
    最近更新 更多