Exemplo n.º 1
0
def RemoteControlExample():

    layout = [[sg.Text('Robotics Remote Control')],
              [sg.T(' ' * 10), sg.RealtimeButton('Forward')],
              [
                  sg.RealtimeButton('Left'),
                  sg.T(' ' * 15),
                  sg.RealtimeButton('Right')
              ], [sg.T(' ' * 10), sg.RealtimeButton('Reverse')], [sg.T('')],
              [sg.Quit(button_color=('black', 'orange'))]]

    window = sg.Window('Robotics Remote Control',
                       auto_size_text=True).Layout(layout).Finalize()

    #
    # Some place later in your code...
    # You need to perform a ReadNonBlocking on your window every now and then or
    # else it won't refresh.
    #
    # your program's main loop
    while (True):
        # This is the code that reads and updates your window
        button, values = window.ReadNonBlocking()
        if button is not None:
            print(button)
        if button == 'Quit' or values is None:
            break
        # time.sleep(.01)

    window.CloseNonBlocking()
Exemplo n.º 2
0
def RemoteControlExample_NoGraphics():
    # Make a form, but don't use context manager

    layout = [[sg.Text('Robotics Remote Control', justification='center')],
              [sg.T('', justification='center', size=(19, 1), key='status')],
              [sg.T(' ' * 8), sg.RealtimeButton('Forward')],
              [
                  sg.RealtimeButton('Left'),
                  sg.T('              '),
                  sg.RealtimeButton('Right')
              ], [sg.T(' ' * 8), sg.RealtimeButton('Reverse')], [sg.T('')],
              [sg.Quit(button_color=('black', 'orange'))]]
    # Display form to user
    window = sg.Window('Robotics Remote Control',
                       auto_size_text=True,
                       grab_anywhere=False).Layout(layout)

    #
    # Some place later in your code...
    # You need to perform a ReadNonBlocking on your form every now and then or
    # else it won't refresh.
    #
    # your program's main loop
    while (True):
        # This is the code that reads and updates your window
        button, values = window.ReadNonBlocking()
        if button is not None:
            window.FindElement('status').Update(button)
        else:
            window.FindElement('status').Update('')
        # if user clicked quit button OR closed the form using the X, then break out of loop
        if button == 'Quit' or values is None:
            break

    window.CloseNonBlocking()
Exemplo n.º 3
0
def HashGeneratorGUI():
    layout = [
        [sg.T('Password Hash Generator', size=(30, 1), font='Any 15')],
        [sg.T('Password'), sg.In(key='password')],
        [sg.T('SHA Hash'),
         sg.In('', size=(40, 1), key='hash')],
    ]

    window = sg.Window('SHA Generator',
                       auto_size_text=False,
                       default_element_size=(10, 1),
                       text_justification='r',
                       return_keyboard_events=True,
                       grab_anywhere=False).Layout(layout)

    while True:
        button, values = window.Read()
        if button is None:
            exit(69)

        password = values['password']
        try:
            password_utf = password.encode('utf-8')
            sha1hash = hashlib.sha1()
            sha1hash.update(password_utf)
            password_hash = sha1hash.hexdigest()
            window.FindElement('hash').Update(password_hash)
        except:
            pass
def ChatBotWithHistory():
    # -------  Make a new Window  ------- #
    sg.ChangeLookAndFeel('GreenTan')  # give our form a spiffy set of colors

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

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

    # ---===--- Loop taking in user input and using it  --- #
    command_history = []
    history_offset = 0
    while True:
        (button, value) = window.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
            window.FindElement('query').Update(
                ''
            )  # manually clear input because keyboard events blocks clear
            window.FindElement('history').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
            window.FindElement('query').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]
            window.FindElement('query').Update(command)
        elif 'Escape' in button:
            window.FindElement('query').Update('')

    sys.exit(69)
