예제 #1
0
import PySimpleGUI as sg

layout = [[sg.Txt('Enter values to calculate')],
          [sg.In(size=(8, 1), key='numerator')], [sg.Txt('_' * 10)],
          [sg.In(size=(8, 1), key='denominator')],
          [sg.Txt('', size=(8, 1), key='output')],
          [sg.ReadButton('Calculate', bind_return_key=True)]]

window = sg.Window('Math').Layout(layout)

while True:
    button, values = window.Read()

    if button is not None:
        try:
            numerator = float(values['numerator'])
            denominator = float(values['denominator'])
            calc = numerator / denominator
        except:
            calc = 'Invalid'

        window.FindElement('output').Update(calc)
    else:
        break
import cv2
import numpy as np
import PySimpleGUI as sg
import os
import detectShapes as detectShapes

#Declaram variabilele globale in care vom stoca imaginiile

global imgOriginal, imgGray, imgBlur, imgCanny, imgContour, shapeName

#Fereastra va fi impartita in doua coloane

#Prima coloana care contine cautarea foldarului cu imagini, a listei si a butoanelor
fileListColumn = [[
    sg.Text("Image Folder"),
    sg.In(size=(25, 1), enable_events=True, key="-FOLDER-"),
    sg.FolderBrowse(),
], [
    sg.Listbox(values=[], enable_events=True, size=(40, 20), key="-FILE LIST-")
],
                  [
                      sg.Button('Normal image', key="-ORIGINAL-"),
                      sg.Button('Gray image', key="-GRAY-"),
                      sg.Button('Blur image', key="-BLUR-"),
                  ],
                  [
                      sg.Button('Canny image', key="-CANNY-"),
                      sg.Button('Detect shape', key="-SHAPE-"),
                  ], [sg.Button('Exit', key="-EXIT-")]]

#A doua coloana in care se afiseaza imaginiile
예제 #3
0
    while True:  # Event Loop
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'OK'):
            if event == sg.WIN_CLOSED:
                color_chosen = None
            break
        window['-OUT-'](f'You chose {event[0]} : {event[1]}')
        color_chosen = event[1]
    window.close()
    if old_look_and_feel is not None:
        sg.theme(old_look_and_feel)
    return color_chosen


if __name__ == '__main__':
    sg.theme('Light Brown 4')
    layout = [[sg.In(key='-CHOICE-'), sg.B('Color Picker')],
              [sg.Ok(), sg.Cancel()]]
    window = sg.Window('My application', layout)
    while True:
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Cancel'):
            break
        if event.startswith('Color'):
            window.hide()
            color_chosen = popup_color_chooser('Dark Blue 3')
            window['-CHOICE-'].update(color_chosen)
            window.un_hide()
        else:
            print(f'The current look and feel = {sg.CURRENT_LOOK_AND_FEEL}')
예제 #4
0
import sys
import os
from pathlib import Path
import PySimpleGUI as sg
from PySimpleGUI.PySimpleGUI import Button

import config
import sensor_utils

# create the Window that collects the sensor CSV file to open,
# and the list of buildings.
layout = [
    [sg.Text("Sensor Information File:", font='Any 14')],
    [
        sg.In(size=(80, 1), enable_events=True, key="sensor-file"),
        sg.FileBrowse('Select Sensor File',
                      file_types=(('CSV files', '*.csv'), ('All Files',
                                                           '*.*'))),
    ],
    [sg.Text('')],
    [sg.Text('Building List', font='Any 14')],
    [
        sg.Text(
            'One Row per building, each row has a Building Abbreviation and Building Name, separated by a colon.'
        )
    ],
    [sg.Multiline('Bldg1: Building Name', (50, 4), key='bldgs')],
    [sg.Text('')],
    [sg.Button('Continue', key='continue'),
     sg.Button('Cancel', key='cancel')],
예제 #5
0
import PySimpleGUI as sg
import selenium as sel
import parse_file as pf

sg.theme('Light Blue 2')

layout = [
          [sg.Text('Select File')],
          [sg.Input(key='-IN-'), sg.FileBrowse(target = ('-IN-'))],
          [sg.Text('Select Starting Date')],
          [sg.CalendarButton('Date',format='%m-%d-%y', key = '-DATE-', target = '-DATESELECTED-', enable_events=True), sg.In(enable_events = True, key = '-DATESELECTED-', size = (10, 1))],
          [sg.Text('Enter AZBOA Site credentials')],
          [sg.Text('ID:'),sg.InputText(key = '-ID-')],
          [sg.Text('Pasword'),sg.InputText(key = '-PASSWORD-')],
          [sg.Text('Choose Browser')],
          [sg.InputCombo(('Chrome','Mozilla'),size=(20,20), key = '-BROWSER-')],
          [sg.Submit(), sg.Cancel(), sg.Exit() ] 
          ]

window = sg.Window('CPE Logger', layout)


while True: #Event loop
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
           break
    if event == 'Submit':
        #Get the pertinent data from the UI form
        file = values['Browse']
        date = values['-DATE-']
예제 #6
0
    def selezione (self, event, window):
        print(event)
        if event == "YouTube popular videos":
            countries = load_countryList(self)
            print('Country list import completed')
            window.close()
            layout = [[sg.Text("Choose country", key="feedback")],
                      [sg.Combo(countries, size=(32, 20), enable_events=True, key='combo')],
                      [sg.Button("SUBMIT", size=(29, 2))],
                      [sg.Button("QUIT")]
                      ]
            # Create the Window
            window2 = sg.Window(event, layout)
            # Event Loop to process "events"
            while True:
                event, values = window2.read()
                if event in (None, sg.WINDOW_CLOSED,  'QUIT'):
                    break
                if event == "SUBMIT":
                    combo = values['combo']
                    country = combo[1]
                    window2.close()
                    print(country)
                    SpotifyTag = 'YouTube popular in ' + country
            self.get_videos_popular(country)

        if event == "One of my YouTube playlists":
            playlists = self.get_myPlaylists()
            print('My YouTube playlist names imported')
            window.close()
            layout = [[sg.Text("Choose playlist", key="feedback")],
                      [sg.Combo(playlists, size=(32, 20), enable_events=True, key='combo')],
                      [sg.Button("SUBMIT", size=(29, 2))],
                      [sg.Button("QUIT")]
                      ]
            # Create the Window
            window2 = sg.Window(event, layout)
            # Event Loop to process "events"
            while True:
                event, values = window2.read()
                if event in (None, sg.WINDOW_CLOSED, 'QUIT'):
                    break
                if event == "SUBMIT":
                    playlistTitle = values['combo']
                    playlistId = self.all_playlists[playlistTitle]["id"]
                    window2.close()
                    SpotifyTag = 'My YouTube playlist: ' + playlistTitle
            self.get_video_in_myPlaylist(playlistId,playlistTitle)

        if event == "My YouTube liked videos":
            window.close()
            self.get_videos_myLikedVideos()
            SpotifyTag = 'My YouTube liked videos'

        if event == "My YouTube watch history":
            window.close()
            layout = [[sg.Text("You must download your YouTube history as a json file and upload it here.")],
                      [sg.Text("To do so:")],
                      [sg.Text("1. Go to https://takeout.google.com/settings/takeout"),sg.Button("click here")],
                      [sg.Text("2. Deselect all and scroll to the bottom of the page")],
                      [sg.Text("3. Tick the YouTube and YouTube Music item")],
                      [sg.Text("4. Select JSON format instead of the default HTML value")],
                      [sg.Text("5. Follow the steps to download the watch history and save it locally")],
                      [sg.Text("6. Use the browse button below to load the JSON file here")],
                      [sg.Text(" ")],
                      [sg.In(key='_FILES_'), sg.FileBrowse(file_types=(("JSON Files", "*.json"),))],
                      [sg.Button("SUBMIT", size=(55, 2))],
                      [sg.Text(" ")],
                      [sg.Button("QUIT")]
                      ]
            # Create the Window
            window2 = sg.Window(event, layout)
            # Event Loop to process "events"
            while True:
                event, values = window2.read()
                if event in (None, sg.WINDOW_CLOSED, 'QUIT'):
                    break
                if event == "click here":
                    webbrowser.open('https://takeout.google.com/settings/takeout', new=2)
                if event == "SUBMIT":
                    filepath = values['_FILES_']
                    if filepath == "":
                        break
                    else:
                        self.get_watch_history(filepath)
                        window2.close()
                        SpotifyTag = 'My YouTube watch history'

        nome_playlist = input("What would you like the new playlist to be called? ")
        self.add_song_to_playlist(nome_playlist, SpotifyTag)
예제 #7
0
def launch_gui():

##########################################
# initializing vocabulary list and class
##########################################

    WS = VOC_class.VOC()
    keys = WS.keys

##############################################
# Conjugation function and languages
##############################################

    lang_src = 'german'
    lang_dest = 'french'

############################
# initializing GUI window
############################

    sg.theme('DarkAmber')   # Add a touch of color

# ----- Full layout -----
    new_word_layout = []
    for k in keys:
        new_word_layout.append([sg.Text(k+' :', size=(10, 1)), sg.InputText(key=k)])

    layout = [
            [sg.Menu([['&Source language', ['&french', '&german']],['&list', [WS.list_of_lists()]],
                      ['&About', '&Read me']], tearoff=False)],
            [sg.Text("TEST YOUR SKILLS", size=(35, 1), justification='center', relief=sg.RELIEF_RIDGE)],
            [sg.Button("Generate word", key="-generate-"), sg.In(enable_events=True,
                                                                 key="-word_to_translate-", size=(35, 1))],
            [sg.Text("Enter translation: "), sg.InputText(size=(35, 1), key="-translation-"), sg.Button('Check',
                                                                                                    key="-check-")],
            [sg.Text('', key='-answer-', size=(50, 1))],
            [sg.Text('')],
            [sg.Text("GET INFORMATION", size=(35, 1), justification='center', relief=sg.RELIEF_RIDGE)],
            [sg.Button("ASK GOOGLE (internet connexion needed)", enable_events=True, key='-google-'), sg.In(key='-google_to_translate-', size=(35, 1))],
            [sg.Text('', key='-google_answer-', size=(35, 1))],
            [sg.Button("CONJUGATE", enable_events=True, key='-conjugate-'),
                      sg.In(key='-to_conjugate-', size=(35, 1))],
            [sg.Text('')],
            [sg.HSeparator()],
            [sg.Text('')],
            [sg.Text("ADD A NEW WORD TO YOUR PERSONAL LIST", size=(70, 1), justification='center', relief=sg.RELIEF_RIDGE)],
            [sg.Frame(title="New word to add", layout=new_word_layout), sg.Button('ADD', key="-add_word-")],
            [sg.Text('')],
            [sg.HSeparator()],
            [sg.Text('')],
            [sg.Text("DISPLAY YOUR PERSONAL LIST", size=(70, 1), justification='center', relief=sg.RELIEF_RIDGE)],
            [sg.Button('SHOW LIST', enable_events=True, key='-show_list-')],
            [sg.Text('')],
            [sg.HSeparator()],
            [sg.Text('')],
            [sg.Cancel("Exit")],
            ]
# Create the window
    window = sg.Window("French-German vocabulary", layout)

    word = None

#################
# Event loop
#################

    while True:

        # read action on the window
        event, values = window.read()

        # remove printed message
        window['-answer-'].update('')

        # Change source and destination language
        # ----------------------------------------

        if event == 'french':
            lang_src = 'french'
            conjugate = conjugate_fr
            lang_dest = 'german'
        if event == "german":
            lang_src = 'german'
            conjugate = conjugate_de
            lang_dest = 'french'

        # Show Readme file
        # ----------------------------------

        if event == 'Read me':
            text = open("../README.md", 'r').read()
            new_window = sg.Window('About',
                                   [
                                       [sg.Text(text, text_color='white')]
                                   ])
            while True:
                ev, val = new_window.read()
                if ev == sg.WIN_CLOSED:
                    break
            new_window.close()

        # Change my_list file
        # ------------------------------

        for l in WS.list_of_lists():
            l = l.replace('&','')
            if event == l:
                WS.change_list(l)

        #  Translate from list
        # ----------------------------

        if event == "-generate-":
            # print random word present in WS.list
            word = WS.print_rand()
            window["-word_to_translate-"].update(word[keys[0]])

        if event == "-check-":
            if len(window["-word_to_translate-"].get()) == 0:
                sg.popup("You have to generate a word to translate before looking for the translation !!", title='Error')
            else:
                # check if translation is correct
                if values["-translation-"] in word[keys[1]]:
                    # print message bellow
                    window['-answer-'].update('Correct !')
                # check if synonym
                elif values["-translation-"] in word[keys[7]]:
                    # print messsage bellow
                    window['-answer-'].update('Correct but a better translation would be {}'.format(word[keys[1]]))
                else:
                    # print correct answer
                    text_out = word[keys[1]]+word[keys[7]]
                    window['-answer-'].update('Incorrect, the translation is/are: '+text_out)

        # Google translate
        # -----------------------

        if event == "-google-":
            if len(window["-google_to_translate-"].get()) == 0:
                sg.popup('You have to enter a word to translate !', title='Error')
            else:
                # translation is a class that contains several information in addition to the translation
                translation = Translator().translate(str(window['-google_to_translate-'].get())
                                       , src=lang_src, dest=lang_dest)
                # if text too long, print in external window
                if len(translation.text) < 20:
                    window['-google_answer-'].update('Translation: '+translation.text)
                else:
                    new_window = sg.Window('Translated text',
                                           [
                                               [sg.Text(translation.text)],
                                               [sg.Button('OK', key='-exit-')]
                                           ])
                    while True:
                        ev, val = new_window.read()
                        if ev == sg.WIN_CLOSED:
                            break
                        if ev == '-exit-':
                            break

        #
        # Conjugate
        # ------------------------

        if event == '-conjugate-':
            verb = window['-to_conjugate-'].get()
            if len(verb) == 0:
                sg.popup('You have to enter a verb to conjugate !', title='Error')
            else:
                # conjugate and return table of conjugation
                table_display = conjugate(verb)
                # open window with conjugation information
                sg.Window('Conjugation table of {}'.format(verb), layout=[[sg.Column(table_display)]]).read()



        # Add word to my_list
        # -----------------------

        if event == "-add_word-":

            # if no word is given
            if len(window[keys[0]].get()) == 0:
                sg.popup('At least a new word must be given in order to add a new item to your list !', title='Error')

            else:
                new_word = []
                for k in keys:
                    if len(window[k].get()) != 0:
                        new_word.append(window[k].get())
                    else:
                        new_word.append(" ")

                # Create new window for confirmation
                new_window = sg.Window('Add word',
                                   [
                                    [sg.Text('Add the following new word to your list ?')],
                                    [sg.Text(str(new_word))],
                                    [sg.Button('YES', key='-yes-'), sg.Button('NO', key='-no-')]
                                   ])
                # read event in new window
                while True:
                    ev, val = new_window.read()
                    if ev == sg.WIN_CLOSED:
                        break
                    if ev == '-yes-':
                        WS.add_word(new_word)
                        break
                    if ev == '-no-':
                        break
                new_window.close()

        # -- Show list --
        if event == "-show_list-":
            table = tabulate(WS.my_list, headers=keys, tablefmt='rst')
            sg.Window('My list of vocabulary in alphabetical order',
                      [[sg.Text(table, font='Courier', text_color='white')]]).read()

        # close window
        if event == sg.WIN_CLOSED or event == "Exit":
            break

    window.close()
예제 #8
0
            key='Image-{}-{}'.format(i, j),
            background_color='white',
            size=(120,120),
            pad=(1,1),
            enable_events=True)
        )

    img_grid.append(img_row)

