PySimple GUI - проблемы с обратным вызовом кнопки - PullRequest
0 голосов
/ 24 января 2020

Я создал скрипт, который читает из Excel и вводит данные в веб-форму, используя панель мониторинга, созданную в PySimple GUI

На панели инструментов есть три кнопки - Загрузить, Следующая строка и загрузить.

Я новичок в python, и все работает, однако вам нужно дважды щелкнуть каждую кнопку, чтобы обновить панель мониторинга, и я не уверен, где что-то не так.

Извините за некорректный код !

import PySimpleGUI as sg
import openpyxl as xl
import os
import re
import time
import pyperclip
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select

sg.ChangeLookAndFeel('DarkAmber')

at = "NONE"
bu = "NONE"
br = "NONE"
fr = "NONE"
ca = "NONE"
sb = "NONE"
cp = "NONE"
re = "NONE"
co = "NONE"
ln = "NONE"
cs = "NONE"
av = "NONE"
oo = "NONE"
ye = "NONE"
pi = "NONE"
fi = "NONE"
mn = "NONE"
ag = "NONE"
ac = "NONE"
pm = "NONE"
au = "NONE"
ft = "NONE"
eu = "NONE"
ao = "NONE"
de = "NONE"
dp = "NONE"
di = "NONE"
ph = "NONE"
mo = "NONE"
ma = "NONE"
sd = "NONE"
assetname = 'NONE'
collection = 'NONE'
row = 2


def loadMetadata(filename, rowNum):

    spreadsheet = values['Browse'].rsplit('/', 1)[-1]
    folderpath = values['Browse'].rsplit('/', 1)[0] + '/'

    os.chdir(folderpath)

    wb = xl.load_workbook(filename=spreadsheet)
    ws = wb['Sheet1']

    assetname = ws['D'+str(rowNum)]
    collection = ws['C'+str(rowNum)]
    at = ws["E"+str(rowNum)]                                 # E - Asset Title                          
    bu = ws["L"+str(rowNum)]                                # L - Business Unit                         
    br = ws["M"+str(rowNum)]                                        # M - Brands                            
    fr = ws["N"+str(rowNum)]                                    # N - Franchise 
    ca = ws["O"+str(rowNum)]                                     # O - Category
    sb = ws["P"+str(rowNum)]                                 # P - Sub-Category
    cp = ws["Q"+str(rowNum)]                                    # Q - Campaign
    re = ws["R"+str(rowNum)]                                      # R - Region
    co = ws["S"+str(rowNum)]                                      # S - Country
    ln = ws["T"+str(rowNum)]                                     # T - Language
    cs = ws["U"+str(rowNum)]                              # U - Content Sub-type
    av = ws["V"+str(rowNum)]                                # V - Asset Version
    oo = ws["W"+str(rowNum)]                           # W - Originating Office
    ye = ws["X"+str(rowNum)]                                         # X - Year
    pi = ws["Y"+str(rowNum)]                                   # Y - Project ID
    fi = ws["Z"+str(rowNum)]                                      # Z - Fido ID
    #fu = 'Fido URL'                                     # Fido URL
    mn = ws["AA"+str(rowNum)]                     # AA - Master/Adaptation Number
    ag = ws["AB"+str(rowNum)]                                       # AB - Agency
    ac = ws["AC"+str(rowNum)]                               # AC - Agency Contact
    pm = ws["AD"+str(rowNum)]                            # AD - Production Master
    au = ws["AE"+str(rowNum)]                                     # AE - Audience
    ft = ws["AF"+str(rowNum)]                                     # AF - Filetype
    eu = ws["AG"+str(rowNum)]                                      # AG - EAN/UPC
    ao = ws["AH"+str(rowNum)]                                  # AH - Asset Owner
    de = ws["AI"+str(rowNum)]                                  # AI - Description
    dp = ws["AJ"+str(rowNum)]                                    # AJ - Image DPI
    di = ws["AK"+str(rowNum)]                              # AK - Image Dimension
    ph = ws["AL"+str(rowNum)]                                 # AL - Photographer
    mo = ws["AM"+str(rowNum)]                                        # AM - Model
    ma = ws["AN"+str(rowNum)]                                  # AN - Model Agent
    sd = ws["AO"+str(rowNum)]                                   # AO - Shoot Date

    metadata = {
        '-FILENAME-':assetname.value,
        '-COLLECTION-':collection.value,
        '-AT-':at.value,
        '-BU-':bu.value,
        '-BR-':br.value,
        '-FR-':fr.value,
        '-CA-':ca.value,
        '-SB-':sb.value,
        '-CP-':cp.value,
        '-RE-':re.value,
        '-CO-':co.value,
        '-LN-':ln.value,
        '-CS-':cs.value,
        '-AV-':av.value,
        '-OO-':oo.value,
        '-YE-':ye.value,
        '-PI-':pi.value,
        '-FI-':fi.value,
        '-MN-':mn.value,
        '-AG-':ag.value,
        '-AC-':ac.value,
        '-PM-':pm.value,
        '-AU-':au.value,
        '-FT-':ft.value,
        '-EU-':eu.value,
        '-AO-':ao.value,
        '-DE-':de.value,
        '-DP-':dp.value,
        '-DI-':di.value,
        '-PH-':ph.value,
        '-MO-':mo.value,
        '-MA-':ma.value,
        '-SD-':sd.value
        }

    return metadata