Exemplo n.º 5
0
def RemoteControlExample():
    # Make a form, but don't use context manager
    sg.SetOptions(element_padding=(0, 0))
    back = '#eeeeee'
    image_forward = 'ButtonGraphics/RobotForward.png'
    image_backward = 'ButtonGraphics/RobotBack.png'
    image_left = 'ButtonGraphics/RobotLeft.png'
    image_right = 'ButtonGraphics/RobotRight.png'

    sg.SetOptions(border_width=0,
                  button_color=('black', back),
                  background_color=back,
                  element_background_color=back,
                  text_element_background_color=back)

    layout = [[sg.Text('Robotics Remote Control')],
              [sg.T('', justification='center', size=(19, 1), key='status')],
              [
                  sg.RealtimeButton('Forward',
                                    image_filename=image_forward,
                                    pad=((50, 0), 0))
              ],
              [
                  sg.RealtimeButton('Left', image_filename=image_left),
                  sg.RealtimeButton('Right',
                                    image_filename=image_right,
                                    pad=((50, 0), 0))
              ],
              [
                  sg.RealtimeButton('Reverse',
                                    image_filename=image_backward,
                                    pad=((50, 0), 0))
              ], [sg.T('')], [sg.Quit(button_color=('black', 'orange'))]]

    window = sg.Window('Robotics Remote Control',
                       auto_size_text=True,
                       grab_anywhere=False).Layout(layout)

    #
    # Some place later in your code...
    # You need to perform a ReadNonBlocking on your form every now and then or
    # else it won't refresh.
    #
    # your program's main loop
    while (True):
        # This is the code that reads and updates your window
        button, values = window.ReadNonBlocking()
        if button is not None:
            window.FindElement('status').Update(button)
        else:
            window.FindElement('status').Update('')
        # if user clicked quit button OR closed the form using the X, then break out of loop
        if button == 'Quit' or values is None:
            break

    window.CloseNonBlocking()
Exemplo n.º 6
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 = sg.T('Song loading....',
                             size=(70, 5 + NumFiles),
                             font=("Helvetica", 14),
                             auto_size_text=False)
        self.SliderElem = sg.Slider(range=(1, 100),
                                    size=(50, 8),
                                    orientation='h',
                                    text_color='#f0f0f0')
        layout = [[
            sg.T('MIDI File Player', size=(30, 1), font=("Helvetica", 25))
        ], [self.TextElem], [self.SliderElem],
                  [
                      sg.ReadFormButton('PAUSE',
                                        button_color=sg.TRANSPARENT_BUTTON,
                                        image_filename=image_pause,
                                        image_size=(50, 50),
                                        image_subsample=2,
                                        border_width=0),
                      sg.T(' '),
                      sg.ReadFormButton('NEXT',
                                        button_color=sg.TRANSPARENT_BUTTON,
                                        image_filename=image_next,
                                        image_size=(50, 50),
                                        image_subsample=2,
                                        border_width=0),
                      sg.T(' '),
                      sg.ReadFormButton('Restart Song',
                                        button_color=sg.TRANSPARENT_BUTTON,
                                        image_filename=image_restart,
                                        image_size=(50, 50),
                                        image_subsample=2,
                                        border_width=0),
                      sg.T(' '),
                      sg.SimpleButton(
                          'EXIT',
                          button_color=sg.TRANSPARENT_BUTTON,
                          image_filename=image_exit,
                          image_size=(50, 50),
                          image_subsample=2,
                          border_width=0,
                      )
                  ]]

        window = sg.FlexForm('MIDI File Player',
                             default_element_size=(30, 1),
                             font=("Helvetica", 25)).Layout(layout).Finalize()
        self.Window = window
Exemplo n.º 7
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 Window  ------- #
    sg.ChangeLookAndFeel('GreenTan')            # give our form a spiffy set of colors

    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.Text('Num Answers',font='Helvetica 15'), sg.Checkbox('Display Full Text', key='full text', font='Helvetica 15'),
                sg.T('Command History', font='Helvetica 15'), sg.T('', size=(40,3), text_color=sg.BLUES[0], key='history')],
                [sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False),
                sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True),
                sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]
              ]

    window = sg.Window('How Do I ??', default_element_size=(30, 2), icon=DEFAULT_ICON, font=('Helvetica',' 13'), default_button_element_size=(8,2), return_keyboard_events=True, no_titlebar=True, grab_anywhere=True)
    window.Layout(layout)
    # ---===--- Loop taking in user input and using it to query HowDoI --- #
    command_history = []
    history_offset = 0
    while True:
        (button, value) = window.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
            window.FindElement('query').Update('')                       # manually clear input because keyboard events blocks clear
            window.FindElement('history').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
            window.FindElement('query').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]
            window.FindElement('query').Update(command)
        elif 'Escape' in button:                            # clear currently line
            window.FindElement('query').Update('')
Exemplo n.º 8
0
def creategui():
    sg.ChangeLookAndFeel('BlueMono')

    frame_layout = [
        [sg.T('Elapsed', size=(60, 1), key='-ELAPSED-')],
        [sg.Multiline('', size=(60, 12), autoscroll=True, key='-ML-')],
    ]

    # define the window layout
    layout = [[
        sg.Text('OMRON HVC P2 Demo GUI',
                size=(50, 1),
                justification='center',
                font='Helvetica 20')
    ], [sg.Image(filename='', key='image'),
        sg.Frame('Result', frame_layout)],
              [
                  sg.ReadButton('Exit',
                                size=(10, 1),
                                pad=((0, 0), 3),
                                font='Helvetica 14'),
                  sg.RButton('Pause',
                             key='-RUN-PAUSE-',
                             size=(10, 1),
                             font='Any 14')
              ]]

    # create the window and show it without the plot
    window = sg.Window('OMRON HVC P2 Demo Application', location=(400, 200))
    #window.Layout(layout).Finalize()
    window.Layout(layout)

    return window
Exemplo n.º 9
0
def openFileBox():
    layout = [[sg.T('Source Folder')], [sg.In()],
              [sg.FileBrowse(target=(-1, 0)),
               sg.OK()]]
    window = sg.Window("Choose File", layout)
    event, values = window.Read()
    if event == "OK":
        return values
    else:
        return 0
Exemplo n.º 10
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')
        ],
    ]

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

    graph = window.FindElement('graph')

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

        button, values = window.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 = prev_x - STEP_SIZE
        graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white')
        # window.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()
Exemplo n.º 11
0
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')
        ],
    ]

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

    graph = window.FindElement('graph')
    output = window.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 = window.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 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.ReadButton('Get List')],
                [sg.T('Language Code'), combobox, sg.ReadButton('Download')],
                [sg.Button('Exit', button_color=('white', 'firebrick3'))]
                ]

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

    # ---===--- Loop taking in user input and using it to query HowDoI --- #
    while True:
        (button, gui) = window.Read()
        if button in ('EXIT', None):
            break           # exit button clicked
        link = gui['link']
        if button is 'Get List':
            print('Getting list of subtitles....')
            window.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}...')
            window.Refresh()
            command = (f'C:/Python/PycharmProjects/GooeyGUI/youtube-dl --sub-lang {lang} --write-sub {link}',)
            ExecuteCommandSubprocess(command, wait=True)
            print('Done')
Exemplo n.º 13
0
def main():
    global g_exit, g_response_time

    layout = [[sg.T('Enter width, height of graph')],
              [sg.In(size=(6, 1)), sg.In(size=(6, 1))],
              [sg.Ok(), sg.Cancel()]]

    window = sg.Window('Enter graph size').Layout(layout)
    b,v = window.Read()
    if b is None or b == 'Cancel':
        sys.exit(69)
    w, h = int(v[0]), int(v[1])
    CANVAS_SIZE = (w,h)

    # start ping measurement thread

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

    layout = [  [sg.Quit( button_color=('white','black'))],
               [sg.Graph(CANVAS_SIZE, (0,0), (SAMPLES,SAMPLE_MAX),background_color='black', key='graph')],]

    window = sg.Window('Canvas test', grab_anywhere=True, background_color='black', no_titlebar=False, use_default_focus=False).Layout(layout).Finalize()
    graph = window.FindElement('graph')

    prev_response_time = None
    i=0
    prev_x, prev_y = 0, 0
    graph_value = 250
    while True:
        # time.sleep(.2)
        button, values = window.ReadNonBlocking()
        if button == 'Quit' or values is None:
            break
        graph_offset = random.randint(-10, 10)
        graph_value = graph_value + graph_offset
        if graph_value > SAMPLE_MAX:
            graph_value = SAMPLE_MAX
        if graph_value < 0:
            graph_value = 0
        new_x, new_y = i, graph_value
        prev_value = graph_value
        if i >= SAMPLES:
            graph.Move(-STEP_SIZE,0)
            prev_x = prev_x - STEP_SIZE
        graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white')
        # window.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