layout = [
    [
        sg.Column(img_grid),
        sg.VerticalSeparator(pad=None),
        sg.Column([
            [sg.Frame('Paths:', [
                [sg.In('Image Directory', key='ImagePath', enable_events=True), sg.FolderBrowse()],
                [sg.In('Image List File', key='ImageListPath', enable_events=True), sg.FileBrowse(file_types=(('ALL Files', '*.*'), ('CSV', '*.csv')),)],
                [sg.In('Anno File', key='AnnoPath', enable_events=True), sg.FileBrowse(file_types=(('ALL Files', '*.*'), ('CSV', '*.csv')),)]
            ])],
            [sg.Frame('Image Files:', [
                [sg.Listbox(values=[], key='ImageList', enable_events=True, size=(51, 15))]
            ])],
            [sg.Frame('Select Label:', [
                [sg.Button('Expand'), sg.Button('Clear'), sg.Button('Statistics')],
                [sg.Listbox(values=classes, key='LabelList', enable_events=True, size=(51, len(classes)))]
            ])],
            [sg.Frame('Control:', [
                [sg.T('Progress: {}/{}'.format(pageNo, pageCount), key='ProgressText', size=(30, 1), auto_size_text=True)],
                [sg.ProgressBar(pageCount, orientation='h', size=(48, 20), key='ProgressBar')],
                [sg.Checkbox('Auto Save (ONLY for Prev / Next)', key='AutoSave', default=True)],
                [sg.Button('Prev'), sg.Button('Save'), sg.Button('Next')]
예제 #9
0
def main():
	"""
    Main method. Will be passed in our conditional statement later.
    """
	menu_def = [['File', ['Open', 'Save', 'Exit', 'Properties']],
	            ['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],
	            ['Help', 'About...'], ]
	sg.theme('Black')
	sg.SetOptions(text_justification='center')
	layout = [[sg.Text('Please enter a country name', size=(100, 2), justification='center',
	                   auto_size_text=True)],
	          [sg.In(size=(100, 2), key='-countryName-', justification='center')],
	          [sg.Text('Correct country name will show here', size=(100, 2), key='output',
	                   justification='center')],
	          [sg.Button('Get data', pad=((500, 5), 0), size=(7, 1), bind_return_key=True),
	           sg.Button('Clear', size=(7, 1)), sg.Quit(size=(7, 1))],
	          [sg.Checkbox('Show graph of data', key='-Box-', pad=((600, 5), 2),
	                       enable_events=True)],
	          [sg.Text('Country data output...', size=(100, 1), justification='center')],
	          [sg.Output(size=(100, 42), key='-Print-')]]
	window = sg.Window('COVID-19 Country Data Analysis', layout, finalize=True)
	
	def read_data_full():
		"""
        Read online CSV file and save the data in csvFile variable
        """
		# Get CSV data from online (up to date CSV)
		url = "https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv"
		csv = requests.get(url).content
		# Read CSV data
		csvFile = pd.read_csv(io.StringIO(csv.decode('unicode_escape')), error_bad_lines=False)
		csvFile = csvFile.set_index(['Date'])
		return csvFile
	
	def read_data_monthly(val):
		"""
        Setting 'Country' as the index in order to sort the values from the csvFile using country
        names
        """
		countryData = val.reindex(columns=['Country', 'Confirmed', 'Recovered', 'Deaths'])
		dateData = pd.date_range(start='1/22/2020',end=date.today())
		return countryData,dateData
	
	def generate_monthly_data(val):  # Rearranging per month
		"""
        Rearranging the countryData from read_data_monthly() per month for better reporting on a
        monthly basis. The last month is reported via the last available data (Yesterday or 2
        days back)
        """
		# January data for all countries
		janData = val.loc['2020-01-31']
		janDataCountriesTotal = janData.set_index(['Country'])
		# February data for all countries
		febData = val.loc['2020-02-29']
		febDataCountriesTotal = febData.set_index(['Country'])
		# March data for all countries
		marData = val.loc['2020-03-31']
		marDataCountriesTotal = marData.set_index(['Country'])
		# April data for all countries
		aprData = val.loc['2020-04-30']
		aprDataCountriesTotal = aprData.set_index(['Country'])
		# May data for all countries though last available day if 2020-05-31 is not available
		lastDay1 = str(date.today() - timedelta(days=1))  # Try for 1 day back
		lastDay2 = str(date.today() - timedelta(days=2))  # Try 2 days back if the 1 day back data
		lastDay3 = str(date.today() - timedelta(days=3))  # Try 3 days back if the 2 day back data
		try:
			mayCheck = val.loc['2020-05-31'].count()
			if mayCheck > 0:
				mayData = val.loc['2020-05-31']
			else:
				mayLastDayCount = val.loc[lastDay1].count()
				if mayLastDayCount == 0:
					mayData = val.loc[lastDay2]
				else:
					mayData = val.loc[lastDay1]
		except:
			mayData = val.loc['2020-05-31']
		mayDataCountriesTotal = mayData.set_index(['Country'])
		# June data for all countries though last available day if 2020-06-30 is not available
		try:
			junCheck = val.loc['2020-06-30'].count()
			if junCheck > 0:
				junData = val.loc['2020-06-30']
			else:
				junLastDayCount = val.loc[lastDay1].count()
				if junLastDayCount == 0:
					junData = val.loc[lastDay2]
				else:
					junData = val.loc[lastDay1]
		except:
			junData = val.loc[lastDay1]
		junDataCountriesTotal = junData.set_index(['Country'])
		return janDataCountriesTotal, febDataCountriesTotal, marDataCountriesTotal, \
		       aprDataCountriesTotal, mayDataCountriesTotal, junDataCountriesTotal
	
	def check_country_name(val1, val2):
		"""
        Get a count check once country name is entered to make sure that the country name exist
        in the csvFile
        """
		return val1.loc[val2].count()
	
	def generate_daily_mean(val):
		"""
        Generating daily mean via the last available data since the data is cumulative. Then,
        the total is divided by the total days of the outbreak (Jan 22, 2020 through last
        available data date)
        """
		numberOfDays = ((date.today() - timedelta(days=1)) - date(2020, 1, 22)).days
		countryCasesDailyMean = np.round(val / numberOfDays)
		return countryCasesDailyMean
	
	def get_plots_for_country(val):
		"""
        Generate a plot for the country entered using the value from countryData
        """
		countryVal = countryData[countryData.Country == val]
		dateVal = dateData
		plt.rcParams['figure.figsize'] = (15,12)
		countryVal.plot(grid=True)
		plt.show(block=False)
	
	# Invoking the necessary methods to get the data needed for the event loop.
	csvFile = read_data_full()
	countryData,dateData = read_data_monthly(csvFile)
	countryData_Jan, countryData_Feb, countryData_Mar, countryData_Apr, countryData_May, \
	countryData_Jun = generate_monthly_data(countryData)
	
	# Event loop for Get data, quit and clear buttons
	while True:
		event, values = window.read()
		if event == 'Get data':
			final_check = 0  # One more check to make sure if the country name is correct,
			# to proceed with all the function invocations for this event
			try:
				countryName = str(values['-countryName-'])
				if countryName in ['United States', 'USA', 'usa', 'United States of America',
				                   'U.S.A', 'u.s.a', 'united states of america', 'u.s.a.', 'us',
				                   'u.s.']:
					countryName = 'US'
					final_check = 1
				if countryName in ['Ivory Coast', 'ivory coast', 'Ivory coast']:
					countryName = 'Cote d\'Ivoire'
					final_check = 1
				if countryName in ['South Korea', 'south korea', 'Korea']:
					countryName = 'Korea, South'
					final_check = 1
				if countryName in ['England', 'Scotland', 'UK', 'U.K.', 'Northern Ireland', 'Wales',
				                   'u.k.', 'uk', 'Great Britain']:
					countryName = 'United Kingdom'
					final_check = 1
				if countryName in ['Holland']:
					countryName = 'Netherlands'
					final_check = 1
				if countryName == 'Congo':
					sg.popup_ok('Please type either [Congo (Brazzaville)] or [Congo (Kinshasa)] '
					            'in your entry')
				check = check_country_name(countryData_Jan, countryName)
				if check == 0:
					sg.popup_error('Country name not found! Please try again.')
				if check > 0:
					final_check = 1
				if not countryName:
					sg.popup_error('Invalid country name!')
			except:
				sg.popup_error('Invalid country name!')
				window['output'].update('')
				window['-countryName-'].update('')
			window['output'].update(countryName)
			if final_check == 1:
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print('Monthly Data')
				print(f'--------------January 2020 ({countryName})------------ \n')
				janSeries = countryData_Jan.loc[[countryName], ['Confirmed', 'Recovered', 'Deaths']]
				print(janSeries)
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print(f'--------------February 2020 ({countryName})------------ \n')
				febSeries = countryData_Feb.loc[[countryName], ['Confirmed', 'Recovered', 'Deaths']]
				print(febSeries)
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print(f'--------------March 2020 ({countryName})------------ \n')
				marSeries = countryData_Mar.loc[[countryName], ['Confirmed', 'Recovered', 'Deaths']]
				print(marSeries)
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print(f'--------------April 2020 ({countryName})------------ \n')
				aprSeries = countryData_Apr.loc[[countryName], ['Confirmed', 'Recovered', 'Deaths']]
				print(aprSeries)
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print(f'--------------May 2020 ({countryName})------------ \n')
				maySeries = countryData_May.loc[[countryName], ['Confirmed', 'Recovered', 'Deaths']]
				print(maySeries)
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print(f'--------------June 2020 ({countryName})------------ \n')
				junSeries = countryData_Jun.loc[[countryName], ['Confirmed', 'Recovered', 'Deaths']]
				print(junSeries)
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
				print('Daily Mean')
				print(f'--------------Daily Mean - To Date ({countryName})------------ \n')
				lastMonthDayVal = generate_daily_mean(junSeries)
				print(lastMonthDayVal)
				if window.FindElement('-Box-').Get():
					get_plots_for_country(countryName)
		if event in ['Clear', None]:
			try:
				countryName = ''
			except:
				sg.popup_ok('An error has occurred.')
			window['-countryName-'].update('')
			window['output'].update('')
			window['-Print-'].update('')
		if event == 'Quit':
			break
예제 #10
0
#!/usr/bin/env python
import sys
if sys.version_info[0] >= 3:
    import PySimpleGUI as sg
else:
    import PySimpleGUI27 as sg

tab1_layout = [[sg.T('This is inside tab 1')]]

tab2_layout = [[sg.T('This is inside tab 2')], [sg.In(key='in')]]

layout = [[
    sg.TabGroup([[sg.Tab('Tab 1', tab1_layout),
                  sg.Tab('Tab 2', tab2_layout)]])
], [sg.RButton('Read')]]

window = sg.Window('My window with tabs',
                   default_element_size=(12, 1)).Layout(layout)

while True:
    b, v = window.Read()
    print(b, v)
    if b is None:  # always,  always give a way out!
        break
예제 #11
0
import PySimpleGUI as sg

layout = [[sg.T(f'Input {i+1}'), sg.In(key=i)] for i in range(10)]
layout += [[sg.Save(), sg.Exit()]]

window = sg.Window('Example ', layout)
event, values = window.read()
window.close()
예제 #12
0
파일: main.py 프로젝트: Thiagojm/RngKitPSG
def main():
    # Mensagem para versão console
    print("""Welcome!
Wait for the application to load!
Do not close this window!""")

    with open("src/others/instructions.txt", "r", encoding="utf8") as f:
        instruction_text = f.read()

    # THEME
    # Good Ones: DarkBlue14, Dark, DarkBlue, DarkBlue3, DarkTeal1, DarkTeal10, DarkTeal9, LightGreen
    sg.theme('LightGreen')

    # TAB 1 - Collect / Analyse

    column_1 = [
        [sg.T("Choose RNG", size=(25, 1))],
        [sg.Radio('BitBabbler', "radio_graph_1", k="bit_ac", default=True)],
        [sg.Radio('TrueRNG', "radio_graph_1", k="true3_ac")],
        [sg.Radio('TrueRNG + BitBabbler', "radio_graph_1", k="true3_bit_ac")],
        [sg.Radio('PseudoRNG', "radio_graph_1", k="pseudo_rng_ac")]
    ]

    column_2 = [[
        sg.T("RAW(0)/XOR (1,2...):", size=(18, 1)),
        sg.InputCombo((0, 1, 2, 3, 4),
                      default_value=0,
                      size=(5, 1),
                      k="ac_combo",
                      enable_events=False,
                      readonly=True),
        sg.T(" ", size=(4, 1))
    ],
                [
                    sg.T("Sample Size (bits):", size=(18, 1)),
                    sg.Input("2048", k="ac_bit_count", size=(6, 1))
                ],
                [
                    sg.T("Sample Interval (s):", size=(18, 1)),
                    sg.Input("1", k="ac_time_count", size=(6, 1))
                ], [sg.T(" ")]]

    column_3 = [[sg.B("Start", k='ac_button', size=(20, 1))], [sg.T("")],
                [
                    sg.T("        Idle",
                         k="stat_ac",
                         text_color="orange",
                         size=(10, 1),
                         relief="sunken")
                ]]

    acquiring_data = [[sg.T(" ")],
                      [
                          sg.Column(column_1),
                          sg.Column(column_2),
                          sg.Column(column_3, element_justification="center")
                      ]]

    data_analysis = [
        [sg.T(" ")],
        [
            sg.T(" ", size=(8, 1)),
            sg.T("Sample Size (bits):", size=(18, 1)),
            sg.Input("2048", k="an_bit_count", size=(6, 1)),
            sg.T(" ", size=(8, 1)),
            sg.T("Sample Interval (s):", size=(18, 1)),
            sg.Input("1", k="an_time_count", size=(6, 1))
        ],
        [sg.T(" ")],
        [
            sg.Text('Select file:', size=(10, 1)),
            sg.Input(size=(60, 1)),
            sg.FileBrowse(key='open_file',
                          file_types=(('CSV and Binary', '.csv .bin'), ),
                          initial_folder="./1-SavedFiles",
                          size=(8, 1)),
            sg.T(" ", size=(13, 1))
        ],
        [
            sg.T(" ", size=(24, 1)),
            sg.B("Generate"),
            sg.T(" ", size=(1, 1)),
            sg.B("Open Output Folder", k="out_folder")
        ],
        [sg.Text('Concatenate Multiple CSV Files')],
        [
            sg.In(),
            sg.FilesBrowse(key='open_files',
                           file_types=(('CSV', '.csv'), ),
                           initial_folder="./1-SavedFiles",
                           size=(8, 1),
                           files_delimiter=","),
            sg.B('Concatenate', k="concat")
        ],
    ]

    tab1_layout = [[
        sg.Frame("Acquiring Data",
                 font="Calibri, 20",
                 layout=acquiring_data,
                 k="acquiring_data",
                 size=(90, 9))
    ],
                   [
                       sg.Frame("Data Analysis",
                                font="Calibri, 20",
                                layout=data_analysis,
                                k="data_analysis",
                                size=(90, 9))
                   ]]

    # TAB 2 - Gráfico
    column_graph_1 = [
        [sg.Radio('BitBabbler', "radio_graph", k="bit_live", default=True)],
        [sg.Radio('TrueRNG3', "radio_graph", k="true3_live")],
        [sg.Radio('PseudoRNG', "radio_graph", k="pseudo_rng_live")]
    ]

    column_graph_2 = [[
        sg.T("RAW(0)/XOR (1,2):", size=(16, 1)),
        sg.InputCombo((0, 1),
                      default_value=0,
                      size=(5, 1),
                      k="live_combo",
                      enable_events=False,
                      readonly=True),
        sg.T(" ", size=(9, 1))
    ],
                      [
                          sg.T("Sample Size (bits):", size=(16, 1)),
                          sg.Input("2048", k="live_bit_count", size=(6, 1))
                      ],
                      [
                          sg.T("Sample Interval (s):", size=(16, 1)),
                          sg.Input("1", k="live_time_count", size=(6, 1))
                      ]]

    column_graph_3 = [[sg.B("Start", k='live_plot', size=(20, 1))], [sg.T("")],
                      [
                          sg.T("        Idle",
                               k="stat_live",
                               text_color="orange",
                               size=(10, 1),
                               relief="sunken")
                      ]]

    graph_options = [[
        sg.Column(column_graph_1),
        sg.Column(column_graph_2),
        sg.Column(column_graph_3, element_justification="center")
    ]]

    live_graph = [[sg.Canvas(key='-CANVAS-')]]

    tab2_layout = [[
        sg.Frame("Options",
                 font="Calibri, 20",
                 layout=graph_options,
                 k="graph_options",
                 size=(90, 9))
    ],
                   [
                       sg.Frame("Live Plot",
                                font="Calibri, 20",
                                layout=live_graph,
                                k="graph",
                                size=(90, 9))
                   ]]

    # TAB 3 - Instruções
    tab3_layout = [[
        sg.T("Instructions",
             relief="raised",
             justification="center",
             size=(70, 1),
             font=("Calibri, 24"))
    ],
                   [
                       sg.Multiline(default_text=instruction_text,
                                    size=(75, 19),
                                    disabled=True,
                                    enable_events=False,
                                    font=("Calibri, 20"),
                                    pad=(5, 5))
                   ]]

    # LAYOUT
    layout = [[
        sg.TabGroup([[
            sg.Tab('Start', tab1_layout),
            sg.Tab('Live Plot', tab2_layout),
            sg.Tab('Instructions', tab3_layout)
        ]],
                    tab_location="top",
                    font="Calibri, 18")
    ]]

    # WINDOW
    window = sg.Window(
        "RngKit ver 2.2 - by Thiago Jung - [email protected]",
        layout,
        size=(1024, 720),
        location=(50, 50),
        finalize=True,
        element_justification="center",
        font="Calibri 18",
        resizable=True,
        icon=("src/images/BitB.ico"))

    # Setting things up!
    canvas_elem = window['-CANVAS-']
    canvas = canvas_elem.TKCanvas
    style.use("ggplot")
    global ax
    f, ax = plt.subplots(figsize=(10, 4.4), dpi=100)
    canvas = FigureCanvasTkAgg(f, canvas)
    canvas.draw()
    canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
    ani = animation.FuncAnimation(f, animate, interval=1000)

    # Creating checker for the splashscreen
    open("src/others/checker", mode='w').close()

    # LOOP
    while True:
        global values
        global thread_cap
        event, values = window.read()
        if event == sg.WIN_CLOSED:  # always,  always give a way out!
            break
        elif event == 'ac_button':
            if not thread_cap:
                if rm.test_bit_time_rate(
                        values["ac_bit_count"],
                        values["ac_time_count"]) and rm.check_usb_cap(values):
                    thread_cap = True
                    threading.Thread(target=ac_data,
                                     args=(values, window),
                                     daemon=True).start()
                    window['ac_button'].update("Stop")
                    window["stat_ac"].update("  Collecting",
                                             text_color="green")
                    window['live_plot'].update("Stop")
                    window["stat_live"].update("  Collecting",
                                               text_color="green")
            else:
                thread_cap = False
                window['ac_button'].update("Start")
                window["stat_ac"].update("        Idle", text_color="orange")
                window['live_plot'].update("Start")
                window["stat_live"].update("        Idle", text_color="orange")

        elif event == "out_folder":
            rm.open_folder()
        elif event == "concat":
            all_files = values['open_files'].split(",")
            rm.concat_files(all_files)
        elif event == "Generate":
            if rm.test_bit_time_rate(values["an_bit_count"],
                                     values["an_time_count"]):
                rm.file_to_excel(values["open_file"], values["an_bit_count"],
                                 values["an_time_count"])
            else:
                pass
        elif event == 'live_plot':
            if not thread_cap:
                if rm.test_bit_time_rate(values["live_bit_count"],
                                         values["live_time_count"]
                                         ) and rm.check_usb_live(values):
                    thread_cap = True
                    ax.clear()
                    threading.Thread(target=live_plot,
                                     args=(values, window),
                                     daemon=True).start()
                    window['live_plot'].update("Stop")
                    window["stat_live"].update("  Collecting",
                                               text_color="green")
                    window['ac_button'].update("Stop")
                    window["stat_ac"].update("  Collecting",
                                             text_color="green")
            else:
                thread_cap = False
                window['live_plot'].update("Start")
                window["stat_live"].update("        Idle", text_color="orange")
                window['ac_button'].update("Start")
                window["stat_ac"].update("        Idle", text_color="orange")

    window.close()
예제 #13
0
import PySimpleGUI as sg

col = [[sg.Text('Col Row 1')]] + [
    [sg.T(f'Col Row {i+2}'), sg.In(f'col input {i+1}')] for i in range(10)
]

layout = [[
    sg.Slider(range(1, 100), default_value=10, orientation='v', size=(8, 20)),
    sg.Column(col)
], [sg.In('Last Input')], [sg.OK()]]

window = sg.Window('Column layout', layout)
event, values = window.read()

window.close()
sg.popup(event, values, line_width=200)
예제 #14
0
print("OMSI Map Merger " + version.version)


def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


directories_layout = [
    [
        sg.Text("Map 1 directory"),
        sg.In(key="map1_directory"),
        sg.FolderBrowse()
    ],
    [
        sg.Text("Map 2 directory"),
        sg.In(key="map2_directory"),
        sg.FolderBrowse()
    ],
]
layout = [
    [
        sg.Column(directories_layout),
        sg.Image(
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "gplv3-with-text-136x68.png"))
    ], [
예제 #15
0
import PySimpleGUI as sg
import os

sg.theme('DarkAmber')  # Add a touch of color
# All the stuff inside your window.
layout = [[sg.T('Video File Location')],
          [sg.In(), sg.FileBrowse(target=(1, 0))], [sg.T('   ')],
          [sg.T('1st Subtitle File')], [sg.In(),
                                        sg.FileBrowse(target=(4, 0))],
          [sg.T('   ')], [sg.T('2nd Subtitle File')],
          [sg.In(), sg.FileBrowse(target=(7, 0))], [sg.T('   ')],
          [sg.T('Secondary Subtitle Index')], [sg.In(default_text="2")],
          [sg.OK()]]

# Create the Window
window = sg.Window('Dual Subtitle With MPV',
                   icon='vid-icon.ico').Layout(layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Cancel':  # if user closes window or clicks cancel
        break

    for i in values:
        print(i, values[i])

    print('mpv "' + values[0] + '" --sub-file="' + values[1] +
          '" --sub-file="' + values[2] + '" --secondary-sid=' + values[3])
    os.popen('mpv "' + values[0] + '" --sub-file="' + values[1] +
             '" --sub-file="' + values[2] + '" --secondary-sid=' + values[3])
예제 #16
0
sg.ChangeLookAndFeel('Dark')
sg.SetOptions(element_padding=(0, 0))

layout = [[
    sg.T('User:'******'User 1', 'User 2'), size=(20, 1)),
    sg.T('0', size=(8, 1))
],
          [
              sg.T('Customer:', pad=((3, 0), 0)),
              sg.OptionMenu(values=('Customer 1', 'Customer 2'), size=(20, 1)),
              sg.T('1', size=(8, 1))
          ],
          [
              sg.T('Notes:', pad=((3, 0), 0)),
              sg.In(size=(44, 1), background_color='white', text_color='black')
          ],
          [
              sg.ReadFormButton('Start',
                                button_color=('white', 'black'),
                                key='start'),
              sg.ReadFormButton('Stop',
                                button_color=('gray34', 'black'),
                                key='stop'),
              sg.ReadFormButton('Reset',
                                button_color=('gray', 'firebrick3'),
                                key='reset'),
              sg.ReadFormButton('Submit',
                                button_color=('gray34', 'springgreen4'),
                                key='submit')
          ]]
        print(sleep)
        time.sleep(sleep)


# Create an event loop
scroll = []
t = 0
pattern = []
sleep = 100
t1 = None

button = sg.Button("PLAY")
bpm = sg.InputText('-1', size=(15, 1))

layout = [
    [sg.In(), sg.FileBrowse(file_types=(("Midi", "*.mid"), ))],
    [
        sg.Button("COMPUTE"),
        sg.Text('Semitone shift'),
        sg.InputText('0', size=(2, 1))
    ],
    [button],
    [sg.Text('Made by: TENTEN youtube.com/c/TenTenGaming/')],
    [sg.Checkbox('Play blackkey as whitekey above', default=False)],
    [sg.Text('TICK rate override'), bpm],
    #[sg.Image('venti.png')],
]
# Create the window
window = sg.Window("Tenten Genshin Lyre player", layout)

#thread stopping bool
예제 #18
0
def main(mask_rate=0.7):
    """"
    The Main GUI - It does it all.

    The "Board" is a grid that's 9 x 9.  Even though the layout is a grid of 9 Frames, the
    addressing of the individual squares is via a key that's a tuple (0,0) to (8,8)
    """

    # It's 1 line of code to make a Sudoku board.  If you don't like it, then replace it.
    # Dude (Dudette), it's 1-line of code.  If you don't like the board, write a line of code.
    # The keys for the inputs are tuples (0-8, 0-8) that reference each Input Element.
    # Get an input element for a position using:    window[row, col]
    # To get a better understanding, take it apart. Spread it out. You'll learn in the process.
    window = sg.Window('Sudoku',
                       [[
                           sg.Frame('', [[
                               sg.I(random.randint(1, 9),
                                    justification='r',
                                    size=(3, 1),
                                    enable_events=True,
                                    key=(fr * 3 + r, fc * 3 + c))
                               for c in range(3)
                           ] for r in range(3)]) for fc in range(3)
                       ] for fr in range(3)] + [
                           [
                               sg.B('Solve'),
                               sg.B('Check'),
                               sg.B('Hint'),
                               sg.B('New Game'),
                               sg.T('Mask rate (0-1)'),
                               sg.In(str(mask_rate), size=(3, 1), key='-RATE-')
                           ],
                       ],
                       finalize=True)

    # create and display a puzzle by updating the Input elements

    puzzle, solution = create_and_show_puzzle(window)
    check_showing = False
    while True:  # The Event Loop
        event, values = window.read()
        if event == sg.WIN_CLOSED:
            break

        if event == 'Solve':
            for r, row in enumerate(solution):
                for c, col in enumerate(row):
                    window[r, c].update(
                        solution[r][c],
                        background_color=sg.theme_input_background_color())
        elif event == 'Check':
            check_showing = True
            solved = check_progress(window, solution)
            if solved:
                sg.popup('Solved! You have solved the puzzle correctly.')
        elif event == 'Hint':
            elem = window.find_element_with_focus()
            try:
                elem.update(solution[elem.Key[0]][elem.Key[1]],
                            background_color=sg.theme_input_background_color())
            except:
                pass  # Likely because an input element didn't have focus
        elif event == 'New Game':
            puzzle, solution = create_and_show_puzzle(window)
        elif check_showing:  # an input was changed, so clear any background colors from prior hints
            check_showing = False
            for r, row in enumerate(solution):
                for c, col in enumerate(row):
                    window[r, c].update(
                        background_color=sg.theme_input_background_color())
    window.close()
"""
    Demo program that shows you how to integrate the PySimpleGUI Debugger
    into your program.
    There are THREE steps, and they are copy and pastes.
    1. At the top of your app to debug add
            import PySimpleGUIdebugger
    2. Initialize the debugger by calling:
            PySimpleGUIdebugger.initialize()
    2. At the top of your app's event loop add
            PySimpleGUIdebugger.refresh(locals(), globals())
"""


layout = [
            [sg.T('A typical PSG application')],
            [sg.In(key='_IN_')],
            [sg.T('        ', key='_OUT_')],
            [sg.Radio('a',1, key='_R1_'), sg.Radio('b',1, key='_R2_'), sg.Radio('c',1, key='_R3_')],
            [sg.Combo(['c1', 'c2', 'c3'], size=(6,3), key='_COMBO_')],
            [sg.Output(size=(50,6))],
            [sg.Ok(), sg.Exit()],
        ]


window = sg.Window('This is your Application Window', layout)
# Variables that we'll use to demonstrate the debugger's features
counter = 0
timeout = 100
PySimpleGUIdebugger.initialize()

while True:             # Event Loop
예제 #20
0
import PySimpleGUI as sg
"""
    Extending PySimpleGUI using the tkinter event bindings

    The idea here is to enable you to receive tkinter "Events" through the normal place you
    get your events, the window.read() call.

    Both elements and windows have a bind method.
    window.bind(tkinter_event_string, key)   or   element.bind(tkinter_event_string, key_modifier)
    First parameter is the tkinter event string.  These are things like <FocusIn> <Button-1> <Button-3> <Enter>
    Second parameter for windows is an entire key, for elements is something added onto a key.  This key or modified key is what is returned when you read the window.
    If the key modifier is text and the key is text, then the key returned from the read will be the 2 concatenated together.  Otherwise your event will be a tuple containing the key_modifier value you pass in and the key belonging to the element the event happened to.
"""
sg.theme('Dark Blue 3')

layout = [[sg.Text('Move mouse over me', key='-TEXT-')], [sg.In(key='-IN-')],
          [sg.Button('Right Click Me', key='-BUTTON-'),
           sg.Button('Exit')]]

window = sg.Window('Window Title', layout, finalize=True)

window.bind('<FocusOut>', '+FOCUS OUT+')

window['-BUTTON-'].bind('<Button-3>', '+RIGHT CLICK+')
window['-TEXT-'].bind('<Enter>', '+MOUSE OVER+')
window['-TEXT-'].bind('<Leave>', '+MOUSE AWAY+')
window['-IN-'].bind('<FocusIn>', '+INPUT FOCUS+')

while True:  # Event Loop
    event, values = window.read()
    print(event, values)
예제 #21
0
						  )
	while True:
		downtime_event, downtime_values = downtime_window.read()

		if downtime_event == '-LOG SAVE-':
			database.save_to_downtime(downtime_values['-VOYAGE-'], downtime_values['-STOP-'], downtime_values['-START-'], downtime_values['-REASON-'], downtime_values['-ASSOSCIATED ERROR-'])
			downtime_window.close()
			break

		# If the user closes the window, exit this loop so that the program can close
		if downtime_event == sg.WIN_CLOSED or downtime_event == '-LOG CANCEL-':
			downtime_window.close()
			break

# Main window layout
main_column_1 = sg.Column([[sg.Frame('Advanced search', [[sg.Column([[sg.Text("Voyage: ", tooltip = "Let me know which voyage you'd like to see the errors for."), sg.In(size = (15, 1), pad = ((34, 0), (0, 0)), key = '-VOYAGE SEARCH-')],
																[sg.Text("Status: ", tooltip = "Would you like to look at errors we've already solved? Let me know here!"), sg.In(size = (15, 1), pad = ((40, 0), (0, 0)), key = '-STATUS SEARCH-')],
																[sg.Text("Fault type: ", tooltip = "Here you can let me know what type of fault you'd like to search for."), sg.In(size = (15, 1), pad = ((20, 0), (0, 0)), right_click_menu = ("Cable", "Hardware", "Sensor", "Connector"), key = '-TYPE SEARCH-')],
																[sg.Text("Fault location: ", tooltip = "If you suspect that your fault might be location-specific, say so here to see previous errors that have occurred in that location."), sg.In(size = (15, 1), pad = ((0, 0), (0, 0)), key = '-LOCATION SEARCH-')],
																[sg.Text("Sensor ID: ", tooltip = "Think that your error could be sensor-specific? Find previous issues with your exact sensor by entering it's asset number here."), sg.In(size = (15, 1), pad = ((21, 0), (0, 0)), key = '-SENSOR ID SEARCH-')],
																[sg.Text("Sensor type: ", tooltip = "Search for previous errors that have been encountered with your specific type of sensor."), sg.In(size = (15, 1), pad = ((8, 0), (0, 0)), key = '-SENSOR TYPE SEARCH-')],
																[sg.Text("From: ", tooltip = "Enter the start date for your search."), sg.In(size = (15, 1), tooltip = "dd-mm-yy hh:mm:ss", pad = ((48, 0), (0, 0)), key = '-FROM SEARCH-')],
																[sg.Text("To: ", tooltip = "Enter the end date for your search."), sg.In(size = (15, 1), tooltip = "dd-mm-yy hh:mm:ss", pad = ((64, 0), (0, 0)), key = '-TO SEARCH-')],
																[sg.Button("Search errors", size = (12, 1), pad = ((93, 0), (7, 0)), enable_events=True, tooltip = "Press me if you'd like to search for specific error characteristics.",key = '-SEARCH ERROR-')]], pad = (3, 3))]])]])


main_column_2 = sg.Column([[sg.Frame('Faults:', [[sg.Column([[sg.Listbox(unresolved_errors, enable_events = True, size=(20, len(unresolved_errors)), key = '-ERROR LIST-')]]),
														sg.Column([[sg.Text("Error ID: ", size=(14,1)), sg.Text("", size=(20,1), key='-OUT ID-')],
																   [sg.Text("Error Description: ", size=(14,15)), sg.Multiline("", size=(20,15), key='-OUT DESC-')],
																   ]) ],
													   [sg.Button("Update", enable_events = True, tooltip = "Press me if you'd like to update some of the information about the selected error.", key = '-UPDATE ERROR-'),
예제 #22
0
# blocked
# plusMinus
# points
# shifts

stats = ['games', 'assists', 'goals', 'pim', 'shots', 'hits',
         'powerPlayGoals', 'powerPlayPoints',
         'gameWinningGoals', 'overTimeGoals', 'shortHandedGoals', 'blocked',
         'plusMinus', 'points', 'shifts']
layout = [[sg.Text("Stat Multipliers")]]

text_column = []
input_column = []
for stat in stats:
    text_column.append([sg.Text(stat)])
    input_column.append([sg.In(key=stat)])

output_file_row = [sg.Text("Output File Name:   "), sg.In(key="output")]
games_played_row = [sg.Text("Min Games Played: "), sg.In(key="games_played")]
per_game_row = [sg.Checkbox(key="per_game", text="Per Game Mode")]

layout.append([sg.Column(text_column), sg.Column(input_column)])
layout.append([sg.Text("")])
layout.append(games_played_row)
layout.append(output_file_row)
layout.append(per_game_row)
layout.append([sg.Button("Submit")])

window = sg.Window("Fantasy Hockey Player Tool", layout)

scraper = NhlScrape()
예제 #23
0
    for i in range(N):
        curr_bound += (firstMin(adj, i) + secondMin(adj, i))

    curr_bound = math.ceil(curr_bound / 2)

    visited[0] = True
    curr_path[0] = 0

    TSPRec(adj, curr_bound, 0, 1, curr_path, visited)


if len(sys.argv) == 1:
    event1, values1 = sg.Window(
        'Branch and Bound',
        [[sg.Text('Choose a file')], [sg.In(), sg.FileBrowse()],
         [sg.Open(), sg.Cancel()]]).read(close=True)
    fname = values1[0]

else:
    fname = sys.argv[1]

if not fname:
    raise SystemExit("Cancelling: no filename supplied...")

f = open(fname, "r")
if f.mode == 'r':
    contents = f.read()
    contents = re.split(r'[,\s]\s*', contents)

a = contents[0::4]
예제 #24
0
import PySimpleGUI as sg

kolom1=[
    [sg.In(size=(40,1),key='-INPUT-')],
    [sg.Button('Tombol Ganti Text',key='-TOMBOL1-')],
    [sg.Submit('Submit')]
]
kolom2=[
    [sg.Text('Text akan berubah',key='-TEXT-')],
]
layout=[
    [sg.Column(kolom1)],
    [sg.VSeparator()],
    [sg.Column(kolom2)]
]

window=sg.Window('Tes UI',layout)

while True:
    event, values = window.read()
    if event=='EXIT' or event==sg.WIN_CLOSED:
        break
    if event=='-TOMBOL1-':
        text=values['-INPUT-']
        window['-TEXT-'].update(text)

window.close()
예제 #25
0
import PySimpleGUI as sg
# Set Program Theme
sg.theme('LightTeal')

# Set up the layout
layout = [[sg.Checkbox(''), sg.T('1.'),
           sg.In(key=1)], [sg.Checkbox(''),
                           sg.T('2.'),
                           sg.In(key=2)],
          [sg.Checkbox(''), sg.T('3.'),
           sg.In(key=3)], [sg.Checkbox(''),
                           sg.T('4.'),
                           sg.In(key=4)], [sg.Button('Exit')]]

# Set up the window
window = sg.Window('To Do', layout)

# Listen for Window Close
while True:
    event, values = window.read()
    print(event, values)
    if event == sg.WIN_CLOSED() or event == 'Exit':
        break

window.close()
예제 #26
0
import PySimpleGUI as sg

kolom1 = [[sg.In(size=(40, 1), key="-INPUT-")],
          [sg.Button("Tombol Ganti Text", key="-TOMBOL1-")],
          [sg.Submit("Submit")]]

kolom2 = [[sg.Text("Text ini bakal berubah", key="-TEXT-")],
          [sg.HorizontalSeparator()]]

layout = [[sg.Column(kolom1), sg.VSeparator(), sg.Column(kolom2)]]

window = sg.Window("Tes UI", layout)

while True:
    event, values = window.read()

    if event == "Exit" or event == sg.WIN_CLOSED:
        break

    if event == "-TOMBOL1-":
        text = values["-INPUT-"]
        window["-TEXT-"].update(text)

window.close()
예제 #27
0
파일: gui.py 프로젝트: alesplana/rm-mapping
def main_process():
    layout = [
        [sg.Text('STEP 1: File processing', font=headFont)],
        [sg.Text('Select file for processing', font=head2Font, size=(30, 2))],
        [
            sg.In(visible=False),
            sg.Input(key='-DIR-', enable_events=True, visible=False),
            sg.Text('                             ',
                    key='-FILENAME-',
                    size=(20, 1)),
            sg.FileBrowse('Browse',
                          target='-DIR-',
                          size=(10, 1),
                          file_types=(("Text Files", "*.txt"), ("CSV Files",
                                                                "*.csv"))),
            sg.Button('Open',
                      button_color=('white', 'red'),
                      size=(8, 1),
                      key='_OPEN_',
                      disabled=True)
        ],
        [
            sg.In(visible=False),
            sg.Input(key='_PCSV_', enable_events=True, visible=False),
            sg.Text('                             ',
                    key='-FN_2-',
                    size=(20, 1)),
            sg.FileSaveAs("Save File As",
                          target='_PCSV_',
                          size=(20, 1),
                          button_color=('white', 'green'),
                          disabled=True,
                          key='-PCSV-'),
            sg.Button('Save',
                      button_color=('white', 'green'),
                      size=(10, 1),
                      key='_SAVECSV_',
                      visible=False)
        ],
        [
            sg.Text('_' * 100,
                    justification='center',
                    text_color='gray',
                    size=(100, 2))
        ],  # horizontal separator
        [sg.Text('STEP 2: Run Principal Component Analysis', font=headFont)],
        [
            sg.Text('Initial PCA Run (20 components)',
                    font=head2Font,
                    size=(25, 1)),
            sg.Button('Open Scree Plot',
                      button_color=('white', '#e7b416'),
                      key='_PCA1_',
                      size=(23, 1),
                      disabled=True),
            sg.Button('Open Scree Plot',
                      key='_FIG_OPEN1_',
                      disabled=True,
                      size=(15, 1),
                      visible=False)
        ],
        [
            sg.Text('Number of Principal Components:',
                    font=head2Font,
                    size=(25, 1)),
            sg.Combo(list(range(2, 21)),
                     size=(5, 2),
                     key='_NCOM_',
                     enable_events=True),
            sg.Button('Run PCA',
                      button_color=('white', 'green'),
                      key='_PCA2_',
                      size=(15, 1),
                      disabled=True),
            sg.Button('Open Fig',
                      key='_FIG_OPEN2_',
                      disabled=True,
                      size=(10, 1),
                      visible=False)
        ],
        [
            sg.Text('_' * 100,
                    justification='center',
                    text_color='gray',
                    size=(100, 2))
        ],  # horizontal separator
        [sg.Text('STEP 3: Cluster using K-Means', font=headFont)],
        [
            sg.Text(
                'Identify the optimal value for k using the total distance vs k value graph.'
            )
        ],
        [
            sg.Button('Show Graph',
                      key='-KGRAPH-',
                      size=(15, 1),
                      disabled=True,
                      button_color=('white', 'green'))
        ],
        [
            sg.Text('                             ', size=(20, 1)),
        ],
        [
            sg.Text('K-Value:', font=head2Font, size=(7, 1)),
            sg.Combo(list(range(1, 11)),
                     size=(6, 2),
                     key='_KVAL_',
                     enable_events=True),
            sg.Text(' '),
            sg.Button('Pick Colors', key='-COLORS-')
        ],
        [
            sg.Button('Run K-Means',
                      key='-KMEANS-',
                      size=(15, 1),
                      disabled=True,
                      button_color=('white', 'green')),
            sg.Button('Open Clustered Figure',
                      key='_FIG_OPEN3_',
                      disabled=True,
                      size=(20, 1)),
            sg.Button('Show Cluster Averages',
                      key='_FIG_OPEN4_',
                      disabled=True,
                      size=(20, 1))
        ],
        # [sg.ColorChooserButton('Pick Color', key='color')],
        [
            sg.Input(key='-DIR_RES-', enable_events=True, visible=False),
            sg.Button('Save Result',
                      button_color=('white', 'green'),
                      size=(15, 1),
                      key='_SAVERES_',
                      disabled=True)
        ],
        [
            sg.Text('                             ', size=(20, 1)),
        ],
        [
            sg.Text('                             ', size=(20, 1)),
        ],
        [
            sg.Text('                             ', size=(20, 1)),
        ],
        [sg.Button('Exit')],
    ]

    main_window = sg.Window('EZ PCA KMeans Processor',
                            layout,
                            grab_anywhere=False,
                            size=(500, 530),
                            return_keyboard_events=True,
                            finalize=True)

    main_window['_SAVECSV_'].update(disabled=True)
    save_handl = False

    reset = 0
    globals()['colors'] = []
    thread_run = 0

    while True:
        event, values = main_window.read()
        file_path = Path(values['-DIR-']).expanduser().resolve()
        fn_1 = os.path.basename(values['-DIR-'])
        fn_2 = os.path.basename(values['_PCSV_'])
        # print(event, values)
        main_window.element('-FILENAME-').Update(fn_1)
        main_window.element('-FN_2-').Update(fn_2)

        if save_handl and not fn_2 == '':
            main_window['_SAVECSV_'].update(disabled=False)
        if not fn_1 == '':
            main_window['_OPEN_'].update(disabled=False)
        # window event handling
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        if event == '-DIR-':
            reset = 1
        if event == '_OPEN_':
            reset = 1
            values['-THREAD-'] = '** WAIT **'
            thread_run = 1
            threading.Thread(target=open_and_convert,
                             args=(main_window, values['-DIR-']),
                             daemon=True).start()
        if event == '-THREAD-' and values['-THREAD-'] == "** DONE **":
            reset = 0
            thread_run = 0
            save_handl = True
            main_window['-PCSV-'].update(disabled=False)
            main_window['_PCA1_'].update(disabled=False)
            main_window['_PCA2_'].update(disabled=False)
        if event == '-THREAD-' and values['-THREAD-'] == "Error 1":
            reset = 0
            thread_run = 0
            sg.popup_ok('Invalid File!', font=headFont)
        if event == '_PCA1_':
            pca1_fig = pca_i(globals()['new_csv'])
            pca1_fig.show()
        if event == '_PCA2_':
            try:
                scores = pca_f(globals()['new_csv'], values['_NCOM_'])
                main_window['_FIG_OPEN2_'].update(disabled=False)
                main_window['_FIG_OPEN1_'].update(disabled=True)
                main_window['-KMEANS-'].update(disabled=False)
                main_window['-KGRAPH-'].update(disabled=False)
            except TypeError:
                sg.PopupOK('Specify number of principal components!',
                           title='PCA error')
        if event == '_KVAL_':
            globals()['colors'] = ''
        if event == '-KGRAPH-':
            kgraph_fig = kgraph_(scores)
            kgraph_fig.show()
        if event == '-KMEANS-':
            try:
                res_, clc_, dist = kmeans_(values['_KVAL_'], scores)
                res = res_.join(dist)
                print('Cluster Centers: ' + str(clc_))
                result_csv_ = res_vbose(globals()['new_csv'], res)
                result_csv = res_vbose(globals()['new_csv'], res_)
                main_window['_SAVERES_'].update(disabled=False)
                main_window['_FIG_OPEN3_'].update(disabled=False)
                main_window['_FIG_OPEN4_'].update(disabled=False)
            except TypeError:
                sg.PopupOK('Set number of clusters!', title='K-Means error')
        if event == '-COLORS-':
            try:
                color_picker(values['_KVAL_'])
            except TypeError:
                sg.PopupOK('Specify number of clusters!', title='Error!')
        if event == '_FIG_OPEN3_':
            if globals()['colors'].count('') > 0 or globals(
            )['colors'] == [] or globals()['colors'].count('None') > 0:
                sg.PopupOK('No color set. Click Pick Color button first!',
                           title='No Colors Passed')
            else:
                km_fig = gen_map(globals()['new_csv'], res_,
                                 globals()['colors'], 100)
                km_fig.show()
                km_fig.savefig(
                    file_path.with_suffix('.map-k' + str(values['_KVAL_']) +
                                          '.svg'),
                    transparent=True,
                    bbox_inches='tight')
                km_fig.savefig(
                    file_path.with_suffix('.map-k' + str(values['_KVAL_']) +
                                          '-transparent.png'),
                    transparent=True,
                    bbox_inches='tight')
        if event == '_FIG_OPEN4_':
            if globals()['colors'].count('') > 0 or globals(
            )['colors'] == [] or globals()['colors'].count(None) > 0:
                color_temp = []
                for i in range(values['_KVAL_']):
                    color = '#{:02x}{:02x}{:02x}'.format(
                        random.randint(0, 255), random.randint(0, 255),
                        random.randint(0, 255))
                    color_temp.append(color)
                cl_avg = clavg_fig(result_csv, values['_KVAL_'], color_temp,
                                   50)
            else:
                cl_avg = clavg_fig(result_csv, values['_KVAL_'],
                                   globals()['colors'], 100)
            cl_avg.show()
            cl_avg.savefig(
                file_path.with_suffix('.map-k' + str(values['_KVAL_']) +
                                      '-avg.svg'))
        if event == '_PCSV_' and not values['_PCSV_'] in ('', None):
            globals()['new_csv'].to_csv(values['_PCSV_'], index=False)
        if event == '_SAVERES_':
            result_csv_.to_csv(
                file_path.with_suffix('.map-k' + str(values['_KVAL_']) +
                                      '.csv'),
                index=False)
        if event == '_FIG_OPEN1_':
            pca1_fig.show()

        if reset == 1:  # window reset
            main_window['-PCSV-'].update(disabled=True)
            main_window['_PCA1_'].update(disabled=True)
            main_window['_PCA2_'].update(disabled=True)
            main_window['-KMEANS-'].update(disabled=True)
            main_window['-KGRAPH-'].update(disabled=True)
            main_window['_FIG_OPEN3_'].update(disabled=True)
            main_window['_FIG_OPEN4_'].update(disabled=True)
        if thread_run == 1:
            sg.PopupAnimated(sg.DEFAULT_BASE64_LOADING_GIF,
                             background_color='white',
                             time_between_frames=1)
        elif thread_run == 0:
            sg.PopupAnimated(None)

    main_window.close()
예제 #28
0
파일: help.py 프로젝트: cailaixiu/cailaixiu
def Launcher():
    sg.theme('DarkAmber')
    contact = ''
    cell = ''
    layout = [[
        sg.Text('IT',
                size=(2, 1),
                justification='center',
                auto_size_text=True,
                text_color='white'),
        sg.Button('报修', key='-HELP-', focus=False, size=(4, 1))
    ]]
    window = sg.Window('才来修',
                       layout,
                       location=(max_width, 100),
                       no_titlebar=True,
                       grab_anywhere=True,
                       keep_on_top=True,
                       element_padding=(0, 0),
                       margins=(0, 0))
    win2_active = False
    counter = 0
    while True:
        event, values = window.read(timeout=500)
        counter += 1

        to_be_fixed = (Ticket.select().where(Ticket.is_fixed == False).count())
        if to_be_fixed > 0 and counter % 10 == 0:
            try:
                r = requests.get(host + '/poll/' + str(get_mac()),
                                 timeout=0.5).json()
                for x in r:
                    Ticket.update(
                        is_fixed=True, ack=x['ack'],
                        rat=x['rat']).where(Ticket.tid == x['_id']).execute()
            except Exception as e:
                pass

        to_be_confirmed = (
            Ticket.select().where((Ticket.is_confirmed == False)
                                  & (Ticket.is_fixed == True)).count())

        if to_be_confirmed > 0:
            if (counter % 2 == 0):
                window['-HELP-'].update(
                    button_color=(sg.theme_text_color(),
                                  sg.theme_element_background_color()))
            else:
                window['-HELP-'].update(button_color=('black', 'orange'))

        if event is None:
            break
        if event == '-HELP-' and not win2_active:
            try:
                scope = ''
                r = requests.get(host + '/scopes', timeout=0.5).json()
                scopes = r
                layoutScopes = []
                for i in range(math.ceil(len(scopes) / 4)):
                    rows = []
                    for j in range(4):
                        idx = i * 4 + j
                        if (idx < len(scopes)):
                            s = scopes[idx]
                            rows.append(
                                sg.Radio(s['scope'],
                                         "SCP",
                                         size=(8, 1),
                                         auto_size_text=True,
                                         enable_events=True,
                                         key='scp_' + str(idx)))

                    layoutScopes += [rows]

                win2_active = True

                if to_be_confirmed > 0:
                    row = Ticket.get(Ticket.is_confirmed == False,
                                     Ticket.is_fixed == True)
                    layout_ask = [[
                        sg.Text(row.body, text_color='white', pad=(5, 10))
                    ], [sg.Text('时间:' + row.at, text_color='silver')]]
                    layout_ack = [[
                        sg.Text(row.ack, text_color='white', pad=(5, 10))
                    ], [sg.Text('时间:' + row.rat, text_color='silver')]]
                    layout2 = [[sg.Frame('报修问题', layout_ask)],
                               [sg.Frame('回复内容', layout_ack)],
                               [
                                   sg.Button('确认',
                                             bind_return_key=True,
                                             font=('Verdana', 16))
                               ]]
                    win2 = sg.Window('回复确认', layout2)
                    while True:
                        ev2, vals2 = win2.Read()
                        if ev2 is None or ev2 == '确认':
                            Ticket.update(is_confirmed=True).where(
                                Ticket.tid == row.tid).execute()
                            win2.close()
                            win2_active = False
                            break

                else:
                    img = pyautogui.screenshot()
                    img_bytes = io.BytesIO()
                    try:
                        img.save(img_bytes, format='PNG')
                        base64_data = codecs.encode(img_bytes.getvalue(),
                                                    'base64')
                        base64_text = codecs.decode(base64_data, 'ascii')
                    except Exception as e:
                        base64_text = ''

                    layout2 = [[
                        sg.Text('报修电话...',
                                auto_size_text=False,
                                justification='center',
                                text_color='black',
                                background_color='white',
                                key='-CALL-')
                    ], [sg.Text('问题简述(电话通不通,都麻烦填一下)')], [sg.In(key='-ASK-')],
                               [sg.Text('联系人姓名', text_color='white')],
                               [sg.In(contact, key='-CONTACT-')],
                               [sg.Text('联系人手机', text_color='white')],
                               [sg.In(cell, key='-CELL-')],
                               [
                                   sg.Checkbox('自动截屏',
                                               key='-SCRN-',
                                               default=True)
                               ], [sg.Button('提交', bind_return_key=True)]]
                    layout2 = layoutScopes + layout2
                    win2 = sg.Window('报修内容', layout2, font=('Verdana', 16))
                    while True:
                        ev2, vals2 = win2.Read()
                        if ev2 is None:
                            win2.close()
                            win2_active = False
                            break
                        if ev2.startswith('scp_'):
                            idx = int(ev2.split('_')[1])
                            win2['-CALL-'](
                                value=','.join(scopes[idx]['phones']))
                            scope = scopes[idx]['scope']

                        if ev2 == '提交':
                            ask = vals2['-ASK-'].strip()
                            if scope is '':
                                sg.popup('请选择报修范围')
                                continue
                            if len(ask) == 0:
                                sg.popup('问题不能为空')
                            elif len(ask) > 100:
                                sg.popup('问题不需太长')
                            else:
                                contact = vals2['-CONTACT-'].strip()
                                cell = vals2['-CELL-'].strip()
                                if vals2['-SCRN-'] is False:
                                    base64_text = ''

                                payload = {
                                    'img': base64_text,
                                    'scope': scope,
                                    'ask': ask,
                                    'mac': get_mac(),
                                    'contact': contact,
                                    'cell': cell
                                }

                                try:
                                    r = requests.post(host + '/api/help',
                                                      data=payload,
                                                      timeout=1.5).json()
                                    if (r['msg'] == '成功'):
                                        Ticket.create(tid=r['_id'],
                                                      body=ask,
                                                      at=r['at'])

                                        url = "https://cailaixiu.com/v/" + r[
                                            'nid'] + "/" + r['tid'] + "/" + r[
                                                'key'] + "/" + str(
                                                    r['_id']
                                                ) + "/" + cell + "/" + ask
                                        qr_img = qrcode.make(url)
                                        out = qr_img.resize((160, 160))
                                        qr_img_bytes = io.BytesIO()
                                        out.save(qr_img_bytes, format='PNG')
                                        qr_data = codecs.encode(
                                            qr_img_bytes.getvalue(), 'base64')

                                        if cell is '':
                                            sg.popup_auto_close(
                                                '报修成功。填写手机号可能获取报修奖励!')
                                        else:
                                            layout3 = [
                                                [sg.Text('手机扫码,获取报修奖励')],
                                                [sg.Image(data=qr_data)],
                                                [
                                                    sg.Button(
                                                        '关闭',
                                                        bind_return_key=True,
                                                        font=('Verdana', 16))
                                                ]
                                            ]
                                            sg.Window('报修成功',
                                                      layout3).read(close=True)
                                    else:
                                        sg.popup('报修失败!原因为' + r['msg'])

                                    win2.close()
                                    win2_active = False
                                except Exception as e:
                                    sg.popup('服务不可用,请稍后再试!')

            except Exception as e:
                sg.popup('服务不可用,请稍后再试!')

    window.close()
예제 #29
0
파일: si100.py 프로젝트: gbroiles/si100
def main():
    """ main event loop """
    global OUTPUT_PDF_PATH
    global INPUT_PDF_PATH

    ANNOT_KEY = "/Annots"
    ANNOT_FIELD_KEY = "/T"
    #    ANNOT_VAL_KEY = "/V"
    #    ANNOT_RECT_KEY = "/Rect"
    SUBTYPE_KEY = "/Subtype"
    WIDGET_SUBTYPE_KEY = "/Widget"

    def fill_dict(values):
        data = {}
        for key in values.keys():
            #            print(key)
            #        pprint.pprint(values)
            #        data["2EntityName"] = values["2EntityName"]
            #        data["2EntityNumber"] = values["2EntityNumber"]
            if values[key]:
                data[key] = values[key]
                print(key, "=", data[key])
        return data

    def fill_form(data_dict):
        template_pdf = pdfrw.PdfReader(INPUT_PDF_PATH)
        for page in range(len(template_pdf.pages)):
            annotations = template_pdf.pages[page][ANNOT_KEY]
            for annotation in annotations:
                if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
                    if annotation[ANNOT_FIELD_KEY]:
                        key = annotation[ANNOT_FIELD_KEY][1:-1]
                        if key in data_dict.keys():
                            annotation.update(
                                pdfrw.PdfDict(V="{}".format(data_dict[key])))
                            annotation.update(pdfrw.PdfDict(Ff=1))
        return template_pdf

    phy_addr_layout = [
        [sg.T("Street address:"),
         sg.In(key="3aAddress")],
        [
            sg.T("ZIP:"),
            sg.In(key="3aZIP", size=(11, 1), enable_events=True),
            sg.T("City:"),
            sg.In(key="3aCity"),
            sg.T("State: CA*"),
            sg.In("CA", key="3aState", visible=False),
        ],
        [sg.T("* State must be California")],
    ]

    mail_addr_layout = [
        [
            sg.Button("Copy from physical address", key="Copy_mail_Addr"),
        ],
        [
            sg.T("Street address:"),
            sg.In(key="3bAddress"),
        ],
        [
            sg.T("ZIP:"),
            sg.In(key="3bZIP", size=(11, 1)),
            sg.T("City:"),
            sg.In(key="3bCity"),
            sg.T("State:"),
            sg.Combo(statelist, key="3bState", size=(3, 1)),
        ],
    ]

    tab1_layout = [
        [sg.T("Corporation name:"),
         sg.In(key="corpname")],
        [sg.T("SOS File No:"), sg.In(key="SOS_file_num")],
        [sg.Frame("Physical address", phy_addr_layout)],
        [sg.Frame("Mailing address", mail_addr_layout)],
    ]

    ceo_layout = [
        [
            sg.Button("Copy from corporation mailing address",
                      key="Copy_ceo_Addr")
        ],
        [
            sg.T("First name:"),
            sg.In(key="ceo_firstname", size=(15, 1)),
            sg.T("Middle name:"),
            sg.In(key="ceo_middlename", size=(15, 1)),
        ],
        [
            sg.T("Last name:"),
            sg.In(key="ceo_lastname", size=(15, 1)),
            sg.T("Suffix:"),
            sg.In(key="ceo_suffix", size=(5, 1)),
        ],
        [
            sg.T("Street address:"),
            sg.In(key="ceo_street", size=(40, 1)),
        ],
        [
            sg.T("City:"),
            sg.In(key="ceo_City", size=(15, 1)),
            sg.T("State:"),
            sg.Combo(statelist, key="ceo_State", size=(3, 1)),
            sg.T("ZIP:"),
            sg.In(key="ceo_ZIP", size=(10, 1)),
        ],
    ]

    secretary_layout = [
        [
            sg.Button("Copy from corporation mailing address",
                      key="Copy_sec_Addr")
        ],
        [
            sg.T("First name:"),
            sg.In(key="sec_firstname", size=(15, 1)),
            sg.T("Middle name:"),
            sg.In(key="sec_middlename", size=(15, 1)),
        ],
        [
            sg.T("Last name:"),
            sg.In(key="sec_lastname", size=(15, 1)),
            sg.T("Suffix:"),
            sg.In(key="sec_suffix", size=(5, 1)),
        ],
        [
            sg.T("Street address:"),
            sg.In(key="sec_street", size=(40, 1)),
        ],
        [
            sg.T("City:"),
            sg.In(key="sec_City", size=(15, 1)),
            sg.T("State:"),
            sg.Combo(statelist, key="sec_State", size=(3, 1)),
            sg.T("ZIP:"),
            sg.In(key="sec_ZIP", size=(10, 1)),
        ],
    ]

    cfo_layout = [
        [
            sg.Button("Copy from corporation mailing address",
                      key="Copy_cfo_Addr")
        ],
        [
            sg.T("First name:"),
            sg.In(key="cfo_firstname", size=(15, 1)),
            sg.T("Middle name:"),
            sg.In(key="cfo_middlename", size=(15, 1)),
        ],
        [
            sg.T("Last name:"),
            sg.In(key="cfo_lastname", size=(15, 1)),
            sg.T("Suffix:"),
            sg.In(key="cfo_suffix", size=(5, 1)),
        ],
        [
            sg.T("Street address:"),
            sg.In(key="cfo_street", size=(40, 1)),
        ],
        [
            sg.T("City:"),
            sg.In(key="cfo_City", size=(15, 1)),
            sg.T("State:"),
            sg.Combo(statelist, key="cfo_State", size=(3, 1)),
            sg.T("ZIP:"),
            sg.In(key="cfo_ZIP", size=(10, 1)),
        ],
    ]

    tab2_layout = [
        [sg.Frame("Chief Executive Officer", ceo_layout)],
        [sg.Frame("Secretary", secretary_layout)],
        [sg.Frame("Chief Financial Officer", cfo_layout)],
    ]

    tab3_layout = [
        [
            sg.Radio(
                "Agent is an individual",
                "agent1",
                key="ind_agent",
                default=True,
                enable_events=True,
            )
        ],
        [
            sg.Radio("Agent is a corporation",
                     "agent1",
                     key="corp_agent",
                     enable_events=True)
        ],
        [
            sg.T("Agent corporate name:",
                 key="agent_corp_name_label",
                 visible=False),
            sg.In(key="agent_corpname", visible=False),
        ],
        [
            sg.T("Agent first name:", key="ind_agent_1"),
            sg.In(key="agent_given", size=(15, 1)),
            sg.T("Agent middle name:", key="ind_agent_3"),
            sg.In(key="agent_middle", size=(15, 1)),
        ],
        [
            sg.T("Agent last name:", key="ind_agent_5"),
            sg.In(key="agent_last"),
            sg.T("Agent suffix:", key="ind_agent_7"),
            sg.In(key="agent_suffix", size=(5, 1)),
        ],
        [
            sg.Button("Copy from corporation physical address",
                      key="Copy_agent_Addr")
        ],
        [
            sg.T("Agent street address:"),
            sg.In(key="agent_Street", size=(40, 1))
        ],
        [
            sg.T("Agent city:"),
            sg.In(key="agent_City", size=(15, 1)),
            sg.T("Agent state: CA"),
            sg.In("CA", key="agent_State", visible=False),
            sg.T("Agent ZIP:"),
            sg.In(key="agent_ZIP", size=(10, 1)),
        ],
    ]
    tab4_layout = [
        [sg.Text("Corporation name:"),
         sg.In(key="2EntityName")],
        [sg.Text("Entity number:"),
         sg.In(key="2EntityNumber", size=(12, 1))],
        [
            sg.Text("Submission comments:"),
            sg.Multiline(key="submission_comments",
                         size=(45, 6),
                         autoscroll=False),
        ],
    ]

    layout = [
        [
            sg.TabGroup([[
                sg.Tab("Corp Info", tab1_layout),
                sg.Tab("Officer info", tab2_layout),
                sg.Tab("Service of Process", tab3_layout),
                sg.Tab("Mail info", tab4_layout),
            ]])
        ],
        [sg.Button("Clear"),
         sg.Button("Print"),
         sg.Button("Save")],
    ]

    window = sg.Window(
        "California Secretary of State Form SI-100",
        layout,
        return_keyboard_events=True,
        grab_anywhere=False,
        #        size=(650, 200),
    )

    while True:
        event, values = window.read()
        pprint.pprint(event)
        pprint.pprint(values)
        if event == "ind_agent":
            window.FindElement("agent_corp_name_label").update(visible=False)
            window.FindElement("agent_corpname").update(visible=False)
            window.FindElement("ind_agent_1").update(visible=True)
            window.FindElement("agent_given").update(visible=True)
            window.FindElement("ind_agent_3").update(visible=True)
            window.FindElement("agent_middle").update(visible=True)
            window.FindElement("ind_agent_5").update(visible=True)
            window.FindElement("agent_last").update(visible=True)
            window.FindElement("ind_agent_7").update(visible=True)
            window.FindElement("agent_suffix").update(visible=True)
            window.FindElement("agent_City").update(visible=True)
            window.FindElement("agent_State").update(visible=True)
            window.FindElement("agent_ZIP").update(visible=True)
        if event == "corp_agent":
            window.FindElement("agent_corp_name_label").update(visible=True)
            window.FindElement("agent_corpname").update(visible=True)
            window.FindElement("ind_agent_1").update(visible=False)
            window.FindElement("agent_given").update(visible=False)
            window.FindElement("ind_agent_3").update(visible=False)
            window.FindElement("agent_middle").update(visible=False)
            window.FindElement("ind_agent_5").update(visible=False)
            window.FindElement("agent_last").update(visible=False)
            window.FindElement("ind_agent_7").update(visible=False)
            window.FindElement("agent_suffix").update(visible=False)
            window.FindElement("agent_City").update(visible=False)
            window.FindElement("agent_State").update(visible=False)
            window.FindElement("agent_ZIP").update(visible=False)

        if event in (None, "Cancel"):
            break
        if event == "Print":
            formdata = fill_dict(values)
            fill_form(formdata)
        if event == "Save":
            formdata = fill_dict(values)
            finished_pdf = fill_form(formdata)
            output_path = sg.PopupGetFile(
                "Save as",
                save_as=True,
                file_types=(("PDF", "*.pdf"), ),
            )
            #            output_path = sg.FileSaveAs()
            #            pprint.pprint(output_path)
            if output_path:
                pdfrw.PdfWriter().write(output_path, finished_pdf)
        if event == "3aZIP":
            continue
        #            potential = values['3aZIP']
        #            print(event, potential)
        #            if len(potential) == 5:
        #                with SearchEngine() as search:
        #                    zipcode = search.by_zipcode(values['3aZIP'], zipcode_type=None)
        #                window.FindElement("3aCity").update(zipcode.major_city)
        if event == "Copy_mail_Addr":
            window.FindElement("3bCity").update(values["3aCity"])
            window.FindElement("3bState").update(values["3aState"])
            window.FindElement("3bAddress").update(values["3aAddress"])
            window.FindElement("3bZIP").update(values["3aZIP"])
        if event == "Copy_ceo_Addr":
            window.FindElement("ceo_City").update(values["3bCity"])
            window.FindElement("ceo_State").update(values["3bState"])
            window.FindElement("ceo_street").update(values["3bAddress"])
            window.FindElement("ceo_ZIP").update(values["3bZIP"])
        if event == "Copy_sec_Addr":
            window.FindElement("sec_City").update(values["3bCity"])
            window.FindElement("sec_State").update(values["3bState"])
            window.FindElement("sec_street").update(values["3bAddress"])
            window.FindElement("sec_ZIP").update(values["3bZIP"])
        if event == "Copy_cfo_Addr":
            window.FindElement("cfo_City").update(values["3bCity"])
            window.FindElement("cfo_State").update(values["3bState"])
            window.FindElement("cfo_street").update(values["3bAddress"])
            window.FindElement("cfo_ZIP").update(values["3bZIP"])
        if event == "Copy_agent_Addr":
            window.FindElement("agent_City").update(values["3aCity"])
            window.FindElement("agent_State").update(values["3aState"])
            window.FindElement("agent_Street").update(values["3aAddress"])
            window.FindElement("agent_ZIP").update(values["3aZIP"])

    window.close()
예제 #30
0
파일: main.py 프로젝트: philmain28/tagtics
import PySimpleGUI as sg  # Part 1 - The import
import tools as tls

import os
# Define the window's contents

layout = [[
    sg.T('Input Path and Tag Filters:'),
    sg.In(key='-Input-'),
    sg.Button('Show')
], [sg.Button('Tag Cloud'), sg.Button('Graph View')],
          [sg.Listbox(values=[], size=(80, 12), key='-LIST-')]]

# Create the window
window = sg.Window('Tagtics File Organiser',
                   layout)  # Part 3 - Window Defintion

path_prev = None
while True:  # Event Loop
    event, values = window.read()

    # parse input and strip whitespace
    parsed_input = values['-Input-'].split('#')
    path = parsed_input[0].strip()
    tags = [tag.strip() for tag in parsed_input[1:]]

    # we don't want to scrap the directory tree everytime we query
    if path_prev != path:
        files = tls.FileMetaData(path)

    #print(files.Tags)