你不能使用没有 gtk 主循环的小部件。
好吧,看来我错了。我真诚的道歉!我曾实际上尝试过这样做,而结论正是我所描述的。但是最近几天这个问题一直困扰着我,所以我做了一些更多的挖掘和实验,并提出了以下程序:
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 8 -*- */
/*
* main.c
* Copyright (C) 2015 John Coppens <john@jcoppens.com>
*
* standalone_filechooser is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* standalone_filechooser is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <gtk/gtk.h>
GtkWidget *
create_filechooser_dialog(char *init_path, GtkFileChooserAction action)
{
GtkWidget *wdg = NULL;
switch (action) {
case GTK_FILE_CHOOSER_ACTION_SAVE:
wdg = gtk_file_chooser_dialog_new("Save file", NULL, action,
"Cancel", GTK_RESPONSE_CANCEL,
"Save", GTK_RESPONSE_OK,
NULL);
break;
case GTK_FILE_CHOOSER_ACTION_OPEN:
wdg = gtk_file_chooser_dialog_new("Open file", NULL, action,
"Cancel", GTK_RESPONSE_CANCEL,
"Open", GTK_RESPONSE_OK,
NULL);
break;
case GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER:
case GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER:
break;
}
return wdg;
}
int main(int argc, char *argv[])
{
GtkWidget *wdg;
char *fname = "";
if (argc == 2)
fname = argv[1];
gtk_init(&argc, &argv);
wdg = create_filechooser_dialog(fname, GTK_FILE_CHOOSER_ACTION_OPEN);
if (gtk_dialog_run(GTK_DIALOG(wdg)) == GTK_RESPONSE_OK) {
printf("%s", gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(wdg)));
return(0);
} else
return (1);
}
您可以从另一个程序(甚至终端)调用对话框
standalone_filechooser [default file]
如果提供了default file(没有括号),它将被选中。如果选择了一个文件,它将打印在stdout,否则程序将返回error=1
在没有主窗口的情况下运行小部件仍然存在一个小问题,这会导致将消息发送到stderr:GtkDialog mapped without a transient parent. This is discouraged。我认为这确实是一个错误(在更新的 gtk3 版本中是 it might be solved)。由于消息是发送到stderr,所以应该不会影响正常使用。