我每次登录时都可以自动更改桌面壁纸

我已经学会了如何通过终端更改背景但是每次登录时我都能让终端更改为不同的背景吗?

介绍

下面的脚本将目录作为参数(最好只包含图像),从其内容中选择随机项,并将项目设置为壁纸。 它旨在从用户的登录开始,虽然也可以单独使用。

设置和使用

首先,脚本必须存储在系统的某个位置。 最好将它放在~/bin目录中。 如果您的主目录中没有bin目录,则只需创建一个。

接下来,确保脚本具有可执行权限。 您可以使用chmod +x ~/bin/set_random_wallpaper.py或通过右键单击文件并在“属性”菜单的“权限”选项卡中选中“ Allow executing file as program来以GUI方式Allow executing file as program

该脚本需要一个目录作为参数。 最好,你应该给它完整的路径。 例如:

 set_random_wallpaper.py /home/JohnDoe/Pictures/wallpapers/ 

如果你是通过命令行进行的,那么你可以给出相对路径, Pictures/wallpapers/ ,但是为了将其设置为在自动登录时运行,请使用完整路径。

要在每次登录时运行文件,请打开“启动应用程序”程序,然后单击“添加”按钮。 使用命令和文件夹的完整路径:

 /home/JohnDoe/bin/set_random_wallpaper.py /home/JohnDoe/Pictures/wallpapers/ 

而已 !

脚本来源

该脚本也可以在GitHub上找到 :

 #!/usr/bin/env python3 """ Author: Serg Kolo , <1047481448@qq.com> Date: December, 21,2016 Purpose: Sets random wallpaper from a given directory Written for: https://askubuntu.com/q/851705/295286 """ from gi.repository import Gio import os,sys,random def gsettings_set(schema, path, key, value): """Set value of gsettings schema""" if path is None: gsettings = Gio.Settings.new(schema) else: gsettings = Gio.Settings.new_with_path(schema, path) if isinstance(value, list): return gsettings.set_strv(key, value) if isinstance(value, int): return gsettings.set_int(key, value) if isinstance(value,str): return gsettings.set_string(key,value) def error_and_exit(message): sys.stderr.write(message + "\n") sys.exit(1) def select_random_uri(dir_path): selection = random.choice(os.listdir(dir_path)) selection_path = os.path.join(dir_path,selection) while not os.path.isfile(selection_path): selection = random.choice(os.listdir(dir_path)) selection_path = os.path.join(dir_path,selection) selection_uri = Gio.File.new_for_path(selection_path).get_uri() return selection_uri def main(): """ Program entry point""" if len(sys.argv) != 2: error_and_exit('>>> Script requires path to a directory as single argument') if not os.path.isdir(sys.argv[1]): error_and_exit('>>> Argument is not a directory') img_dir = os.path.abspath(sys.argv[1]) uri = select_random_uri(img_dir) try: gsettings_set('org.gnome.desktop.background',None,'picture-uri',uri) except Exception as ex: error_and_exit(ex.repr()) if __name__ == '__main__': main() 

技术细节和操作理论

脚本本身以非常简单的方式工作,但我用自己的一些函数加以调整。 main函数检查是否存在参数以及该参数是否为目录 – 否则退出。 如果一切正常,我们继续获取目录的绝对路径,并将其提供给set_random_uri()函数。

您可能知道也可能不知道,壁纸是在dconf数据库中设置的,可以使用gsettings命令访问和更改。 简单的命令行方式是

 gsettings set org.gnome.desktop.background picture-uri file:///home/JohnDoe/Pictures/cool_wallpaper.jpg 

file://... part是文件的URI(实际上是文件的编码路径,如果您的系统使用的语言环境不同于英语,则非常有用)。 首先,我们需要选择随机文件并获取其URI。 这很简单 – 我们使用random.choice()从list和os.listdir()以获取目录中的项目列表。 如果我们的随机选择恰好是目录而不是文件怎么办? 那么,这就是select_random_uri中的while循环。 一旦我们对选择感到满意,我们就会得到它

那么,从gsettings set命令发生的事情几乎是一样的,但是我使用自定义编写的gsettings_set()函数,避免了调用外部命令的需要,并且它对其他项目很有用,例如启动器列表指示器 。

而已 ! 玩得开心编码,负责任地享受Ubuntu!

额外资源

  • 此类脚本的Bash版本之前已经实现,请参阅: https : //askubuntu.com/a/744470/295286