layout = [      
    [sg.Text('Frontloader', size=(30, 1), font=("Helvetica", 25))],
    [sg.Text('Filename: ', size=(20,1)), sg. InputText(assetname, key='-FILENAME-',size=(50,1))],
    [sg.Text('_'  * 80)],   
    [sg.Text('Asset Title: ', size=(20,1)),sg.InputText(at, key='-AT-')],
    [sg.Text('Business Unit: ', size=(20,1)),sg.InputText(bu, key='-BU-')],
    [sg.Text('Brand: ', size=(20,1)),sg.InputText(br, key='-BR-')],
    [sg.Text('Franchise: ', size=(20,1)),sg.InputText(fr, key='-FR-')],
    [sg.Text('Category: ', size=(20,1)),sg.InputText(ca, key='-CA-')],
    [sg.Text('Sub-Category: ', size=(20,1)),sg.InputText(sb, key='-SB-')],
    [sg.Text('Region: ', size=(20,1)),sg.InputText(re, key='-RE-')],   
    [sg.Text('Country: ', size=(20,1)),sg.InputText(co, key='-CO-')],
    [sg.Text('Language: ', size=(20,1)),sg.InputText(ln, key='-LN-')],
    [sg.Text('Content Sub-Type: ', size=(20,1)),sg.InputText(cs, key='-CS-')],
    [sg.Text('Originating Office: ', size=(20,1)),sg.InputText(oo, key='-OO-')],
    [sg.Text('Year: ', size=(20,1)),sg.InputText(ye, key='-YE-')],
    [sg.Text('Agency: ', size=(20,1)),sg.InputText(ag, key='-AG-')],
    [sg.Text('Agency Contact: ', size=(20,1)),sg.InputText(ac, key='-AC-')],
    [sg.Text('Filetype: ', size=(20,1)),sg.InputText(ft, key='-FT-')],
    [sg.Text('Description: ', size=(20,1)),sg.InputText(de, key='-DE-')],
    [sg.Text('Image DPI: ', size=(20,1)),sg.InputText(dp, key='-DP-')],
    [sg.Text('Image Dimension: ', size=(20,1)),sg.InputText(di, key='-DI-')],
    [sg.Text('Photographer: ', size=(20,1)),sg.InputText(ph, key='-PH-')],
    [sg.Text('Model Name: ', size=(20,1)),sg.InputText(mo, key='-MO-')],
    [sg.Text('Model Agent: ', size=(20,1)),sg.InputText(ma, key='-MA-')],
    [sg.Text('Shoot Date: ', size=(20,1)),sg.InputText(sd, key='-SD-')],
    [sg.Text('_'  * 80)],      
    [sg.Text('Load a spreadsheet', size=(35, 1))],      
    [sg.Text('filename:', size=(15, 1), auto_size_text=False, justification='right'),      
     sg.InputText(''), sg.FileBrowse()],      
    [sg.Button('Load'), sg.Cancel(),sg.Button('Upload'),sg.Button('Next Row')]      
]


