예제 #1
0
def GetFilesToCompare():
    with sg.FlexForm('File Compare') as form:
        form_rows = [[sg.Text('Enter 2 files to comare')],
                     [sg.Text('File 1', size=(15, 1)), sg.InputText(), sg.FileBrowse()],
                     [sg.Text('File 2', size=(15, 1)), sg.InputText(), sg.FileBrowse()],
                     [sg.Submit(), sg.Cancel()]]
        rc = form.LayoutAndShow(form_rows)
    return rc
예제 #2
0
 def __init__(self, return_to, form_name, item_type, handler, tree):
     self.return_to = return_to
     self.item_type = item_type
     self.handler = handler
     self.form = sg.FlexForm(form_name, return_keyboard_events=True).layout(
         self.layout()
     )
     self.tree = tree
예제 #3
0
def captcha_input(img_path):
    with sg.FlexForm('验证码输入') as form:
        layout = [[sg.Image(filename=img_path)],
                  [sg.Text('输入上述图片中的字母或数字:', auto_size_text=True)],
                  [sg.InputText()], [sg.Submit('确认'),
                                     sg.Cancel('取消')]]
    _, values = form.LayoutAndRead(layout)
    return values
예제 #4
0
def browse():
    with sg.FlexForm('Browse...') as form:
        form_rows = [[sg.Text('D64 folder')],
                     [sg.InputText(), sg.FileBrowse()],
                     [sg.Submit(), sg.Cancel()]]
        (button, (source_filename, )) = form.LayoutAndRead(form_rows)

    print(button, source_filename)
예제 #5
0
def ChatBotWithHistory():
    # -------  Make a new FlexForm  ------- #
    sg.ChangeLookAndFeel('GreenTan')  # give our form a spiffy set of colors

    form = sg.FlexForm('Chat window with history',
                       default_element_size=(30, 2),
                       font=('Helvetica', ' 13'),
                       default_button_element_size=(8, 2),
                       return_keyboard_events=True)

    multiline_elem = sg.Multiline(size=(85, 5),
                                  enter_submits=True,
                                  key='query',
                                  do_not_clear=False)
    history_elem = sg.T('', size=(20, 3))
    layout = [[sg.Text('Your output will go here', size=(40, 1))],
              [sg.Output(size=(127, 30), font=('Helvetica 10'))],
              [sg.T('Command History'), history_elem],
              [
                  multiline_elem,
                  sg.ReadFormButton('SEND',
                                    button_color=(sg.YELLOWS[0], sg.BLUES[0]),
                                    bind_return_key=True),
                  sg.SimpleButton('EXIT',
                                  button_color=(sg.YELLOWS[0], sg.GREENS[0]))
              ]]
    form.Layout(layout)

    # ---===--- Loop taking in user input and using it  --- #
    command_history = []
    history_offset = 0
    while True:
        (button, value) = form.Read()
        if button is 'SEND':
            query = value['query'].rstrip()
            # EXECUTE YOUR COMMAND HERE
            print('The command you entered was {}'.format(query))
            command_history.append(query)
            history_offset = len(command_history) - 1
            multiline_elem.Update(
                ''
            )  # manually clear input because keyboard events blocks clear
            history_elem.Update('\n'.join(command_history[-3:]))
        elif button is None or button is 'EXIT':  # quit if exit button or X
            break
        elif 'Up' in button and len(command_history):
            command = command_history[history_offset]
            history_offset -= 1 * (history_offset > 0)  # decrement is not zero
            multiline_elem.Update(command)
        elif 'Down' in button and len(command_history):
            history_offset += 1 * (history_offset < len(command_history) - 1
                                   )  # increment up to end of list
            command = command_history[history_offset]
            multiline_elem.Update(command)
        elif 'Escape' in button:
            multiline_elem.Update('')

    exit(69)
