如何使用Python脚本更改壁纸?

我想用一个小的Python脚本在Ubuntu 11.10(使用Unity)中更改我的壁纸。 我发现可以通过/desktop/gnome/background/picture_filenamegconf-editor进行更改。 使用python-gconf ,我可以更改必要的值。

显然,gconf字符串不会被读出。 如果我更改它(通过脚本或通过gconf-editor ),壁纸仍然保留,并在“更改壁纸”菜单中显示旧壁纸。

我如何通过Python脚本更改Unity的壁纸?

以下代码确实有效。

 #!/usr/bin/python # -*- coding: utf-8 -*- from gi.repository import Gio class BackgroundChanger(): SCHEMA = 'org.gnome.desktop.background' KEY = 'picture-uri' def change_background(self, filename): gsettings = Gio.Settings.new(self.SCHEMA) print(gsettings.get_string(self.KEY)) print(gsettings.set_string(self.KEY, "file://" + filename)) gsettings.apply() print(gsettings.get_string(self.KEY)) if __name__ == "__main__": BackgroundChanger().change_background("/home/user/existing.jpg") 

不幸的是,gconf本身并没有真正清理干净。 这是旧设置。 使用11.10中的GNOME3和Unity,桌面背景设置现在存储在dconf中。 使用dconf-editor您可以在org.gnome.desktop.background.picture-uri找到该设置。

这是一个快速示例,展示了如何使用python,GTK和GObject Introspection更改背景:

 #! /usr/bin/python from gi.repository import Gtk, Gio class BackgroundChanger(Gtk.Window): SCHEMA = 'org.gnome.desktop.background' KEY = 'picture-uri' def __init__(self): Gtk.Window.__init__(self, title="Background Changer") box = Gtk.Box(spacing=6) self.add(box) button1 = Gtk.Button("Set Background Image") button1.connect("clicked", self.on_file_clicked) box.add(button1) def on_file_clicked(self, widget): gsettings = Gio.Settings.new(self.SCHEMA) dialog = Gtk.FileChooserDialog("Please choose a file", self, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) self.add_filters(dialog) response = dialog.run() if response == Gtk.ResponseType.OK: background = dialog.get_filename() gsettings.set_string(self.KEY, "file://" + background) elif response == Gtk.ResponseType.CANCEL: pass dialog.destroy() def add_filters(self, dialog): filter_image = Gtk.FileFilter() filter_image.set_name("Image files") filter_image.add_mime_type("image/*") dialog.add_filter(filter_image) filter_any = Gtk.FileFilter() filter_any.set_name("Any files") filter_any.add_pattern("*") dialog.add_filter(filter_any) win = BackgroundChanger() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() 

以下是关于GSettings和Python的两篇有用的博客文章:

http://www.micahcarrick.com/gsettings-python-gnome-3.html

http://www.lucidelectricdreams.com/2011/06/reading-and-writing-gsettings-from.html

干得好

 #! /usr/bin/python import os os.system("gsettings set org.gnome.desktop.background picture-uri file:///home/user/Pictures/wallpaper/Stairslwallpaper.png") 

也许不是最好但最简单的解决方案:

 import commands command = 'gsettings set org.gnome.desktop.background picture-uri "file:///home/user/test.png"' status, output = commands.getstatusoutput(command)