window = sg.Window('Frontloader', default_element_size=(40, 1)).Layout(layout)

while True: 

    event, values = window.Read()

    if len(values['Browse']) > 0:
            metadata = loadMetadata(values,row)
            event, values = window.Read()

    if event == 'Load':
        window['-FILENAME-'].update(metadata['-FILENAME-'])
        window['-AT-'].update(metadata['-AT-'])
        window['-BU-'].update(metadata['-BU-'])
        window['-BR-'].update(metadata['-BR-'])
        window['-FR-'].update(metadata['-FR-'])
        window['-CA-'].update(metadata['-CA-'])
        window['-SB-'].update(metadata['-SB-'])
        window['-RE-'].update(metadata['-RE-'])
        window['-CO-'].update(metadata['-CO-'])
        window['-LN-'].update(metadata['-LN-'])
        window['-CS-'].update(metadata['-CS-'])
        window['-OO-'].update(metadata['-OO-'])
        window['-YE-'].update(metadata['-YE-'])
        window['-AG-'].update(metadata['-AG-'])
        window['-AC-'].update(metadata['-AC-'])
        window['-FT-'].update(metadata['-FT-'])
        window['-DE-'].update(metadata['-DE-'])
        window['-DP-'].update(metadata['-DP-'])
        window['-DI-'].update(metadata['-DI-'])
        window['-PH-'].update(metadata['-PH-'])
        window['-MO-'].update(metadata['-MO-'])
        window['-MA-'].update(metadata['-MA-'])
        window['-SD-'].update(metadata['-SD-'])
        pyperclip.copy(metadata['-COLLECTION-'])

    if event == 'Upload':
        browser = webdriver.Firefox(executable_path = '/usr/local/scripts/geckodriver 2')
        browser.get('REDACTED')
        usernameElem = browser.find_element_by_css_selector('#id_username')
        usernameElem.send_keys('REDACTED')
        passwordElem = browser.find_element_by_css_selector('#id_password')
        passwordElem.send_keys('REDACTED')
        passwordElem.submit()
        browser.implicitly_wait(10)
        uploadElem = browser.find_element_by_xpath('/html/body/nav/ul/li[2]/a/i')
        uploadElem.click()
        browser.get('REDACTED')
        urButton = browser.find_element_by_xpath('//*[@id="add-usage-rights"]')
        time.sleep(2.4)
        urButton.click()
        usageTerritory = browser.find_element_by_css_selector('#rights-management-table > tbody > tr.editable > td.term-territories > div > span > span.selection > span > ul > li > input')
        usageTerritory.send_keys('Asia')
        usageTerritory.send_keys(Keys.RETURN)
        usageTerritory.send_keys('Africa')
        usageTerritory.send_keys(Keys.RETURN)
        usageTerritory.send_keys('Arab States')
        usageTerritory.send_keys(Keys.RETURN)
        usageTerritory.send_keys('Australia')
        usageTerritory.send_keys(Keys.RETURN)
        usageTerritory.send_keys('CIS')
        usageTerritory.send_keys(Keys.RETURN)
        usageTerritory.send_keys('Europe')
        usageTerritory.send_keys(Keys.RETURN)
        usageTerritory.send_keys('North America')
        usageTerritory.send_keys(Keys.RETURN)
        usageTerritory.send_keys('South/Latin America')
        usageTerritory.send_keys(Keys.RETURN)
        use = browser.find_element_by_css_selector('#rights-management-table > tbody > tr.editable > td.term-uses > div > span > span.selection > span > ul > li > input')
        use.send_keys('Social')
        use.send_keys(Keys.RETURN)
        use.send_keys('Digital')
        use.send_keys(Keys.RETURN)
        use.send_keys('OOH')
        use.send_keys(Keys.RETURN)
        use.send_keys('POS')
        use.send_keys(Keys.RETURN)
        use.send_keys('Print')
        use.send_keys(Keys.RETURN)
        use.send_keys('Video')
        use.send_keys(Keys.RETURN)
        use.send_keys('Audio')
        use.send_keys(Keys.RETURN)
        inceptDate = browser.find_element_by_xpath("//input[starts-with(@id,'dp15')]")
        inceptDate.send_keys('03/12/2020')
        inceptMonth = browser.find_element_by_css_selector('.ui-datepicker-month')
        inceptMonth.send_keys('March')
        inceptYear = browser.find_element_by_css_selector('.ui-datepicker-year')
        inceptYear.send_keys('2019')
        notSpecified = browser.find_element_by_css_selector('#override-option > label:nth-child(1)')
        notSpecified.click()
        expiryDate = browser.find_element_by_xpath("//input[starts-with(@id,'dp15')]")
        expiryDate.send_keys('03/12/2020')
        description2 = browser.find_element_by_css_selector('#rights-management-table > tbody > tr.editable > td.term-description > div > input[type=text]')
        description2.send_keys('USAGE RIGHTS DESCRIPTION')
        addUsage = browser.find_element_by_css_selector('.save-term')
        addUsage.click()
        at = metadata['-AT-']                                 # Asset Title  
        bu = metadata['-BU-']                              # Global Brands
        br = metadata['-BR-']                                       # Brand
        fr = metadata['-FR-']                                    # Franchise
        ca = metadata['-CA-']                                    # Catagory
        sb = metadata['-SB-']                                 # Sub-Catagory
        cp = metadata['-CP-']                                    # Campaign
        re = metadata['-RE-']                                      # Region
        co = metadata['-CO-']                                      # Country
        ln = metadata['-LN-']                                     # Language
        cs = metadata['-CS-']                            # Content Sub-type
        av = metadata['-AV-']                               # Asset Version
        oo = metadata['-OO-']                          # Originating Office
        ye = str(metadata['-YE-'])                                        # Year
        pi = metadata['-PI-']                                  # Project ID
        fi = metadata['-FI-']                                      # Fido ID
        #fu = 'Fido URL'                                     # Fido URL
        mn = metadata['-MN-']                    # Master/Adaptation Number
        ag = metadata['-AG-']                                       # Agency
        ac = metadata['-AC-']                               # Agency Contact
        pm = metadata['-PM-']                            # Production Master
        au = metadata['-AU-']                                    # Audience
        ft = metadata['-FT-']                                     # Filetype
        eu = metadata['-EU-']                                      # EAN/UPC
        ao = metadata['-AO-']                                  # Asset Owner
        de = metadata['-DE-']                                  # Description
        dp = str(metadata['-DP-'])                                    # Image DPI
        di = metadata['-DI-']                              # Image Dimension
        ph = metadata['-PH-']                                # Photographer
        mo = metadata['-MO-']                                        # Model
        ma = metadata['-MA-']                                 # Model Agent
        sd = metadata['-SD-']                                   # Shoot Date
        assetTitle = browser.find_element_by_css_selector('#id_wba_title')
        assetTitle.send_keys(at)
        businessUnit = Select(browser.find_element_by_css_selector('#id_wba_brand'))
        businessUnit.select_by_visible_text(bu)
        brand = Select(browser.find_element_by_css_selector('#id_wba_subbrand'))
        brand.select_by_visible_text(br)
        franchise = Select(browser.find_element_by_css_selector('#id_wba_franchise'))
        franchise.select_by_visible_text(fr)
        category = Select(browser.find_element_by_css_selector('#id_wba_category'))
        category.select_by_visible_text(ca)
        subCatagory = Select(browser.find_element_by_css_selector('#id_wba_subcategory'))
        subCatagory.select_by_visible_text(sb)
        region = Select(browser.find_element_by_css_selector('#id_wba_region'))
        region.select_by_visible_text(re)
        country = Select(browser.find_element_by_css_selector('#id_wba_country'))
        country.select_by_visible_text(co)
        Language = Select(browser.find_element_by_css_selector('#id_wba_language'))
        Language.select_by_visible_text(ln)
        contentSubType = Select(browser.find_element_by_css_selector('#id_wba_channel'))
        contentSubType.select_by_visible_text(cs)
        originatingOffice = Select(browser.find_element_by_css_selector('#id_wba_office'))
        originatingOffice.select_by_visible_text(oo)
        year = Select(browser.find_element_by_css_selector('#id_wba_year'))
        year.select_by_visible_text(ye)
        agency = Select(browser.find_element_by_css_selector('#id_wba_agency'))
        agency.select_by_visible_text(ag)
        agencyContact = browser.find_element_by_css_selector('#id_wba_agency_contact')
        agencyContact.send_keys(ac)
        fileType = Select(browser.find_element_by_css_selector('#id_wba_filetype'))
        fileType.select_by_visible_text(ft)
        description = browser.find_element_by_css_selector('#id_wba_description')
        description.send_keys(de)
        imageDPI = Select(browser.find_element_by_css_selector('#id_wba_imagedpi'))
        imageDPI.select_by_visible_text(dp)
        imageDimension = browser.find_element_by_css_selector('#id_wba_imagedimension')
        imageDimension.send_keys(di)
        photographer = browser.find_element_by_css_selector('#id_wba_photographersname')
        photographer.send_keys(ph)
        model = browser.find_element_by_css_selector('#id_wba_modelsname')
        model.send_keys(mo)
        modelAgent = browser.find_element_by_css_selector('#id_wba_modelsagent')
        modelAgent.send_keys(ma)
        shootDate = browser.find_element_by_css_selector('#id_wba_photoshoot')
        shootDate.send_keys(sd)

    if event == 'Next Row':
        row = row + 1
        metadata = loadMetadata(values,row)
        window['-FILENAME-'].update(metadata['-FILENAME-'])
        window['-AT-'].update(metadata['-AT-'])
        window['-BU-'].update(metadata['-BU-'])
        window['-BR-'].update(metadata['-BR-'])
        window['-FR-'].update(metadata['-FR-'])
        window['-CA-'].update(metadata['-CA-'])
        window['-SB-'].update(metadata['-SB-'])
        window['-RE-'].update(metadata['-RE-'])
        window['-CO-'].update(metadata['-CO-'])
        window['-LN-'].update(metadata['-LN-'])
        window['-CS-'].update(metadata['-CS-'])
        window['-OO-'].update(metadata['-OO-'])
        window['-YE-'].update(metadata['-YE-'])
        window['-AG-'].update(metadata['-AG-'])
        window['-AC-'].update(metadata['-AC-'])
        window['-FT-'].update(metadata['-FT-'])
        window['-DE-'].update(metadata['-DE-'])
        window['-DP-'].update(metadata['-DP-'])
        window['-DI-'].update(metadata['-DI-'])
        window['-PH-'].update(metadata['-PH-'])
        window['-MO-'].update(metadata['-MO-'])
        window['-MA-'].update(metadata['-MA-'])
        window['-SD-'].update(metadata['-SD-'])
        pyperclip.copy(metadata['-COLLECTION-'])



event, values = window.Read()
...