예제 #6
0
def main():
    global g_interval,  g_procs, g_exit

    # ----------------  Create Form  ----------------
    sg.ChangeLookAndFeel('Black')
    form_rows = [[sg.Text('', size=(8,1), font=('Helvetica', 20),text_color=sg.YELLOWS[0], justification='center', key='text')],
                 [sg.Text('', size=(30, 8), font=('Courier New', 12),text_color='white', justification='left', key='processes')],
                 [sg.Exit(button_color=('white', 'firebrick4'), pad=((15,0), 0)), sg.Spin([x+1 for x in range(10)], 1, key='spin')],]

    form = sg.FlexForm('CPU Utilization', no_titlebar=True, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True)
    form.Layout(form_rows)
    # start cpu measurement thread
    thread = Thread(target=CPU_thread,args=(None,))
    thread.start()
    # ----------------  main loop  ----------------
    while (True):
        # --------- Read and update window --------
        button, values = form.ReadNonBlocking()

        # --------- Do Button Operations --------
        if values is None or button == 'Exit':
            break
        try:
            g_interval = int(values['spin'])
        except:
            g_interval = 1

        # cpu_percent = psutil.cpu_percent(interval=interval)       # if don't wan to use a task
        cpu_percent = g_cpu_percent

        # let the GUI run ever 700ms regardless of CPU polling time. makes window be more responsive
        time.sleep(.7)

        display_string = ''
        if g_procs:
            # --------- Create list of top % CPU porocesses --------
            try:
                top = {proc.name() : proc.cpu_percent() for proc in g_procs}
            except: pass


            top_sorted = sorted(top.items(), key=operator.itemgetter(1), reverse=True)
            if top_sorted:
                top_sorted.pop(0)
            display_string = ''
            for proc, cpu in top_sorted:
                display_string += '{:2.2f} {}\n'.format(cpu/10, proc)


        # --------- Display timer in window --------
        form.FindElement('text').Update('CPU {}'.format(cpu_percent))
        form.FindElement('processes').Update(display_string)

    # Broke out of main loop. Close the window.
    form.CloseNonBlockingForm()
    g_exit = True
    thread.join()
    exit(69)
 def __init__(self, return_to, form_name, parent_object_key, stories, tree):
     self.return_to = return_to
     self.stories = stories
     self.tree = tree
     self.parent_object_key = parent_object_key
     self.available_values = self.stories.get_available_children_by_parent_id(
         parent_object_key)
     self.form = sg.FlexForm(form_name, return_keyboard_events=True).layout(
         self.layout(self.available_values))
def TableSimulation():
    """
    Display data in a table format
    """
    # sg.ChangeLookAndFeel('Dark')
    sg.SetOptions(element_padding=(0, 0))
    layout = [[sg.T('Table Using Combos and Input Elements', font='Any 18')],
              [
                  sg.T('Row, Cal to change'),
                  sg.In(key='inputrow',
                        justification='right',
                        size=(8, 1),
                        pad=(1, 1),
                        do_not_clear=True),
                  sg.In(key='inputcol',
                        size=(8, 1),
                        pad=(1, 1),
                        justification='right',
                        do_not_clear=True),
                  sg.In(key='value',
                        size=(8, 1),
                        pad=(1, 1),
                        justification='right',
                        do_not_clear=True)
              ]]

    for i in range(20):
        inputs = [
            sg.In('{}{}'.format(i, j),
                  size=(8, 1),
                  pad=(1, 1),
                  justification='right',
                  key=(i, j),
                  do_not_clear=True) for j in range(10)
        ]
        line = [sg.Combo(('Customer ID', 'Customer Name', 'Customer Info'))]
        line.append(inputs)
        layout.append(inputs)

    form = sg.FlexForm('Table',
                       return_keyboard_events=True,
                       grab_anywhere=False)
    form.Layout(layout)

    while True:
        button, values = form.Read()
        if button is None:
            break
        try:
            location = (int(values['inputrow']), int(values['inputcol']))
            target_element = form.FindElement(location)
            new_value = values['value']
            if target_element is not None and new_value != '':
                target_element.Update(new_value)
        except:
            pass
예제 #9
0
def main():
    global g_exit, g_response_time

    # start ping measurement thread
    thread = Thread(target=ping_thread, args=(None, ))
    thread.start()

    sg.ChangeLookAndFeel('Black')
    sg.SetOptions(element_padding=(0, 0))

    layout = [
        [
            sg.T('Ping times to Google.com', font='Any 12'),
            sg.Quit(pad=((100, 0), 0), button_color=('white', 'black'))
        ],
        [
            sg.Graph(CANVAS_SIZE, (0, 0), (SAMPLES, 500),
                     background_color='black',
                     key='graph')
        ],
    ]

    form = sg.FlexForm('Canvas test',
                       grab_anywhere=True,
                       background_color='black',
                       no_titlebar=False,
                       use_default_focus=False)
    form.Layout(layout)

    form.Finalize()
    graph = form.FindElement('graph')

    prev_response_time = None
    i = 0
    prev_x, prev_y = 0, 0
    while True:
        time.sleep(.2)

        button, values = form.ReadNonBlocking()
        if button == 'Quit' or values is None:
            break
        if g_response_time is None or prev_response_time == g_response_time:
            continue
        new_x, new_y = i, g_response_time[0]
        prev_response_time = g_response_time
        if i >= SAMPLES:
            graph.Move(-STEP_SIZE, 0)
            prev_x -= STEP_SIZE
        graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white')
        # form.FindElement('graph').DrawPoint((new_x, new_y), color='red')
        prev_x, prev_y = new_x, new_y
        i += STEP_SIZE if i < SAMPLES else 0

    # tell thread we're done. wait for thread to exit
    g_exit = True
    thread.join()
예제 #10
0
    def PlayerPlaybackGUIStart(self, NumFiles=1):
        # -------  Make a new FlexForm  ------- #

        image_pause = './ButtonGraphics/Pause.png'
        image_restart = './ButtonGraphics/Restart.png'
        image_next = './ButtonGraphics/Next.png'
        image_exit = './ButtonGraphics/Exit.png'

        self.TextElem = g.T('Song loading....',
                            size=(70, 5 + NumFiles),
                            font=("Helvetica", 14),
                            auto_size_text=False)
        self.SliderElem = g.Slider(range=(1, 100),
                                   size=(50, 8),
                                   orientation='h',
                                   text_color='#f0f0f0')
        form = g.FlexForm('MIDI File Player',
                          default_element_size=(30, 1),
                          font=("Helvetica", 25))
        layout = [[
            g.T('MIDI File Player', size=(30, 1), font=("Helvetica", 25))
        ], [self.TextElem], [self.SliderElem],
                  [
                      g.ReadFormButton('PAUSE',
                                       button_color=g.TRANSPARENT_BUTTON,
                                       image_filename=image_pause,
                                       image_size=(50, 50),
                                       image_subsample=2,
                                       border_width=0),
                      g.T(' '),
                      g.ReadFormButton('NEXT',
                                       button_color=g.TRANSPARENT_BUTTON,
                                       image_filename=image_next,
                                       image_size=(50, 50),
                                       image_subsample=2,
                                       border_width=0),
                      g.T(' '),
                      g.ReadFormButton('Restart Song',
                                       button_color=g.TRANSPARENT_BUTTON,
                                       image_filename=image_restart,
                                       image_size=(50, 50),
                                       image_subsample=2,
                                       border_width=0),
                      g.T(' '),
                      g.SimpleButton(
                          'EXIT',
                          button_color=g.TRANSPARENT_BUTTON,
                          image_filename=image_exit,
                          image_size=(50, 50),
                          image_subsample=2,
                          border_width=0,
                      )
                  ]]

        form.LayoutAndRead(layout, non_blocking=True)
        self.Form = form
def gui1():  #layout
    global gui_rows, window
    gui_rows = [[
        sg.RealtimeButton(IO.pop()),
        sg.RealtimeButton(IO.pop()),
        sg.RealtimeButton(IO.pop()),
        sg.RealtimeButton(IO.pop())
    ],
                [
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop())
                ],
                [
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop())
                ],
                [
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop())
                ],
                [
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop())
                ],
                [
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop())
                ],
                [
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop()),
                    sg.RealtimeButton(IO.pop())
                ],
                [
                    sg.T(' ' * 10),
                    sg.SimpleButton('Random',
                                    size=(13, 1),
                                    button_color=('black', 'orange'))
                ]]

    window = sg.FlexForm('Siem-See',
                         auto_size_text=True,
                         default_button_element_size=(5, 2),
                         auto_size_buttons=False)
    window.Layout(gui_rows)
def DownloadSubtitlesGUI():
    sg.ChangeLookAndFeel('Dark')

    combobox = sg.InputCombo(values=[
        '',
    ], size=(10, 1), key='lang')
    layout = [[sg.Text('Subtitle Grabber', size=(40, 1), font=('Any 15'))],
              [
                  sg.T('YouTube Link'),
                  sg.In(default_text='',
                        size=(60, 1),
                        key='link',
                        do_not_clear=True)
              ], [sg.Output(size=(90, 20), font='Courier 12')],
              [sg.ReadFormButton('Get List')],
              [sg.T('Language Code'), combobox,
               sg.ReadFormButton('Download')],
              [sg.SimpleButton('Exit', button_color=('white', 'firebrick3'))]]

    form = sg.FlexForm('Subtitle Grabber launcher',
                       text_justification='r',
                       default_element_size=(15, 1),
                       font=('Any 14'))
    form.Layout(layout)

    # ---===--- Loop taking in user input and using it to query HowDoI --- #
    while True:
        (button, gui) = form.Read()
        if button in ('EXIT', None):
            break  # exit button clicked
        link = gui['link']
        if button is 'Get List':
            print('Getting list of subtitles....')
            form.Refresh()
            command = [
                f'C:/Python/PycharmProjects/GooeyGUI/youtube-dl --list-subs {link}',
            ]
            output = ExecuteCommandSubprocess(command, wait=True, quiet=True)
            lang_list = [
                o[:5].rstrip() for o in output.split('\n') if 'vtt' in o
            ]
            lang_list = sorted(lang_list)
            combobox.Update(values=lang_list)
            print('Done')

        elif button is 'Download':
            lang = gui['lang']
            if lang is '':
                lang = 'en'
            print(f'Downloading subtitle for {lang}...')
            form.Refresh()
            command = (
                f'C:/Python/PycharmProjects/GooeyGUI/youtube-dl --sub-lang {lang} --write-sub {link}',
            )
            ExecuteCommandSubprocess(command, wait=True)
            print('Done')
