Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from io import BytesIO
- from random import randint
- import requests
- import urllib.request
- import wget
- from tkinter import *
- from PIL import ImageTk, Image
- api_key = "your api key"
- username = "your username"
- collection_id = #the id number of the collection you want to view
- base_url = "https://wallhaven.cc/api/v1/"
- opener=urllib.request.build_opener()
- opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
- urllib.request.install_opener(opener)
- def getRandomWall():
- global static_path
- url = "{}collections/{}/{}?apikey={}&page={}".format(base_url, username, collection_id, api_key, 0)
- r = requests.get(url)
- meta = r.json()['meta']
- last_page = meta['last_page']
- per_page = meta['per_page']
- total = meta['total']
- wall = randint(1,total)
- wall_page = 1
- while wall_page * per_page < wall:
- wall_page = wall_page + 1
- wall_page_offset = wall - ((wall_page - 1) * per_page)
- r = requests.get("{}collections/{}/{}?apikey={}&page={}".format(base_url, username, collection_id, api_key, wall_page))
- static_path = r.json()['data'][wall_page_offset - 1]['path']
- return static_path
- def saveWallCallback(e):
- wget.download(static_path)
- def getWallBytes(path):
- global img_data
- response = requests.get(path)
- img_data = response.content
- bg = ImageTk.PhotoImage(Image.open(BytesIO(img_data)))
- return bg
- window=Tk()
- window.title('Hello Python')
- window.geometry("1280x720")
- bg = getWallBytes(getRandomWall())
- my_canvas = Canvas(window)
- my_canvas.pack(fill="both", expand=True)
- class fauxEvent:
- def __init__(self, width, height) -> None:
- self.width = width
- self.height = height
- pass
- def changeWallCallback(e):
- getWallBytes(getRandomWall())
- faux_event = fauxEvent(window.winfo_width(),window.winfo_height())
- resizerCallback(faux_event)
- def resizerCallback(e):
- global bg1, resized_bg, new_bg
- bg1 = Image.open(BytesIO(img_data))
- ratio = bg1.size[0] / bg1.size[1]
- if e.width / ratio > e.height:
- w = e.height * ratio
- h = e.height
- elif e.height * ratio > e.width:
- w = e.width
- h = e.width / ratio
- else:
- w = e.width
- h = e.height
- w = round(w)
- h = round(h)
- resized_bg = bg1.resize((w, h), Image.ANTIALIAS)
- new_bg = ImageTk.PhotoImage(resized_bg)
- my_canvas.create_image(round(e.width/2),round(e.height/2), image=new_bg) #image centered on screen
- pass
- window.bind('<Configure>', resizerCallback)
- my_canvas.bind("<Button-1>", changeWallCallback)
- my_canvas.bind("<Button-3>", saveWallCallback)
- my_canvas.pack()
- window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement