- How can I change my desktop background with python?
- 12 Answers 12
- Change windows wallpaper python
- About
- Change windows wallpaper python
- About
- PyWin32: How to Set the Desktop Background on Windows
- Бесплатный аналог Wallpaper Engine на Python
- Вступление
- Используемый софт/библиотеки и т.п.
- Задумка. Цель проекта
- Первая версия. Схема работы
- Final Cut и установка
- Планы на будущее и правки проекта
- Источники. Другая информация
How can I change my desktop background with python?
How can I change my desktop background with python?
I want to do it in both Windows and Linux.
12 Answers 12
On Windows with python2.5 or higher, use ctypes to load user32.dll and call SystemParametersInfo() with SPI_SETDESKWALLPAPER action.
For Python3.5, SystemParametersInfoA doesn’t work. Use SystemParametersInfoW.
I use the following method in one of my initial projects:
The get_desktop_environment method has been posted in another thread.
‘) – user5413945 Apr 8 ’16 at 12:21
On a gnome desktop, you usually do this with gconf, either directly calling gconftool or using the gconf python module. The latter is in the link given by unutbu. The first method could be done like this.
In gnome, it is probably preferable to use the python binding of gconf directly:
Firstly, import ctypes : it gives you access to windows components such as the screensaver, wallpapers, etc.
Then call ctypes.windll.user32.SystemParametersInfoA(a,b,c,d) :
On windows, you will need some trickery with pywin32, and the windows API, on ‘linux’ the answer will depend on which desktop is running — KDE, Gnome, or something more exotic. Under KDE (and maybe Gnome) you can probably send a message using D-Bus, which you could do without including any new libraries by using the command line tool dbus-send.
The other option would be to set the desktop wallpaper to a file which you then edit / replace from python — but this will probably only result in a change when the user logs in.
There is a difference what SystemParametersInfo method to be called based on what if you are running on 64 bit or 32 bit OS. For 64 bit you have to use SystemParametersInfoW (Unicode) and for 32 bit SystemParametersInfoA (ANSI)
Alternatively: (with SystemParametersInfoA )
Arguments are:
SystemParametersInfo(SetOrGet, GetBufferSize, SetBufferOrGetBuffer, SetChange)
The path has to be absolute, so if you’re using something relative to your script, do:
path = os.path.abspath(path)
To see more stuff you can do with SystemParametersInfo , see the docs.
(near the bottom there’s an example to change the mouse speed)
P.S. There are many answers already here, but they’re leaving out the broadcasting you’re supposed to do. Sure it works without it, but it’s bad practice not to use it properly.
P.P.S And they only gave hard coded values, rather than the variables they come from.
Also note, i use 512 characters for the buffer size when getting the path, just to be more safe since paths might exceed 256. I doubt anyone will have paths as long as that though.
One more note. I’ve only tested the above examples in Python 3, but i don’t think SystemParametersInfoA needs the .encode() in Python 2. (they updated strings in Python 3 to unicode i believe) The string in SystemParametersInfoW may need converting for Python 2.
Change windows wallpaper python
Python Wallpaper Changer
This script makes it easy to change desktop wallpaper to a random file in a given folder. It also provides support for grabbing new wallpaper images from the Microsoft Windows lock screen wallpapers.
- Install the Pillow python package: pip install Pillow
- Place this script in a desired location.
- In that same location, create a folder in which to store your wallpaper images, noting the path to this target location.
- Issue the following command, passing the target location above in as the parameter, to create a new configuration file: python paperchanger.py —create
Simply issue python paperchanger.py to change the desktop wallpaper to a random image.
The following command line options are available:
The first positional argument is the name of the configuration file to read. If not specified, the default filename paper_changer.cfg will be read in.
—create
Create a new configuration file, using the specified target folder as the repository of files.
—lockbrowse
Open the Microsoft Windows lock screen image storage location in a Windows Explorer window.
—lockscan
Scan the Microsoft Windows lock screen image storage location for new images. If any new images are found, the location is opened in a Windows Explorer window for you to preview the images.
—locksync
Move the images found by the —lockscan option to the file repository, adding them to the available image pool.
—pool
Show the current random selection pool.
—sync
Synchronize the configuration file with the image pool, adding any new files that were found, and removing any files that are no longer present.
About
Python script to change Windows desktop wallpaper
Change windows wallpaper python
Python Wallpaper Changer
This script makes it easy to change desktop wallpaper to a random file in a given folder. It also provides support for grabbing new wallpaper images from the Microsoft Windows lock screen wallpapers.
- Install the Pillow python package: pip install Pillow
- Place this script in a desired location.
- In that same location, create a folder in which to store your wallpaper images, noting the path to this target location.
- Issue the following command, passing the target location above in as the parameter, to create a new configuration file: python paperchanger.py —create
Simply issue python paperchanger.py to change the desktop wallpaper to a random image.
The following command line options are available:
The first positional argument is the name of the configuration file to read. If not specified, the default filename paper_changer.cfg will be read in.
—create
Create a new configuration file, using the specified target folder as the repository of files.
—lockbrowse
Open the Microsoft Windows lock screen image storage location in a Windows Explorer window.
—lockscan
Scan the Microsoft Windows lock screen image storage location for new images. If any new images are found, the location is opened in a Windows Explorer window for you to preview the images.
—locksync
Move the images found by the —lockscan option to the file repository, adding them to the available image pool.
—pool
Show the current random selection pool.
—sync
Synchronize the configuration file with the image pool, adding any new files that were found, and removing any files that are no longer present.
About
Python script to change Windows desktop wallpaper
PyWin32: How to Set the Desktop Background on Windows
Back in my system administrator days, we were thinking about setting the user’s Window desktop background to a specific image on login. Since I was in charge of the login scripts, which were written in Python, I decided to do some research to find out if there was a way to do it. We will look at two different approaches to this task in this article. The code in this article was tested using Python 2.7.8 and PyWin32 219 on Windows 7.
For the first approach, you will need to go download a copy of PyWin32 and install it. Now let’s look at the code:
In this example, we use a sample image that Microsoft provides with Windows. In the code above, we eidt a Windows Registry key. You could do the first 3 lines using Python’s own _winreg module if you wanted to. The last line tells Windows to set the desktop to the image we provided.
Now let’s look at another approach that utilizes the ctypes module and PyWin32.
In this piece of code, we create a buffer object that we then pass to basically the same command as we did in the previous example, namely SystemParametersInfoA. You will note that we don’t need to edit the registry in this latter case. If you check out the links listed in the sample code, you will note that some users found that Windows XP only allowed bitmaps to be set as the desktop background. I tested with a JPEG on Windows 7 and it worked fine for me.
Now you can create your own script that changes the desktop’s background at random intervals! Or maybe you’ll just use this knowledge in your own system administration duties. Have fun!
Бесплатный аналог Wallpaper Engine на Python
Вступление
Приветствую всех, кто решил поинтересоваться данной темой. В этом посте я хочу поделиться с Вами бесплатным и кривоногим(пусть и рабочим) аналогом Wallpaper Engine из Steam, написанным на одном Python с использованием некоторых сторонних библиотек и модулей.
Почему он носит такой статус, разберемся по ходу повествования. Перед тем, как я начну, отмечу, что до этого момента не занимался разработкой десктопных приложений, да и вообще почти забыл что такое код. Буквально за 20-30 дней подтянулся с уровня плинтуса и решил «позабавиться». Не буду долго разглагольствовать. Приступим к сути.
Используемый софт/библиотеки и т.п.
Задумка. Цель проекта
На самом деле все очень просто. Платить не хочешь — делай сам (да, для студента 100 рублей это деньги). Целью является апгрейд навыков в сфере Python и программирования в целом. И да, есть еще субъективные причины, о которых лучше помолчать (Сдвинуть с рынка Wallpaper Engine и захватить Млечный путь).
Первая версия. Схема работы
Для работы приложения я использовал библиотеку Weebp и видеоплеер MPV (Это рекомендовано автором данного Open-Source проекта). Смысл прост и понятен: Weebp создает «окно» и делает его неактивным и не контактным. Далее «вешается» плеер MPV и запускается видео-обои. Не смотря на эту структуру и кривой код, программа показывает более чем хорошую производительность.
Надо придумать название проекта, не ноунеймом же быть. Моя фантазия наколдовала для этого детища имя, не ушедшее дальше Wallpaper Engine.
Перед Вами Wallpaper Layout версии 1.0.
Да, версия 1.0 являлась консольной. Я думаю, это неудивительно.
Далее были правки. Много правок. Все это привело к версии 1.1 и данному виду
На тот момент Wallpaper Layout имел 2 предустановленных пресета, которые мог выбрать юзер.
Далее ситуация улучшилась и уже в версии 1.2 появился более привлекательный и лаконичный интерфейс, а также возможность загружать свои пресеты.
На данный момент все детали GUI носят англоязычные обозначения.
Final Cut и установка
С использованием новой графической оболочки пришли некоторые недоработки и жуки. На фото один из них — жук пробрался в шрифты и все погрыз.
Все исправилось одной строчкой в файле GUI
После всех фиксов появилась стабильная на данный момент версия 1.2.2, которую Вы можете загрузить и опробовать. Все о данной программе я Вам рассказал, поэтому бояться нечего. Процесс установки самый простой.
Создавайте ярлык и пользуйтесь.
Планы на будущее и правки проекта
Ничто в этом мире не может быть идеальным (кроме читателей, конечно же). Любое творчество и процесс создания требуют улучшений и исправлений. Поэтому поделюсь с Вами о планах, связанных с разработкой Wallpaper Layout
- Жук погрыз иконку приложения в левом верхнем углу при запуске. Будет исправлено
- Добавится возможность удобной загрузки пользовательских пресетов через модальное окно и исчезнут форматы файлов в выпадающем списке
- Исчезнут мелькающие консоли при установке обоев
- Изменится внешний вид приложения
- Реализуется сохранение и автозапуск Ваших обоев вместе со стартом Windows
- И многое другое, до чего дойдут руки
Если у Вас есть пожелания, вопросы или рекомендации, то я с радостью все выслушаю и приму к сведению.
Спасибо за внимание.
Источники. Другая информация
Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.