예제 #13
0
def main():
    fig = Figure()

    ax = fig.add_subplot(111)
    ax.set_xlabel("X axis")
    ax.set_ylabel("Y axis")
    ax.grid()

    canvas_elem = g.Canvas(size=(640,
                                 480))  # get the canvas we'll be drawing on
    # define the form layout
    layout = [[
        g.Text('Animated Matplotlib',
               size=(40, 1),
               justification='center',
               font='Helvetica 20')
    ], [canvas_elem],
              [
                  g.ReadFormButton('Exit',
                                   size=(10, 2),
                                   pad=((280, 0), 3),
                                   font='Helvetica 14')
              ]]

    # create the form and show it without the plot
    form = g.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI')
    form.Layout(layout)
    form.ReadNonBlocking()

    graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas)
    canvas = canvas_elem.TKCanvas

    dpts = [randint(0, 10) for x in range(10000)]
    for i in range(len(dpts)):
        button, values = form.ReadNonBlocking()
        if button is 'Exit' or values is None:
            exit(69)

        ax.cla()
        ax.grid()

        ax.plot(range(VIEW_SIZE), dpts[i:i + VIEW_SIZE], color='purple')
        graph.draw()
        figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
        figure_w, figure_h = int(figure_w), int(figure_h)
        photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

        canvas.create_image(640 / 2, 480 / 2, image=photo)

        figure_canvas_agg = FigureCanvasAgg(fig)
        figure_canvas_agg.draw()

        # Unfortunately, there's no accessor for the pointer to the native renderer
        tkagg.blit(photo,
                   figure_canvas_agg.get_renderer()._renderer,
                   colormode=2)
예제 #14
0
def OneLineGUI():
    """
    The One-Line GUI
    For those of you into super-compact code, a complete customized GUI can be specified, shown, and received the results using a single line of Python code. The way this is done is to combine the call to FlexForm and the call to LayoutAndRead.  FlexForm returns a FlexForm object which has the LayoutAndRead method.
    """
    import PySimpleGUI as sg

    layout = [[sg.Text('Filename')],
              [sg.Input(), sg.FileBrowse()],
              [sg.OK(), sg.Cancel()] ]

    button, (number,) = sg.FlexForm('Get filename example').LayoutAndRead(layout)

    """
    you can write this line of code for the exact same result (OK, two lines with the import):
    """
    # import PySimpleGUI as sg

    button, (filename,) = sg.FlexForm('Get filename example'). LayoutAndRead([[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ])
예제 #15
0
def SecondForm():

    layout = [[
        sg.Text(
            'The second form is small \nHere to show that opening a window using a window works'
        )
    ], [sg.OK()]]

    form = sg.FlexForm('Second Form')
    b, v = form.LayoutAndRead(layout)
예제 #16
0
def deploy_gui():
    sg.SetOptions(text_justification='left')
    most_recent = most_recent_history(ECS_HISTORY_JSON)

    # Local directory settings
    directory_settings = [
        # Source
        [sg.Text('Source', size=(LABEL_COL_WIDTH, 1), font='Any {0}'.format(BODY_FONT_SIZE)),
         sg.In(default_text=most_recent.get('source', ''), size=(INPUT_COL_WIDTH, 1), key='source',
               font='Any {0}'.format(16))]
    ]

    # DockerHub settings
    docker_hub_settings = [
        # Username
        [sg.Text('Username', size=(LABEL_COL_WIDTH, 1), font='Any {0}'.format(BODY_FONT_SIZE)),
         sg.In(default_text=most_recent.get('docker_user', ''), size=(INPUT_COL_WIDTH, 1), key='docker_user')],

        # Repo
        [sg.Text('Repository', size=(LABEL_COL_WIDTH, 1), font='Any {0}'.format(BODY_FONT_SIZE)),
         sg.In(default_text=most_recent.get('docker_repo', most_recent.get('aws_environment-name', '')),
               size=(INPUT_COL_WIDTH, 1), key='docker_repo')],

        # Tag
        [sg.Text('Tag', size=(LABEL_COL_WIDTH, 1), font='Any {0}'.format(BODY_FONT_SIZE)),
         sg.In(default_text=most_recent.get('docker_repo_tag', ''), size=(INPUT_COL_WIDTH, 1),
               key='docker_repo_tag')]
    ]

    # Task settings
    task_settings = [
        # Cluster name
        [sg.Text('Cluster name', size=(LABEL_COL_WIDTH, 1), font='Any {0}'.format(BODY_FONT_SIZE)),
         sg.In(default_text=most_recent.get('cluster', ''), size=(INPUT_COL_WIDTH, 1), key='cluster')],

        # Task name
        [sg.Text('Task name', size=(LABEL_COL_WIDTH, 1), font='Any {0}'.format(BODY_FONT_SIZE)),
         sg.In(default_text=most_recent.get('task_name', ''), size=(INPUT_COL_WIDTH, 1), key='task_name')],
    ]

    # Create form layout
    layout = [
        [sg.Frame('Directory settings', directory_settings, title_color='green', font=DEFAULT_FONT)],
        [sg.Frame('DockerHub settings', docker_hub_settings, title_color='blue', font=DEFAULT_FONT)],
        [sg.Frame('Cluster & Task settings', task_settings, title_color='blue', font=DEFAULT_FONT)],
        [sg.Submit(), sg.Cancel()]]
    window = sg.FlexForm('AWS ECS Deployer', font=("Helvetica", HEADER_FONT_SIZE))
    window.Layout(layout)

    while True:
        button, values = window.ReadNonBlocking()
        if button is 'Submit':
            return values
        elif button is 'Cancel':
            exit()
예제 #17
0
def MediaPlayerGUI():
    background = '#F0F0F0'
    # Set the backgrounds the same as the background on the buttons
    sg.SetOptions(background_color=background, element_background_color=background)
    # Images are located in a subfolder in the Demo Media Player.py folder
    image_pause = './ButtonGraphics/Pause.png'
    image_restart = './ButtonGraphics/Restart.png'
    image_next = './ButtonGraphics/Next.png'
    image_exit = './ButtonGraphics/Exit.png'

    # A text element that will be changed to display messages in the GUI
    TextElem = sg.Text('', size=(15, 2), font=("Helvetica", 14))

    # Open a form, note that context manager can't be used generally speaking for async forms
    form = sg.FlexForm('Media File Player', auto_size_text=True, default_element_size=(20, 1),
                       font=("Helvetica", 25))
    # define layout of the rows
    layout= [[sg.Text('Media File Player',size=(17,1), font=("Helvetica", 25))],
             [TextElem],
             [sg.ReadFormButton('Restart Song', button_color=(background,background),
                                image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0),
                                sg.Text(' ' * 2),
              sg.ReadFormButton('Pause', button_color=(background,background),
                                image_filename=image_pause, image_size=(50, 50), image_subsample=2, border_width=0),
                                sg.Text(' ' * 2),
              sg.ReadFormButton('Next', button_color=(background,background),
                                image_filename=image_next, image_size=(50, 50), image_subsample=2, border_width=0),
                                sg.Text(' ' * 2),
              sg.Text(' ' * 2), sg.SimpleButton('Exit', button_color=(background,background),
                                image_filename=image_exit, image_size=(50, 50), image_subsample=2, border_width=0)],
             [sg.Text('_'*30)],
             [sg.Text(' '*30)],
            [
             sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15)),
             sg.Text(' ' * 2),
             sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15)),
             sg.Text(' ' * 8),
             sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15))],
             [sg.Text('Bass', font=("Helvetica", 15), size=(6, 1)),
             sg.Text('Treble', font=("Helvetica", 15), size=(10, 1)),
             sg.Text('Volume', font=("Helvetica", 15), size=(7, 1))]

             ]

    # Call the same LayoutAndRead but indicate the form is non-blocking
    form.LayoutAndRead(layout, non_blocking=True)
    # Our event loop
    while(True):
        # Read the form (this call will not block)
        button, values = form.ReadNonBlocking()
        if button == 'Exit':
            break
        # If a button was pressed, display it on the GUI by updating the text element
        if button:
            TextElem.Update(button)
