GUIzero tkinter неверное имя команды ".! Button" - PullRequest
0 голосов
/ 28 февраля 2020

Так что я использую GUIzero, чтобы попытаться сделать массовый загрузчик, но столкнулся с небольшой проблемой. Когда я запускаю код, он работает нормально, но если я ввожу неправильное имя файла, затем нажимаю кнопку отправки, возникает ошибка.

import ao3                                                                                                              # Imports the AO3 library
import re                                                                                                               # Imports the regex library
import webbrowser                                                                                                       # Imports the web browser library
from guizero import App, Text, PushButton, TextBox, CheckBox                                                            # Imports the GUIzero library

fileName = ""
selectedFormat = ""

def GUI():
    def submit(selectedFormat):
        fileName = name.value
        selectionPDFSelected = boxPDF.value
        selectionMOBISelected = boxMOBI.value
        selectionEPUBSelected = boxEPUB.value
        if fileName != None:
            fileName = re.search('[a-zA-Z0-9]+', fileName).group()
            if selectionPDFSelected or selectionMOBISelected or selectionEPUBSelected == 1:
                if selectionPDFSelected == 1:
                    selectedFormat = "PDF"
                elif selectionMOBISelected == 1:
                    selectedFormat = "MOBI"
                elif selectionEPUBSelected == 1:
                    selectedFormat = "EPUB"

                name.value = fileName
                selection_label.value = selectedFormat
                app.destroy()
            else:
                print("No format selected, please try again")
        else:
            print("No file name inputted, please try again")

    app = App(layout="grid", width ="525", height="100", title="AO3 Downloader")

    name_label = Text(app, text="Please enter the filename of the text file:", grid=[0, 0], align="left")
    name = TextBox(app, text="", grid=[1, 0])

    selection_label = Text(app, text="Please tick which format you want to download to:", grid=[0, 1], align="left")
    boxPDF = CheckBox(app, text="PDF", grid=[1, 1])
    boxMOBI = CheckBox(app, text="MOBI", grid=[2, 1])
    boxEPUB = CheckBox(app, text="EPUB", grid=[3, 1])

    submit_button = PushButton(app, text="Submit", align="bottom", grid=[0, 4])
    submit_button.when_clicked = submit

    app.display()
    return name.value, selection_label.value

def AO3Downloader(fileName, selectedFormat):                                                                        # Function to download AO3 fics
    print(fileName, selectedFormat)
    validName = False                                                                                               # Define the validName boolean
    i = 0                                                                                                           # Variable to initialise loop
    formatChoice = ''                                                                                               # Variable to initialise format choice
    formatType = ''                                                                                                 # Variable to initialise format to download in
    count = 0                                                                                                       # Variable to initialise count for how many lines
    fileFic = ""

    fileName = fileName + ".txt"

    while validName != True:
        try:
            fileFic = open(fileName, "r")
            validName = False
        except IOError:
            print("File not found, please enter a valid file name")
            GUI()

    fileFic = open(fileName, "r")                                                                                   # Opens the file

    for line in fileFic:                                                                                            # Repeats for each line in the file
        count += 1                                                                                                  # Adds 1 to count for each line
        fileFic = open(fileName, "r")                                                                               # Reopens the text file since the for loop messes with the variable

    while formatType == '':                                                                                         # Repeats if there is no format selected
        if selectedFormat == "PDF":
            formatType = ".pdf"
        elif selectedFormat == "MOBI":
            formatType = ".mobi"
        elif selectedFormat == "EPUB":
            formatType = ".epub"
        else:                                                                                                       # Determines if the user entered not 1 or 2
            print("Error, please try again")                                                                        # Displays an error

    def tagMaker(splittedList, lengthArray):                                                                        # Function to make the end tag
        endTag = ''                                                                                                 # Variable to initialise the end tag (CAN'T BE AT THE START DUE TO ERRORS)
        if lengthArray == 1:                                                                                        # If statement to determine if there is only one word in the title
            endTag = splittedList[0]                                                                                # Sets the end tag variable to the only word in the title
        elif lengthArray > 1:                                                                                       # If statement to determine if there is more than one word in the title
            for i in range(lengthArray):                                                                            # For loop to add each word in the title to the end tag with %20
                endTag = endTag + splittedList[i] + '%20'                                                           # Sets the end tag variable to the the current end tag and the next word with %20 on the end
            endTag = endTag.replace('%20', '')[:-3]                                                                 # Removes the last %20 off the final word
        return endTag                                                                                               # Returns the end tag for the file

    print("Now downloading all fics in", formatType)                                                                # Print statement to inform user of format picking success
    print("*----------------------------------------*")                                                             # Print statement to create break for a cleaner perspective

    for i in range(count):                                                                                          # Repeats for how ever many lines there are in the file
        line = fileFic.readline()                                                                                   # Get URL from file
        removedEnd = re.search('https://archiveofourown.org/works/[0-9]+', line).group()                            # Removed the /chapters/numbers bit from the end so it can be more easily manipulated
        workID = int(removedEnd.replace('https://archiveofourown.org/works/', ''))                                  # Finds individual ID for story
        work = ao3.Work(workID)                                                                                     # Assigns that ID to AO3 api variable
        title = work.title                                                                                          # Grabs the title using AO3 api
        print("Found", title + ". Now grabbing URL")                                                                # Print statement to inform user of the fic it is going to download
        fiveWordTitle = title.split()[:6]                                                                           # Grabs first five words of the title
        cleanedFiveWordTitle = re.sub('[^A-Za-z0-9 ]', '', str(fiveWordTitle))                                      # Makes sure the title only has numbers and characters
        splittedList = cleanedFiveWordTitle.split()                                                                 # Splits title into separate array indexes allowing it to be put into the end tag
        lengthArray = len(splittedList)                                                                             # Finds length of the array allowing for the end tag to be made
        endTag = tagMaker(splittedList, lengthArray)                                                                # Creates the tag at the end
        downloadURL = 'https://archiveofourown.org/downloads/' + str(workID) + '/' + str(endTag) + formatType       # Creates the full download URL with file extension
        print("URL grabbed, now downloading")                                                                       # Print statement to inform user of URL tagging success
        webbrowser.open(downloadURL, new=0, autoraise=True)                                                         # Launches the download site
        print("Moving onto to the next fic")                                                                        # Print statement to inform user of fic downloading success
        fileResult = open("DownloadedFics.txt", "a")                                                                # Opens and assigns the text file "Downloads.txt" to a variable
        fileResultString = title + " Downloaded in " + formatType + "\n"                                            # Creates the string which has the title and format with it
        fileResult.write(fileResultString)                                                                          # Writes the variable fileResultString to DownloadedFics.txt
        print("*----------------------------------------*")                                                         # Print statement to create break for a cleaner perspective

    fileResult.write("*----------END OF DOWNLOADED FILES----------*\n")                                             # Writes to DownloadedFics.txt indicating the program has finished
    input("All fics downloaded, press enter to exit")                                                               # Print statement to inform user that every fic has been downloaded

fileName, selectedFormat = GUI()
AO3Downloader(fileName, selectedFormat)                                                                             # Calls the AO3 downloader function

Ошибка возникает где-то в 'while validName! = True: ' немного. Но я не уверен, где.

Спасибо всем!

...