случайные дубликаты изображений в папке Python tkinter - PullRequest
0 голосов
/ 20 июня 2020

Я создаю приложение, в котором вы можете указать, сколько случайных изображений вы хотите сгенерировать. Данные случайного изображения берутся с этого URL https://source.unsplash.com/random/1920x1080. всякий раз, когда я создаю новые изображения, вы можете видеть в папке, в которой он создал дубликаты изображений. Возможно, это не проблема программирования, но я трачу много времени на то, чтобы выяснить, как это исправить. Моя цель - выяснить, почему ссылка иногда создает повторяющееся изображение. Буду признателен за любую помощь, которую я могу получить.

для лучшего понимания вот мой код:

modules = ["pip", "requests", "datetime"]

try:
    import time
    from time import sleep
    import urllib
    from tkinter.ttk import *
    import tkinter as tk
    from tkinter import *
    from PIL import ImageTk, Image
    import os
    import requests
    import io
    from tkinter.messagebox import showinfo
    from datetime import datetime
    import subprocess
    import threading
    from threading import Thread
except ImportError:
    import sys
    import pip
    import subprocess
    module_installation_question = input(
        "Some modules are missing, do you want to install all required modules for this project? yes or no.: ").lower()
    if module_installation_question == "yes":
        for module in modules:
            subprocess.call(['pip', 'install', module])
        print("Restart the editor and this project should work...")
        sys.exit()
    elif module_installation_question == "no":
        print("This project won't work if one module is missing...")
        sys.exit()

Image_creator = tk.Tk()
Image_creator.geometry("520x530")
Image_creator.configure(bg="#1A1A1A")

button = tk.Button(Image_creator, text="Start",
                   command=lambda: test())
button.place(relx=0.5, rely=0.5, anchor="center")

url = "https://source.unsplash.com/random/1920x1080"
image_connection1 = ""

reopen_programm_format = '"{}" "{}" "{}"'.format(
    sys.executable,
    __file__,
    os.path.basename(__file__),
    sys.exit,
)


def test():
    for i in range(20):
        extracting_images_from_web()
        sleep(2)
        storing_images()


def storing_images(directory="images downloaded"):
    time_now = datetime.now()
    time_now_format = time_now.strftime("%d.%m.%Y - %H.%M.%S")
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
        filename = f"{time_now_format}" + ".jpg"
        with open(os.path.join(directory, filename), "wb") as saving_image:
            saving_image.write(image_connection1)
            saving_image.close()
    except:
        showinfo("Error", "Random Error ocurred...")


def extracting_images_from_web():
    global image_connection1
    try:
        with urllib.request.urlopen(url) as connection1:
            image_connection1 = connection1.read()
    except urllib.error.URLError:
        showinfo("No Internet Connection",
                 "You need an active internet connection!")


Image_creator.mainloop()
...