Exemplo n.º 14
0
def pong():
    # ------------- Define GUI layout -------------
    layout = [[
        sg.Canvas(size=(700, 400), background_color='black', key='canvas')
    ], [sg.T(''), sg.ReadButton('Quit')]]
    # ------------- Create window -------------
    window = sg.Window('The Classic Game of Pong',
                       return_keyboard_events=True).Layout(layout).Finalize()
    # window.Finalize()                  # TODO Replace with call to window.Finalize once code released

    # ------------- Get the tkinter Canvas we're drawing on -------------
    canvas = window.FindElement('canvas').TKCanvas

    # ------------- Create line down center, the bats and ball -------------
    canvas.create_line(350, 0, 350, 400, fill='white')
    bat1 = pongbat(canvas, 'white')
    bat2 = pongbat2(canvas, 'white')
    ball1 = Ball(canvas, bat1, bat2, 'green')

    # ------------- Event Loop -------------
    while True:
        # ------------- Draw ball and bats -------------
        ball1.draw()
        bat1.draw()
        bat2.draw()

        # ------------- Read the form, get keypresses -------------
        button, values = window.ReadNonBlocking()
        # ------------- If quit  -------------
        if button is None and values is None or button == 'Quit':
            exit(69)
        # ------------- Keypresses -------------
        if button is not None:
            if button.startswith('Up'):
                bat2.up(2)
            elif button.startswith('Down'):
                bat2.down(2)
            elif button == 'w':
                bat1.up(1)
            elif button == 's':
                bat1.down(1)

        if ball1.checkwin():
            sg.Popup('Game Over', ball1.checkwin() + ' won!!')
            break

        # ------------- Bottom of loop, delay between animations -------------
        # time.sleep(.01)
        canvas.after(10)
def Launcher():

    # def print(line):
    #     window.FindElement('output').Update(line)

    sg.ChangeLookAndFeel('Dark')

    namesonly = [f for f in os.listdir(ROOT_PATH) if f.endswith('.py')]

    sg.SetOptions(element_padding=(0, 0),
                  button_element_size=(12, 1),
                  auto_size_buttons=False)

    layout = [[
        sg.Combo(values=namesonly, size=(35, 30), key='demofile'),
        sg.ReadButton('Run', button_color=('white', '#00168B')),
        sg.ReadButton('Program 1'),
        sg.ReadButton('Program 2'),
        sg.ReadButton('Program 3', button_color=('white', '#35008B')),
        sg.Button('EXIT', button_color=('white', 'firebrick3'))
    ], [sg.T('', text_color='white', size=(50, 1), key='output')]]

    window = sg.Window('Floating Toolbar', no_titlebar=True,
                       keep_on_top=True).Layout(layout)

    # ---===--- Loop taking in user input and executing appropriate program --- #
    while True:
        (button, value) = window.Read()
        if button is 'EXIT' or button is None:
            break  # exit button clicked
        if button is 'Program 1':
            print('Run your program 1 here!')
        elif button is 'Program 2':
            print('Run your program 2 here!')
        elif button is 'Run':
            file = value['demofile']
            print('Launching %s' % file)
            ExecuteCommandSubprocess('python', os.path.join(ROOT_PATH, file))
        else:
            print(button)
Exemplo n.º 16
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg

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