예제 #18
0
def Everything():
    with g.FlexForm('Everything bagel',
                    auto_size_text=True,
                    default_element_size=(40, 1)) as form:
        layout = [
            [
                g.Text('All graphic widgets in one form!',
                       size=(30, 1),
                       font=("Helvetica", 25),
                       text_color='blue')
            ], [g.Text('Here is some text.... and a place to enter text')],
            [g.InputText()],
            [
                g.Checkbox('My first checkbox!'),
                g.Checkbox('My second checkbox!', default=True)
            ],
            [
                g.Radio('My first Radio!', "RADIO1", default=True),
                g.Radio('My second Radio!', "RADIO1")
            ],
            [
                g.Multiline(
                    default_text=
                    'This is the default Text should you decide not to type anything',
                    scale=(2, 10))
            ], [g.InputCombo(['choice 1', 'choice 2'], size=(20, 3))],
            [g.Text('_' * 100, size=(70, 1))],
            [g.Text('Choose Source and Destination Folders', size=(35, 1))],
            [
                g.Text('Source Folder', size=(15, 1), auto_size_text=False),
                g.InputText('Source'),
                g.FolderBrowse()
            ],
            [
                g.Text('Destination Folder',
                       size=(15, 1),
                       auto_size_text=False),
                g.InputText('Dest'),
                g.FolderBrowse()
            ],
            [
                g.SimpleButton('Your very own button',
                               button_color=('white', 'green'))
            ], [g.Submit(), g.Cancel()]
        ]

        (button, (values)) = form.LayoutAndShow(layout)

    g.MsgBox('Title',
             'Typical message box',
             'The results of the form are a lot of data!  Get ready... ',
             'The button clicked was "{}"'.format(button),
             'The values are',
             values,
             auto_close=True)
