有人能告诉我以下程序有什么问题吗?我在引用http://wikistack.com/use-css-gtk/网站作为示例。但是当我运行程序时,我得到错误 style.css:1:0预期有效的选择器
#include <gtk/gtk.h>
#include <string.h> /* for css */
#include <iostream>
int main (int argc, char *argv[])
{
GtkWidget *window;
/*---- CSS ------------------*/
GtkCssProvider *provider;
GdkDisplay *display;
GdkScreen *screen;
/*---------------------------*/
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_widget_set_size_request(window, 400, 300);
gtk_window_set_title(GTK_WINDOW(window), "wikistack");
g_signal_connect(G_OBJECT (window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
/* ----------------- CSS -------------------------------------------------*/
provider = gtk_css_provider_new ();
display = gdk_display_get_default ();
screen = gdk_display_get_default_screen (display);
gtk_style_context_add_provider_for_screen (screen, GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
const gchar* home = "D:\\style.css";
GError *error = 0;
gtk_css_provider_load_from_file(provider, g_file_new_for_path(home), &error);
std::cout << error->message;
g_object_unref (provider);
/* -----------------------------------------------------------------------*/
gtk_widget_show_all(window);
gtk_main ();
return 0;
}
并且style.css文件包含下面的样式信息。
/* Theme labels that are descendants of a window */
GtkWindow GtkLabel {
background-color: #898989;
}
答案 0 :(得分:2)
'\ xef \ xbb \ xbf'是Unicode零宽度无中断空格U + FEFF的UTF8编码版本。它通常用作unicode文本开头的字节顺序标记
示例:
# when you read from a byte string
b'window {\n opacity: 1;\n ...
# when you read from a .css file
b'\xef\xbb\xbfwindow {\n ...
因此,gtk_css_provider_load_from_file函数会引发错误。
“ utf-8-sig”编码明确要求在文件开头写入此BOM。 要在Python 2中读取文件时自动对其进行处理,可以使用编解码器模块:
示例:
css_provider = Gtk.CssProvider()
with open("main.css", "rb") as css_file:
css_file = EncodedFile(css_file, 'utf-8', 'utf-8-sig')
css_provider.load_from_data(css_file.read())
EncodedFile通过在utf8-sig中解码原始文件对象来包装原始文件对象,实际上跳过BOM并在没有BOM的情况下在utf8中对其重新编码。
答案是从此anwser中获取并修改的。