# encoding: utf-8 import urllib.request, sys # page = urllib.request.urlopen('http://tieba.baidu.com/p/1753935195') # print(page) # htmlcode = page.read() # # pageFile = open('E:\\text_lj\\pagecode.txt','w') # pageFile.write(htmlcode.decode("utf-8")) # pageFile.close() import win32api import win32con import win32gui key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 2:拉伸适应桌面;0:桌面居中 win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, 'D:\\wallpaper\\img7.jpg', 1 + 2) # 关闭打开的键 win32api.RegCloseKey(key)
def updateBGImage(self): img = Image.open(self.localFileName) img.save(self.localBMPFileName) os.remove(self.localFileName) win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, self.localBMPFileName, 1 + 2)
def setWallpaper(p): win32gui.SystemParametersInfo(20, p, 0)
## Set actions all take an unsigned int in pvParam "SPI_GETMOUSESPEED", "SPI_GETACTIVEWNDTRKTIMEOUT", "SPI_GETCARETWIDTH", "SPI_GETFOREGROUNDFLASHCOUNT", "SPI_GETFOREGROUNDLOCKTIMEOUT", ## Set actions all take an unsigned int in uiParam "SPI_GETWHEELSCROLLLINES", "SPI_GETKEYBOARDDELAY", "SPI_GETKEYBOARDSPEED", "SPI_GETMOUSEHOVERHEIGHT", "SPI_GETMOUSEHOVERWIDTH", "SPI_GETMOUSEHOVERTIME", "SPI_GETSCREENSAVETIMEOUT", "SPI_GETMENUSHOWDELAY", "SPI_GETLOWPOWERTIMEOUT", "SPI_GETPOWEROFFTIMEOUT", "SPI_GETBORDER", ## below are winxp only: "SPI_GETFONTSMOOTHINGCONTRAST", "SPI_GETFONTSMOOTHINGTYPE", "SPI_GETFOCUSBORDERHEIGHT", "SPI_GETFOCUSBORDERWIDTH", "SPI_GETMOUSECLICKLOCKTIME"): print(pname) cget=getattr(win32con,pname) cset=getattr(win32con,pname.replace('_GET','_SET')) orig_value=win32gui.SystemParametersInfo(cget) print('\toriginal setting:',orig_value) win32gui.SystemParametersInfo(cset, orig_value+1) new_value=win32gui.SystemParametersInfo(cget) print('\tnew value:',new_value) # On Vista, some of these values seem to be ignored. So only "fail" if # the new value isn't what we set or the original if new_value!=orig_value+1: assert new_value == orig_value print("Strange - setting %s seems to have been ignored" % (pname,)) win32gui.SystemParametersInfo(cset, orig_value) assert win32gui.SystemParametersInfo(cget)==orig_value # these take a boolean value in pvParam
def setWallPaperFromBmp(bmp): key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, 'Control Panel\\Desktop', 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, 'WallpaperStyle', 0, win32con.REG_SZ,'0') win32api.RegSetValueEx(key, 'TileWallpaper', 0, win32con.REG_SZ, '0') win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp, 1+2)
def SystemParametersInfo(): win32gui.SystemParametersInfo()
def set_wallpaper(img_path): win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, 1 + 2) time.sleep(3) os.remove(img_path)
#coding:utf-8 import win32gui,win32con,win32api import Image import time start = time.time() img = Image.open('test.jpg') img.save('test.bmp','BMP') # Update WallPaper print('正在设置图片:%s为桌面壁纸...' % 'test.bmp') key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop",0,win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2") #2拉伸适应桌面,0桌面居中 win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, 'test.bmp', 1+2) print('成功应用图片:%s为桌面壁纸' % 'test.bmp') end = time.time() print(end-start)
resultId = str(result['id']) resultURL = result['urls']['regular'] # Download Images print(u'正在为您下载图片:%s...' % resultId) basePath = sys.path[0] if (os.path.isfile(basePath)): basePath = os.path.dirname(basePath) baseFolder = basePath + '\\Download\\' if (not path.exists(baseFolder)): os.makedirs(baseFolder) jpgFile = baseFolder + resultId + '.jpg' bmpFile = baseFolder + resultId + '.bmp' response = requests.get(resultURL) with open(jpgFile, 'wb') as file: file.write(response.content) img = Image.open(jpgFile) img.save(bmpFile, 'BMP') os.remove(jpgFile) # Update WallPaper print(u'正在设置图片:%s为桌面壁纸...' % resultId) key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2") #2拉伸适应桌面,0桌面居中 win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmpFile, 1 + 2) print(u'成功应用图片:%s为桌面壁纸' % resultId)
def setWallpaper(path): key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, 1 + 2)
def setWallpaperFromBmp(self): win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, os.path.realpath(self.localBMPFileName), 1 + 2)
def is_screensaver_running(self): return win32gui.SystemParametersInfo( win32con.SPI_GETSCREENSAVERRUNNING)
REQUIRED_CLASSES_PROGRAMS = { 'TkTopLevel': 'py -3 D:\WORK\sbis3\script\\test\\not_decided.pyw', # Классы\путь к запускаемому файлу окон, по ним ищем hwnd окна\запускаем окно. # 'Chrome': '"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://dev-ci//plugin/jenkinswalldisplay/walldisplay.html?viewName=+++++++++++Platforma&jenkinsUrl=http%3A%2F%2Fdev-ci%2F', 'Mozilla': '"C:\Program Files (x86)\Mozilla Firefox\\firefox.exe" http://dev-ci//plugin/jenkinswalldisplay/walldisplay.html?viewName=+++++++++++Platforma&jenkinsUrl=http%3A%2F%2Fdev-ci%2F', 'BuildScreen': 'D:\download\BuildScreen\BuildScreen.exe' } WINDOW_IS_CLOSED = { cls: True for cls in REQUIRED_CLASSES_PROGRAMS } # Генерация флагов существования окон требуемых окон. TIMEOUT = 5 pid = os.getpid() win32gui.SystemParametersInfo(win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0) # Опция, позволяющая работать методу # SetForegroundWindow корректно, # если фокус с окна сбился. Popen('py -3 D:\WORK\sbis3\script\\test\\view_time_date.py') time.sleep(0.5) # Без паузы сценарий не успевает полностью запуститься. CLOCK_HWND = win32gui.FindWindow(0, 'Clock') while True: HWND_CLASS_LIST = [ ] # Список hwnd(A handle to a window)\class окон, по которым хотим переключаться. # Проходим по всем окнам. # Заполняем словарь HWND_CLASS_LIST родительскими идентификаторами окон. # Выставляем окнам флаг существования. win32gui.EnumWindows(write_parent_hwnd, 0) HWND_CLASS_LIST.sort(
def setWallPaper(imagepath='download/cache_wallpaper.png'): keyex = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(keyex, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(keyex, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, imagepath, win32con.SPIF_SENDWININICHANGE)
def set_wallpaper_permanent(picPath, SHOW_DEBUG): if SHOW_DEBUG: print('Setting the wallpaper') win32gui.SystemParametersInfo(0x0014, picPath, 1 + 2)
def set_desktop_windows(imagepath): k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 2拉伸适应桌面,0桌面居中 win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, imagepath, 1 + 2)
if self.l2_window.mp_line: self.mp_line = self.canvas.create_line(self.l2_window.mp_line, width=2, fill='white') if self.l2_window.target_hp_line: self.target_hp_line = self.canvas.create_line( self.l2_window.target_hp_line, width=2, fill='white') try: self.party_hp_lines = [] self.party_mp_lines = [] for i, php_line in enumerate(self.l2_window.party_hp_lines): self.party_hp_lines.append( self.canvas.create_line(php_line, width=2, fill='white')) self.party_mp_lines.append( self.canvas.create_line(self.l2_window.party_mp_lines[i], width=2, fill='white')) except: pass import win32gui, win32con if __name__ == '__main__': win32gui.SystemParametersInfo( win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0, win32con.SPIF_SENDWININICHANGE | win32con.SPIF_UPDATEINIFILE) root = tk.Tk() app = L2BotApp(root) root.mainloop()
import requests, json, os import win32gui, win32api, win32con urlbase = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&pid=hp' r = requests.get(urlbase) r = r.json() url = 'https://cn.bing.com' + r[u'images'][0][u'urlbase'] + '_1920x1080.jpg' pic = requests.get(url) with open(r'C:\Users\chun\Pictures\1.jpg', 'wb') as f: f.write(pic.content) f.close() k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, r'C:\Users\chun\Pictures\1.jpg', 1 + 2)
# Set mac/win/linux wallpaper if sys == 'Darwin': system( 'osascript -e \'tell application "System Events" to tell every desktop to set picture to "' + img_path + '"\'') elif sys == 'Linux': system('gsettings set org.gnome.desktop.background picture-uri ' + img_path) elif sys == 'Windows': key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel/Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path.replace('\\', '/'), 1 + 2) print('Set wallpaper') # automatically change wallpaper if not run: if sys == 'Darwin' or sys == 'Linux': system('crontab -l | { cat; echo "0 */2 * * * cd ' + folder + ' && $(which python3) ' + folder + 'wallpaper.py > misc/output.log 2>&1"; } | crontab -') elif sys == 'Windows': system( 'schtasks /create /sc hourly /mo 2 /tn "Daily Paper" /tr python3.exe ' + folder + 'wallpaper.py') print('Scheduled Daily Paper.')
def _force_set_foreground_window(self, hWindow): # As there are some restrictions about which processes can call SetForegroundWindow as described here: # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow # we try consecutively three different ways to show the splash screen on top of all other windows. # Solution 1: Pressing alt key unlocks SetForegroundWindow # https://stackoverflow.com/questions/14295337/win32gui-setactivewindow-error-the-specified-procedure-could-not-be-found # Not using win32com.client.Dispatch like in the link because there are problems when building with py2exe. ALT_KEY = win32con.VK_MENU RIGHT_ALT = 0xb8 win32api.keybd_event(ALT_KEY, RIGHT_ALT, 0, 0) win32api.keybd_event(ALT_KEY, RIGHT_ALT, win32con.KEYEVENTF_KEYUP, 0) win32gui.ShowWindow(hWindow, win32con.SW_SHOW) try: win32gui.SetForegroundWindow(hWindow) except Exception as e: exc_message = str(e) logger.debug( 'Failed attempt to show splash screen with keybd_event: {}'. format(exc_message)) if win32gui.GetForegroundWindow() == hWindow: return True # Solution 2: Attaching current thread to the foreground thread in order to use BringWindowToTop # https://shlomio.wordpress.com/2012/09/04/solved-setforegroundwindow-win32-api-not-always-works/ foreground_thread_id, foreground_process_id = win32process.GetWindowThreadProcessId( win32gui.GetForegroundWindow()) appThread = win32api.GetCurrentThreadId() if foreground_thread_id != appThread: try: win32process.AttachThreadInput(foreground_thread_id, appThread, True) win32gui.BringWindowToTop(hWindow) win32gui.ShowWindow(hWindow, win32con.SW_SHOW) win32process.AttachThreadInput(foreground_thread_id, appThread, False) except Exception as e: exc_message = str(e) logger.debug( 'Failed attempt to show splash screen with AttachThreadInput: {}' .format(exc_message)) else: win32gui.BringWindowToTop(hWindow) win32gui.ShowWindow(hWindow, win32con.SW_SHOW) if win32gui.GetForegroundWindow() == hWindow: return True # Solution 3: Working with timers that lock/unlock SetForegroundWindow #https://gist.github.com/EBNull/1419093 try: timeout = win32gui.SystemParametersInfo( win32con.SPI_GETFOREGROUNDLOCKTIMEOUT) win32gui.SystemParametersInfo( win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0, win32con.SPIF_SENDCHANGE) win32gui.BringWindowToTop(hWindow) win32gui.SetForegroundWindow(hWindow) win32gui.SystemParametersInfo( win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, timeout, win32con.SPIF_SENDCHANGE) except Exception as e: exc_message = str(e) logger.debug( 'Failed attempt to show splash screen with SystemParametersInfo: {}' .format(exc_message)) if win32gui.GetForegroundWindow() == hWindow: return True # Solution 4: If on some machines the splash screen still doesn't come on top, we can try # the following solution that combines attaching to a thread and timers: # https://www.codeproject.com/Tips/76427/How-to-Bring-Window-to-Top-with-SetForegroundWindo return False
def set_wallpaper(image_path): if image_path is None: return """ Given a path to an image, set it as the wallpaper """ if not os.path.exists(image_path): log.error("Image does not exist.") sys.exit(1) log.info("Updating wallpaper..") log.info( "Name of wallpaper: {}".format( re.sub("([a-z])([A-Z])", r"\1 \2", image_path.split("/")[-1].split("_")[0]) ) ) if sys.platform.startswith("win32"): bmp_image = Image.open(image_path) bmp_img_path = os.path.splitext(image_path)[0] + ".bmp" bmp_image.save(bmp_img_path, "BMP") key = win32api.RegOpenKeyEx( win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE, ) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo( win32con.SPI_SETDESKWALLPAPER, bmp_img_path, 1 + 2 ) os.remove(bmp_img_path) elif sys.platform.startswith("darwin"): try: command = """ osascript -e 'tell application "System Events" set desktopCount to count of desktops repeat with desktopNumber from 1 to desktopCount tell desktop desktopNumber set picture to "{image_path}" end tell end repeat end tell' """.format( image_path=image_path ) check_call([command], shell=True) except CalledProcessError or FileNotFoundError: log.error("Setting wallpaper failed.") sys.exit(1) elif sys.platform.startswith("linux"): check_call( [ "gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://{}".format(image_path), ] ) log.info("Wallpaper successfully updated. :)")
import sys import win32api import win32con import win32gui import os base_url = 'http://www.bing.com/' url = base_url + 'HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN' r = requests.get(url) data = r.json() images = data.get('images', []) for image in images: image_url = image.get('url', '') if image_url == '': continue image_date = requests.get(base_url + image_url) file_name = os.path.split(image_url)[1] with open(file_name, 'wb') as f: f.write(image_date.content) k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 2拉伸适应桌面,0桌面居中 win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, os.path.join(sys.path[0], file_name), 1 + 2)
def set_wallpaper_permanent(picPath, SHOW_DEBUG): if SHOW_DEBUG: print('Setting the wallpaper') win32gui.SystemParametersInfo(0x0014, picPath, 1 + 2) balloon_tip("Desktop Wallpaper Changer", "Wallpaper Updated!")
def set_background(file_path): de = get_desktop_environment() if de == "windows": key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "6") # 2 for stretching, 0 for centering, 6 for fitting win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, file_path, 1 + 2) elif de == "mac": subprocess.call([ "osascript", "-e", 'tell application "System Events"\n' 'set theDesktops to a reference to every desktop\n' 'repeat with aDesktop in theDesktops\n' 'set the picture of aDesktop to \"' + file_path + '"\nend repeat\nend tell' ]) else: # Linux # gsettings requires it. fetch_envvar("DBUS_SESSION_BUS_ADDRESS") # feh and nitrogen (might) require it. fetch_envvar("DISPLAY") if de in [ "gnome", "unity", "cinnamon", "pantheon", "gnome-classic", "budgie-desktop" ]: # Because of a bug and stupid design of gsettings, see http://askubuntu.com/a/418521/388226 if de == "unity": subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "draw-background", "false" ]) subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://" + file_path ]) subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "picture-options", "scaled" ]) subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "primary-color", "#000000" ]) if de == "unity": assert os.system( 'bash -c "gsettings set org.gnome.desktop.background draw-background true"' ) == 0 elif de == "mate": subprocess.call([ "gsettings", "set", "org.mate.background", "picture-filename", file_path ]) elif de == 'i3': subprocess.call(['feh', '--bg-max', file_path]) elif de == "xfce4": # Xfce4 displays to change the background of displays = subprocess.getoutput( 'xfconf-query --channel xfce4-desktop --list | grep last-image' ).split() for display in displays: subprocess.call([ "xfconf-query", "--channel", "xfce4-desktop", "--property", display, "--set", file_path ]) elif de == "lxde": subprocess.call([ "pcmanfm", "--set-wallpaper", file_path, "--wallpaper-mode=fit", ]) elif de == "kde": if plasma_version() > LooseVersion("5.7"): ''' Command per https://github.com/boramalper/himawaripy/issues/57 Sets 'FillMode' to 1, which is "Scaled, Keep Proportions" Forces 'Color' to black, which sets the background colour. ''' script = 'var a = desktops();' \ 'for (i = 0; i < a.length; i++) {{' \ 'd = a[i];d.wallpaperPlugin = "org.kde.image";' \ 'd.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General");' \ 'd.writeConfig("Image", "file://{}");' \ 'd.writeConfig("FillMode", 1);' \ 'd.writeConfig("Color", "#000");' \ '}}' try: subprocess.check_output([ "qdbus", "org.kde.plasmashell", "/PlasmaShell", "org.kde.PlasmaShell.evaluateScript", script.format(file_path) ]) except subprocess.CalledProcessError as e: if "Widgets are locked" in e.output.decode("utf-8"): print( "Cannot change the wallpaper while widgets are locked! (unlock the widgets)" ) else: raise e else: print("Couldn't detect plasmashell 5.7 or higher.") elif has_program("feh"): print( "Couldn't detect your desktop environment ('{}'), but you have " "'feh' installed so we will use it...".format(de)) subprocess.call(["feh", "--bg-max", file_path]) elif has_program("nitrogen"): print( "Couldn't detect your desktop environment ('{}'), but you have " "'nitrogen' installed so we will use it...".format(de)) subprocess.call(["nitrogen", "--restore"]) else: return False return True
from PIL import Image import os #Variables: saveDir = 'C:\BingWallPaper\\' i = 0 while i<1: try: usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') except: i = 0 else: i = 1 xmldoc = minidom.parse(usock) num = 1 #Parsing the XML File for element in xmldoc.getElementsByTagName('url'): url = 'http://www.bing.com' + element.firstChild.nodeValue #Get Current Date as fileName for the downloaded Picture picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' urlretrieve(url, picPath) #Convert Image picData = Image.open(picPath) picData.save(picPath.replace('jpg','bmp')) picPath = picPath.replace('jpg','bmp') num = num+1 #Set Wallpaper: win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
def set_wallpaper(file_path): print('正在设置为壁纸...') win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, file_path, 1 + 2) print('壁纸设置成功.')
# set to False to compare result and master png files. These may differ depending on OM settings between # environment that creates the master and the results. # # TODO: need a robust png test that is not OM installation dependent. Then set following to False. IGNORE_IMAGE_DIFFERENCES = True # set to True to show viewer for each CRC call SHOW_TEST_VIEWERS = False _prevent_interactive = os.environ.get('GEOSOFT_PREVENT_INTERACTIVE', 0) == '1' if _prevent_interactive: UPDATE_RESULTS = False UPDATE_RESULTS_DONT_ASK = False SHOW_TEST_VIEWERS = False win32gui.SystemParametersInfo(win32con.SPI_SETFONTSMOOTHING, True) # Make root window for UI methods root_window = None if UPDATE_RESULTS and SHOW_TEST_VIEWERS: root_window = Tk() root_window.overrideredirect(1) root_window.withdraw() def _t(s): return s def _verify_no_gx_context(): loc_gx = None
def setWallPaper(path): reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, 'Control Panle\\Desktop', 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(reg_key, 'WallpaperStyle', 0, win32con.REG_SZ, '2') win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, win32con.SPIF_SENDWININICHANGE)
image_url = index_url + item_src['href'] image_request = requests.get(url=image_url, headers=headers) if image_request.status_code == 200: image_request.encoding = 'utf-8' image_html = image_request.text image_soup = BeautifulSoup(image_html, 'lxml') pic_src = image_soup.find( class_='target progressive__img progressive--not-loaded') pic_src = pic_src['data-progressive'] down_request = requests.get(url=pic_src, headers=headers) data = down_request.content today = datetime.date.today() file = open(str(today) + '.jpg', 'wb') file.write(data) file.close() image_path = os.getcwd() + '/' + str(today) + '.jpg' reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) # 最后的参数:2拉伸,0居中,6适应,10填充,0平铺 win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 最后的参数:1表示平铺,拉伸居中等都是0 win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0") # 刷新桌面 win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, image_path, win32con.SPIF_SENDWININICHANGE)
def set_img_as_wallpaper(self, filepath): win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, filepath, 1 + 2) print("Set {} as wallpaper succeed".format(filepath))