layout = [[
    sg.T('Notes:', pad=((3, 0), 0)),
    sg.In(size=(44, 1),
          background_color='white',
          text_color='black',
          key='notes')
],
          [
              sg.T('Output:', pad=((3, 0), 0)),
              sg.T('', size=(44, 1), text_color='white', key='output')
          ],
          [
              sg.CBox('Checkbox:', default=True, pad=((3, 0), 0), key='cbox'),
              sg.Listbox((1, 2, 3, 4), size=(8, 3), key='listbox'),
              sg.Radio('Radio 1', default=True, group_id='1', key='radio1'),
              sg.Radio('Radio 2', default=False, group_id='1', key='radio2')
          ],
          [
              sg.Spin((1, 2, 3, 4), 1, key='spin'),
              sg.OptionMenu((1, 2, 3, 4), key='option'),
              sg.Combo(values=(1, 2, 3, 4), key='combo')
Exemplo n.º 17
0
def TableSimulation():
    """
    Display data in a table format
    """
    sg.SetOptions(element_padding=(0, 0))
    sg.PopupNoWait('Give it a few seconds to load please...', auto_close=True)

    menu_def = [
        ['File', ['Open', 'Save', 'Exit']],
        [
            'Edit',
            ['Paste', [
                'Special',
                'Normal',
            ], 'Undo'],
        ],
        ['Help', 'About...'],
    ]

    columm_layout = [[]]

    MAX_ROWS = 60
    MAX_COL = 10
    for i in range(MAX_ROWS):
        inputs = [sg.T('{}'.format(i), size=(4, 1), justification='right')] + [
            sg.In(size=(10, 1),
                  pad=(1, 1),
                  justification='right',
                  key=(i, j),
                  do_not_clear=True) for j in range(MAX_COL)
        ]
        columm_layout.append(inputs)

    layout = [
        [sg.Menu(menu_def)],
        [sg.T('Table Using Combos and Input Elements', font='Any 18')],
        [
            sg.
            T('Type in a row, column and value. The form will update the values in realtime as you type'
              ),
            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)
        ], [sg.Column(columm_layout, size=(800, 600), scrollable=True)]
    ]

    window = sg.Window('Table',
                       return_keyboard_events=True,
                       grab_anywhere=False).Layout(layout)

    while True:
        button, values = window.Read()
        # --- Process buttons --- #
        if button is None or button == 'Exit':
            break
        elif button == 'About...':
            sg.Popup('Demo of table capabilities')
        elif button == 'Open':
            filename = sg.PopupGetFile('filename to open',
                                       no_window=True,
                                       file_types=(("CSV Files", "*.csv"), ))
            # --- populate table with file contents --- #
            if filename is not None:
                with open(filename, "r") as infile:
                    reader = csv.reader(infile)
                    try:
                        data = list(
                            reader)  # read everything else into a list of rows
                    except:
                        sg.PopupError('Error reading file')
                        continue
                # clear the table
                [
                    window.FindElement((i, j)).Update('')
                    for j in range(MAX_COL) for i in range(MAX_ROWS)
                ]

                for i, row in enumerate(data):
                    for j, item in enumerate(row):
                        location = (i, j)
                        try:  # try the best we can at reading and filling the table
                            target_element = window.FindElement(location)
                            new_value = item
                            if target_element is not None and new_value != '':
                                target_element.Update(new_value)
                        except:
                            pass

        # if a valid table location entered, change that location's value
        try:
            location = (int(values['inputrow']), int(values['inputcol']))
            target_element = window.FindElement(location)
            new_value = values['value']
            if target_element is not None and new_value != '':
                target_element.Update(new_value)
        except:
            pass
Exemplo n.º 18
0
'''
Demo_Chatterbot.py
A GUI wrapped arouind the Chatterbot package.
The GUI is used to show progress bars during the training process and 
to collect user input that is sent to the chatbot.  The reply is displayed in the GUI window
'''

# Create the 'Trainer GUI'
# The Trainer GUI consists of a lot of progress bars stacked on top of each other
sg.ChangeLookAndFeel('GreenTan')
sg.DebugWin()
MAX_PROG_BARS = 20  # number of training sessions
bars = []
texts = []
training_layout = [
    [sg.T('TRAINING PROGRESS', size=(20, 1), font=('Helvetica', 17))],
]
for i in range(MAX_PROG_BARS):
    bars.append(sg.ProgressBar(100, size=(30, 4)))
    texts.append(sg.T(' ' * 20, size=(20, 1), justification='right'))
    training_layout += [
        [texts[i], bars[i]],
    ]  # add a single row

training_window = sg.Window('Training').Layout(training_layout)
current_bar = 0


# callback function for training runs
def print_progress_bar(description,
                       iteration_counter,
Exemplo n.º 19
0
    'Pyplot Scatter With Legend': PyplotScatterWithLegend,
    'Artist Customized Box Plots': PyplotArtistBoxPlots,
    'Artist Customized Box Plots 2': ArtistBoxplot2,
    'Pyplot Histogram': PyplotHistogram
}

sg.ChangeLookAndFeel('LightGreen')
figure_w, figure_h = 650, 650
# define the form layout
listbox_values = [key for key in fig_dict.keys()]
col_listbox = [[
    sg.Listbox(values=listbox_values,
               change_submits=True,
               size=(28, len(listbox_values)),
               key='func')
], [sg.T(' ' * 12), sg.Exit(size=(5, 2))]]

layout = [
    [sg.Text('Matplotlib Plot Test', font=('current 18'))],
    [
        sg.Column(col_listbox, pad=(5, (3, 330))),
        sg.Canvas(size=(figure_w, figure_h), key='canvas'),
        sg.Multiline(size=(70, 35), pad=(5, (3, 90)), key='multiline')
    ],
]

# create the form and show it without the plot
window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI',
                   grab_anywhere=False).Layout(layout)