def main():
    global g_exit, g_response_time
    # start ping measurement thread

    sg.ChangeLookAndFeel('Black')
    sg.SetOptions(element_padding=(0, 0))

    layout = [
        [
            sg.Quit(button_color=('white', 'black')),
            sg.T('', pad=((100, 0), 0), font='Any 15', key='output')
        ],
        [
            sg.Graph(CANVAS_SIZE, (0, 0), (SAMPLES, SAMPLE_MAX),
                     background_color='black',
                     key='graph')
        ],
    ]

    form = sg.FlexForm('CPU Graph',
                       grab_anywhere=True,
                       keep_on_top=True,
                       background_color='black',
                       no_titlebar=True,
                       use_default_focus=False)
    form.Layout(layout)

    graph = form.FindElement('graph')
    output = form.FindElement('output')
    # start cpu measurement thread
    thread = Thread(target=CPU_thread, args=(None, ))
    thread.start()

    last_cpu = i = 0
    prev_x, prev_y = 0, 0
    while True:  # the Event Loop
        time.sleep(.5)
        button, values = form.ReadNonBlocking()
        if button == 'Quit' or values is None:  # always give ths user a way out
            break
        # do CPU measurement and graph it
        current_cpu = int(g_cpu_percent * 10)
        if current_cpu == last_cpu:
            continue
        output.Update(current_cpu / 10)  # show current cpu usage at top
        if current_cpu > SAMPLE_MAX:
            current_cpu = SAMPLE_MAX
        new_x, new_y = i, current_cpu
        if i >= SAMPLES:
            graph.Move(-STEP_SIZE, 0)  # shift graph over if full of data
            prev_x = prev_x - STEP_SIZE
        graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white')
        prev_x, prev_y = new_x, new_y
        i += STEP_SIZE if i < SAMPLES else 0
        last_cpu = current_cpu
def Launcher2():
    sg.ChangeLookAndFeel('GreenTan')
    form = sg.FlexForm('Script launcher')

    filelist = glob.glob(LOCATION_OF_YOUR_SCRIPTS + '*.py')
    namesonly = []
    for file in filelist:
        namesonly.append(ntpath.basename(file))

    layout = [
        [sg.Text('Script output....', size=(40, 1))],
        [
            sg.Listbox(values=namesonly,
                       size=(30, 19),
                       select_mode=sg.SELECT_MODE_EXTENDED,
                       key='demolist'),
            sg.Output(size=(88, 20), font='Courier 10')
        ],
        [
            sg.Checkbox('Wait for program to complete',
                        default=False,
                        key='wait')
        ],
        [
            sg.ReadFormButton('Run'),
            sg.ReadFormButton('Shortcut 1'),
            sg.ReadFormButton('Fav Program'),
            sg.SimpleButton('EXIT')
        ],
    ]

    form.Layout(layout)

    # ---===--- Loop taking in user input and using it to query HowDoI --- #
    while True:
        (button, value) = form.Read()
        if button in ('EXIT', None):
            break  # exit button clicked
        if button in ('Shortcut 1', 'Fav Program'):
            print(
                'Quickly launch your favorite programs using these shortcuts')
            print(
                'Or  copy files to your github folder.  Or anything else you type on the command line'
            )
            # copyfile(source, dest)
        elif button is 'Run':
            for index, file in enumerate(value['demolist']):
                print('Launching %s' % file)
                form.Refresh()  # make the print appear immediately
                if value['wait']:
                    execute_command_blocking(LOCATION_OF_YOUR_SCRIPTS + file)
                else:
                    execute_command_nonblocking(LOCATION_OF_YOUR_SCRIPTS +
                                                file)
예제 #21
0
def main():
    def note_generator(question, answer):
        note = Note(
            model=model,
            fields=[question, answer],
            guid=Note.guid
        )
        return note

    with sg.FlexForm('Get filename example') as form:
        layout = [[sg.Text('File to convert:')], [sg.Input(), sg.FileBrowse(file_types=(("CSV Files", "*.csv"),))],
                  [sg.T('Put converted file in folder:')],
                  [sg.Input(), sg.FolderBrowse()],
                  [sg.T('Deck title:')],
                  [sg.InputText()],
                  [sg.SimpleButton('Convert', bind_return_key=True), sg.Cancel()]]

    button, values = form.LayoutAndRead(layout)

    file = values[0]
    dest_folder = values[1]
    deck_title = values[2]
    deck_id = id_generator(deck_title)

    with open(file) as data:
        reader = csv.DictReader(data)
        l_data = []
        for row in reader:
            l_data.append(row)

    model = genanki.Model(
        1607392319,  # The model ID appears to only affect the code, not the ID of output deck files
        'Simple Model',
        fields=[
            {'name': 'Question'},
            {'name': 'Answer'},
        ],
        templates=[
            {
                'name': 'Card 1',
                'qfmt': '{{Question}}',
                'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
            },
        ])

    deck = genanki.Deck(
        deck_id,
        deck_title)

    for line in l_data:
        deck.add_note(note_generator(line['Term'], line['Definition']))

    # file title doesn't affect the deck title
    genanki.Package(deck).write_to_file(dest_folder + '/' + deck_title + '.apkg')
예제 #22
0
def SourceDestFolders():
    with sg.FlexForm('Demo Source / Destination Folders') as form:
        form_rows = ([sg.Text('Enter the Source and Destination folders')],
                     [sg.Text('Source Folder', size=(15, 1), justification='right'), sg.InputText('Source', key='source'), sg.FolderBrowse()],
                     [sg.Text('Destination Folder', size=(15, 1), justification='right'), sg.InputText('Dest', key='dest'), sg.FolderBrowse()],
                     [sg.Submit(), sg.Cancel()])

        button, values = form.LayoutAndRead(form_rows)
    if button is 'Submit':
        sg.Popup('Submitted', values, 'The user entered source:', values['source'], 'Destination folder:', values['dest'], 'Using button', button)
    else:
        sg.PopupError('Cancelled', 'User Cancelled')
예제 #23
0
def hr_approval(hr_emp_id, hr_name, emp_name, emp_id, phoneNumber,
                manager_emp_id, DOJ, DOL, jobTitleName):
    form = sg.FlexForm(
        'HR approval on employee exit')  # begin with a blank form

    layout = [[sg.Submit(), sg.Cancel()]]
    button, values = form.Layout(layout).Read()

    if button == "Submit":
        return 1
    else:
        return 0
예제 #24
0
def reprodutor():
    fff = []
    Sg.theme('LightGreen9')
    layout = [
        [Sg.Text('MY MUSIC PLAYER', size=(30, 1), justification='center', font=("Helvetica", 25),
                 relief=Sg.RELIEF_RAISED, background_color='#00FF7F', text_color='#000000')],
        [Sg.Button('PLAY>>', size=(11, 0), border_width=5), Sg.Button('PAUSE', size=(11, 0), border_width=5),
         Sg.Button('NEXT>', size=(11, 0), border_width=5), Sg.Button('FALL BACK<', size=(11, 0), border_width=5)],
        [Sg.Button('CONTINUE', size=(11, 0), border_width=5), Sg.Button('STOP', size=(11, 0), border_width=5)],
        [Sg.Combo(fff, size=(60, 0), key='-comb-')],
        [linha22(21)],
        [Sg.Output(size=(79, 10), key='-out-', text_color='#00FF7F', background_color='#00000f')],
        [linha22(21)],
        [Sg.Button('Select', size=(11, 0)),
         Sg.Button('Exit', size=(11, 0))]
    ]
    reprod = Sg.FlexForm('MUSIC PLAYER').Layout(layout)
    musica = []
    num = 0
    while True:
        a = functions.Repod(musica, num)
        event, value = reprod.read()
        if event == 'Exit' or event == Sg.WIN_CLOSED:
            break
        if event == 'Select':
            music0 = functions.esc()
            for m in music0:
                if m not in musica:
                    musica.append(m)
                    print('Música adicionada à playlist!')
                    print(m)
                else:
                    print('Música ja se encontra na playlist!')
        if event == 'PLAY>>':
            if musica:
                a.play()
            else:
                print(f'Playlist vazia, selecione faixas!')

        if event == 'PAUSE':
            a.pause()
        if event == 'CONTINUE':
            a.retom()
        if event == 'STOP':
            a.parar()
        if event == 'NEXT>':
            if num < len(musica) - 1:
                num += 1
            else:
                num = 0
            a.prox()
    reprod.close()
예제 #25
0
def HowDoI():
    '''
    Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
    Excellent example of 2 GUI concepts
        1. Output Element that will show text in a scrolled window
        2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form
    :return: never returns
    '''
    # -------  Make a new FlexForm  ------- #
    sg.ChangeLookAndFeel('GreenTan')            # give our form a spiffy set of colors

    form = sg.FlexForm('How Do I ??', default_element_size=(30, 2), icon=DEFAULT_ICON, font=('Helvetica',' 13'), default_button_element_size=(8,2), return_keyboard_events=True)

    multiline_elem = sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False)
    history_elem = sg.T('', size=(40,3), text_color=sg.BLUES[0])
    layout =  [
                [sg.Text('Ask and your answer will appear here....', size=(40, 1))],
                [sg.Output(size=(127, 30), font=('Helvetica 10'))],
                [ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'), sg.T('Num Answers',font='Helvetica 15'), sg.Checkbox('Display Full Text', key='full text', font='Helvetica 15'),
                sg.T('Command History'), history_elem],
                [multiline_elem,
                sg.ReadFormButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True),
                sg.SimpleButton('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]
              ]
    form.Layout(layout)
    # ---===--- Loop taking in user input and using it to query HowDoI --- #
    command_history = []
    history_offset = 0
    while True:
        (button, value) = form.Read()
        if button is 'SEND':
            query = value['query'].rstrip()
            print(query)
            QueryHowDoI(query, value['Num Answers'], value['full text'])  # send the string to HowDoI
            command_history.append(query)
            history_offset = len(command_history)-1
            multiline_elem.Update('')                       # manually clear input because keyboard events blocks clear
            history_elem.Update('\n'.join(command_history[-3:]))
        elif button is None or button is 'EXIT':            # if exit button or closed using X
            break
        elif 'Up' in button and len(command_history):                                # scroll back in history
            command = command_history[history_offset]
            history_offset -= 1 * (history_offset > 0)      # decrement is not zero
            multiline_elem.Update(command)
        elif 'Down' in button and len(command_history):                              # scroll forward in history
            history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list
            command = command_history[history_offset]
            multiline_elem.Update(command)
        elif 'Escape' in button:                            # clear currently line
            multiline_elem.Update('')

    exit(69)
예제 #26
0
def ocr_gui():
    sg.ChangeLookAndFeel('Reddit')

    form = sg.FlexForm('OCR Configurator', default_element_size=(40, 1))

    column1 = [[
        sg.Text('Orientation Threshold: ',
                text_color='#000000',
                background_color='#ffffff',
                justification='left',
                size=(20, 1))
    ],
               [
                   sg.Slider(range=(0, 100),
                             orientation='h',
                             size=(20, 15),
                             default_value=50)
               ]]
    column2 = [[
        sg.Text('Script Threshold: ',
                text_color='#000000',
                background_color='#ffffff',
                justification='left',
                size=(20, 1))
    ],
               [
                   sg.Slider(range=(0, 100),
                             orientation='h',
                             size=(20, 15),
                             default_value=50)
               ]]
    layout = [
        [
            sg.Text('Automated GA OCR Configurator',
                    size=(30, 1),
                    font=("Helvetica", 14))
        ], [sg.Text('_' * 80)], [sg.Text('Choose OCR Engine :', size=(35, 1))],
        [
            sg.Text('OCR Engine',
                    size=(15, 1),
                    auto_size_text=False,
                    justification='right'),
            sg.InputText(r"C:\Program Files\Tesseract-OCR\tesseract.exe"),
            sg.FileBrowse()
        ], [sg.Text('_' * 80)], [sg.Submit()],
        [sg.Text('\N{COPYRIGHT SIGN} Weir EnSci')],
        [sg.Text('Created & Maintained by Ankit Saxena')]
    ]

    button, values = form.layout(layout).Read()
    # print(values) # debug
    return values
예제 #27
0
def TableSimulation():
    """
    Display data in a table format
    """
    import PySimpleGUI as sg
    sg.ChangeLookAndFeel('Dark1')

    layout = [[sg.T('Table Test')]]

    for i in range(20):
        layout.append([sg.T('{} {}'.format(i,j), size=(4, 1), background_color='black', pad=(1, 1)) for j in range(10)])

    sg.FlexForm('Table').LayoutAndRead(layout)
예제 #28
0
def TabbedForm():
    """
    Tabbed Form
    Tabbed forms are easy to make and use in PySimpleGUI. You simple may your layouts for each tab and then instead of LayoutAndRead you call ShowTabbedForm. Results are returned as a list of form results. Each tab acts like a single form.
    """
    import PySimpleGUI as sg

    with sg.FlexForm('') as form:
        with sg.FlexForm('') as form2:

            layout_tab_1 = [[sg.Text('First tab', size=(20, 1), font=('helvetica', 15))],
                            [sg.InputText(), sg.Text('Enter some info')],
                            [sg.Submit(button_color=('red', 'yellow')), sg.Cancel(button_color=('white', 'blue'))]]

            layout_tab_2 = [[sg.Text('Second Tab', size=(20, 1), font=('helvetica', 15))],
                            [sg.InputText(), sg.Text('Enter some info')],
                            [sg.Submit(button_color=('red', 'yellow')), sg.Cancel(button_color=('white', 'blue'))]]

            results = sg.ShowTabbedForm('Tabbed form example', (form, layout_tab_1, 'First Tab'),
                                        (form2, layout_tab_2,'Second Tab'))

    sg.Popup(results)
예제 #29
0
def TableSimulation():
    """
    Display data in a table format
    """
    import PySimpleGUI as sg

    layout = [[sg.T('Table Test')]]

    for i in range(20):
        row = [sg.T(f'Row {i}  ', size=(10, 1))]
        layout.append([sg.T(f'{i}{j}', size=(4, 1), background_color='white', pad=(1, 1)) for j in range(10)])

    sg.FlexForm('Table').LayoutAndRead(layout)
def CustomMeter():

    progress_bar = sg.ProgressBar(10000, orientation='h', size=(20, 20))

    layout = [[sg.Text('A custom progress meter')], [progress_bar],
              [sg.Cancel()]]

    form = sg.FlexForm('Custom Progress Meter')
    form.LayoutAndRead(layout, non_blocking=True)

    for i in range(10000):
        button, values = form.ReadNonBlocking()
        progress_bar.UpdateBar(i)