window.Finalize()
Exemplo n.º 20
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg

layout = [[
    sg.Graph(canvas_size=(400, 400),
             graph_bottom_left=(0, 0),
             graph_top_right=(400, 400),
             background_color='red',
             key='graph')
],
          [
              sg.T('Change circle color to:'),
              sg.ReadButton('Red'),
              sg.ReadButton('Blue'),
              sg.ReadButton('Move')
          ]]

window = sg.Window('Graph test').Layout(layout).Finalize()

graph = window.FindElement('graph')
circle = graph.DrawCircle((75, 75), 25, fill_color='black', line_color='white')
point = graph.DrawPoint((75, 75), 10, color='green')
oval = graph.DrawOval((25, 300), (100, 280),
                      fill_color='purple',
                      line_color='purple')
rectangle = graph.DrawRectangle((25, 300), (100, 280), line_color='purple')
line = graph.DrawLine((0, 0), (100, 100))
Exemplo n.º 21
0
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg
"""
Demonstrates using a "tight" layout with a Dark theme.
Shows how button states can be controlled by a user application.  The program manages the disabled/enabled
states for buttons and changes the text color to show greyed-out (disabled) buttons
"""

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.ReadButton('Start',
                            button_color=('white', 'black'),
Exemplo n.º 22
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg
import sys
'''
Quickly add a GUI to your script!

This simple script shows a 1-line-GUI addition to a typical Python command line script.

Previously this script accepted 1 parameter on the command line.  When executed, that
parameter is read into the variable fname.

The 1-line-GUI shows a form that allows the user to browse to find the filename. The GUI
stores the result in the variable fname, just like the command line parsing did.
'''

if len(sys.argv) == 1:
    button, (fname, ) = sg.Window('My Script').LayoutAndRead(
        [[sg.T('Document to open')], [sg.In(), sg.FileBrowse()],
         [sg.Open(), sg.Cancel()]])
else:
    fname = sys.argv[1]

if not fname:
    sg.Popup("Cancel", "No filename supplied")
    raise SystemExit("Cancelling: no filename supplied")
Exemplo n.º 23
0
    The simple case is that you want to add a single meter to your code.  The one-line solution
"""

# Display a progress meter in work loop. User is not allowed to break out of the loop
for i in range(10000):
    if i % 5 == 0:
        sg.OneLineProgressMeter('My 1-line progress meter', i + 1, 10000,
                                'single')

# Display a progress meter. Allow user to break out of loop using cancel button
for i in range(10000):
    if not sg.OneLineProgressMeter('My 1-line progress meter', i + 1, 10000,
                                   'single'):
        break

layout = [[sg.T('One-Line Progress Meter Demo', font=('Any 18'))],
          [
              sg.T('Outer Loop Count', size=(15, 1), justification='r'),
              sg.In(default_text='100',
                    size=(5, 1),
                    key='CountOuter',
                    do_not_clear=True),
              sg.T('Delay'),
              sg.In(default_text='10',
                    key='TimeOuter',
                    size=(5, 1),
                    do_not_clear=True),
              sg.T('ms')
          ],
          [
              sg.T('Inner Loop Count', size=(15, 1), justification='r'),
Exemplo n.º 24
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg
import math

layout = [
    [
        sg.T('Example of Using Math with a Graph',
             justification='center',
             size=(40, 1),
             relief=sg.RELIEF_RAISED)
    ],
    [
        sg.Graph(canvas_size=(400, 400),
                 graph_bottom_left=(-105, -105),
                 graph_top_right=(105, 105),
                 background_color='white',
                 key='graph',
                 tooltip='This is a cool graph!')
    ],
]

window = sg.Window('Graph of Sine Function',
                   grab_anywhere=True).Layout(layout).Finalize()
graph = window.FindElement('graph')

# Draw axis
graph.DrawLine((-100, 0), (100, 0))
Exemplo n.º 25
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg

sg.ChangeLookAndFeel('GreenTan')
tab2_layout = [[sg.T('This is inside tab 2')],
               [sg.T('Tabs can be anywhere now!')]]

tab1_layout = [[sg.T('Type something here and click button'), sg.In(key='in')]]

tab3_layout = [[sg.T('This is inside tab 3')]]
tab4_layout = [[sg.T('This is inside tab 4')]]

tab_layout = [[sg.T('This is inside of a tab')]]
tab_group = sg.TabGroup(
    [[sg.Tab('Tab 7', tab_layout),
      sg.Tab('Tab 8', tab_layout)]])

tab5_layout = [[sg.T('Watch this window')], [sg.Output(size=(40, 5))]]
tab6_layout = [[sg.T('This is inside tab 6')],
               [sg.T('How about a second row of stuff in tab 6?'), tab_group]]

layout = [
    [sg.T('My Window!')],
    [
        sg.Frame('A Frame',
                 layout=[[
                     sg.TabGroup([[
"""
    Demo of how to combine elements into your own custom element
"""

sg.SetOptions(element_padding=(0,0))
# sg.ChangeLookAndFeel('Dark')
# --- Define our "Big-Button-Spinner" compound element. Has 2 buttons and an input field --- #
NewSpinner =  [sg.ReadButton('-', size=(2,1), font='Any 12'),
               sg.In('0', size=(2,1), font='Any 14', justification='r', key='spin'),
               sg.ReadButton('+', size=(2,1), font='Any 12')]
# --- Define Window --- #
layout = [
          [sg.Text('Spinner simulation')],
            NewSpinner,
            [sg.T('')],
          [sg.Ok()]
         ]

window = sg.Window('Spinner simulation').Layout(layout)

# --- Event Loop --- #
counter = 0
while True:
    button, value = window.Read()

    if button == 'Ok' or button is None:    # be nice to your user, always have an exit from your form
        break

    # --- do spinner stuff --- #
    counter += 1 if button =='+' else -1 if button == '-' else 0
Exemplo n.º 27
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg

layout = [[sg.T('Calendar Test')], [sg.In('', size=(20, 1), key='input')],
          [sg.CalendarButton('Choose Date', target='input', key='date')],
          [sg.Ok(key=1)]]

window = sg.Window('Calendar', grab_anywhere=False).Layout(layout)
b, v = window.Read()
sg.Popup(v['input'])
Exemplo n.º 28
0
def gui():

    #  Gui to get dates from the user
    dates = []
    layout = [[sg.Text('GBO Master Calibration Finder', font=('Helvetica', 25), justification='center')],
              [sg.Text('_' * 100, size=(65, 1))],
              [sg.Text('Enter the dates of science images', font=('Helvetica', 14))],
              [sg.T('Format: 20180715'), sg.T('Added Date', size=(19,1), justification='right')],
              [sg.InputText('', size=(12, 1), key='datein'),
              sg.T('', size=(20, 1), justification='right', key='dateout')],
              [sg.Submit('Add Date')],
              [sg.Button('Next'), sg.Button('Exit')]]

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

    while True:  # Event Loop
        event, values = window.Read()
        print event, values
        if event is None or event == 'Exit':
            print '\nClosing program based on "Exit" command'
            sys.exit(1)
            break
        if event == 'Next':
            break
        if event == 'Add Date':
            dates.append(values['datein'])
            window.Element('dateout').Update(values['datein'])

    window.Close()


    #  Gui to get Path, Binning, and Temp from user
    layout = [[sg.Text('GBO Master Calibration Finder', font=('Helvetica', 25), justification='center')],
              [sg.Text('_' * 100, size=(65, 1))],
              [sg.Text('Enter output path for your files', font=('Helvetica', 12))],
              [sg.InputText(outdir, size=(45, 1), key='path'), sg.Text('Leave as is for default')],
              [sg.Text('_' * 100, size=(65, 1))],
              [sg.Text('Select the type of master frames to find', font=('Helvetica', 14))],
              [sg.Checkbox('Bias', default=True, size=(12, 1), key='Bias'),
               sg.Checkbox('Dark', default=True, size=(12, 1), key='Dark'),
               sg.Checkbox('Flat', default=True, size=(12, 1), key='Flat')],
              [sg.Text('_' * 100, size=(65, 1))],
              [sg.Text('Select the Binning', font=('Helvetica', 14))],
              [sg.Radio('1X1', "RADIO1", default=True, key='1X1'), sg.Radio('2X2', "RADIO1", key='2X2'),
               sg.Radio('3X3', "RADIO1", key='3X3'), sg.Radio('4X4', "RADIO1", key='4X4')],
              [sg.Text('_' * 100, size=(65, 1))],
              [sg.Text('Select the Temp', font=('Helvetica', 14))],
              [sg.Radio('-25', "RADIO2", default=True, key='-25'), sg.Radio('-30', "RADIO2", key='-30'),
               sg.Radio('-35', "RADIO2", key='-35')],
              [sg.Submit(), sg.Button('Exit')]]

    window = sg.Window('GBO Master Calibration Finder', font=("Helvetica", 12)).Layout(layout)

    event, values = window.Read()
    if event == 'Exit':
        print '\nClosing program based on "Exit" command'
        sys.exit(2)

    window.Close()

    types = ['Bias', 'Dark', 'Flat']
    types = [x for x in types if values[x] == True]
    binning = [x for x in bins if values[x] == True]
    binning = binning[0]
    temp = [x for x in temps if values[x] == True]
    temp = temp[0]

    outpath = values['path']
    if not outpath.endswith('\\'):
        outpath = outpath + '\\'


    #  Gui to get dark exposure times from the user
    if 'Dark' in types:
        darkbin = dark_files.where(done_files['binning'] == binning)
        darkbin.dropna(how='all', inplace=True)
        darktemp = darkbin.where(darkbin['temp'] == temp)
        darktemp.dropna(how='all', inplace=True)

        exposures = np.sort(darktemp['exp'].unique())

        layout = [[sg.Text('GBO Master Calibration Finder', font=('Helvetica', 25), justification='center')],
                  [sg.Text('Your Binning is:'), sg.Text(binning)],
                  [sg.Text('Your Temp is:', size=(12,1)), sg.Text(temp)],
                  [sg.Text('',size=(15,1)), sg.Text('Available Exposures')],
                  [sg.Text('', size=(16,1)),
                   sg.Listbox(exposures, size=(10,12), select_mode='multiple', key='exposures')],
                  [sg.Submit(), sg.Button('Exit')]]

        window = sg.Window('GBO Master Calibration Finder', font=("Helvetica", 12)).Layout(layout)

        event, values = window.Read()

        window.Close()

        if event == 'Exit':
            print '\nClosing program based on "Exit" command'
            sys.exit(3)

        exposures = values['exposures']
    else:
        exposures = []

    #  Gui to get filters from the user
    if 'Flat' in types:
        flatbin = flat_files.where(done_files['binning'] == binning)
        flatbin.dropna(how='all', inplace=True)
        flattemp = flatbin.where(flatbin['temp'] == temp)
        flattemp.dropna(how='all', inplace=True)

        filters = np.sort(flattemp['filter'].unique())

        layout = [[sg.Text('GBO Master Calibration Finder', font=('Helvetica', 25), justification='center')],
                  [sg.Text('Your Binning is:'), sg.Text(binning)],
                  [sg.Text('Your Temp is:', size=(12,1)), sg.Text(temp)],
                  [sg.Text('',size=(15,1)), sg.Text('Available Filters')],
                  [sg.Text('', size=(16,1)),
                   sg.Listbox(filters, size=(10,12), select_mode='multiple', key='filters')],
                  [sg.Submit(), sg.Button('Exit')]]

        window = sg.Window('GBO Master Calibration Finder', font=("Helvetica", 12)).Layout(layout)

        event, values = window.Read()

        window.Close()

        if event == 'Exit':
            print '\nClosing program based on "Exit" command'
            sys.exit(4)

        filters = values['filters']
    else:
        filters = []

    return types, outpath, binning, temp, dates, exposures, filters
Exemplo n.º 29
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI 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
Exemplo n.º 30
0
#!/usr/bin/env python
import sys
if sys.version_info[0] < 3:
    import PySimpleGUI27 as sg
else:
    import PySimpleGUI as sg

"""
Turn off padding in order to get a really tight looking layout.
"""

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.ReadButton('Start', button_color=('white', 'black')),
           sg.ReadButton('Stop', button_color=('gray50', 'black')),
           sg.ReadButton('Reset', button_color=('white', '#9B0023')),
           sg.ReadButton('Submit', button_color=('gray60', 'springgreen4')),
           sg.Button('Exit', button_color=('white', '#00406B'))]]

window = sg.Window("Time Tracker", default_element_size=(12, 1), text_justification='r', auto_size_text=False,
                   auto_size_buttons=False, no_titlebar=True,
                   default_button_element_size=(12, 1))

window.Layout(layout)

while True: