Python PySimpleGUI.Button() Examples

The following are 30 code examples of PySimpleGUI.Button(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PySimpleGUI , or try the search function .
Example #1
Source File: Demo_Youtube-dl_Frontend.py    From PySimpleGUI with GNU Lesser General Public License v3.0 14 votes vote down vote up
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.Button('Get List')],
                [sg.T('Language Code'), combobox, sg.Button('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:
        event, values = window.Read()
        if event in ('Exit', None):
            break           # exit button clicked
        link = values['link']
        if event == 'Get List':
            print('Getting list of subtitles....')
            window.Refresh()
            command = [f'C:\\Python\\Anaconda3\\Scripts\\youtube-dl.exe --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 event == 'Download':
            lang = values['lang'] or 'en'
            print(f'Downloading subtitle for {lang}...')
            window.Refresh()
            command = [f'C:\\Python\\Anaconda3\\Scripts\\youtube-dl.exe --sub-lang {lang} --write-sub {link}',]
            print(ExecuteCommandSubprocess(command, wait=True, quiet=False))
            print('Done') 
Example #2
Source File: Demo_Script_Launcher_Realtime_Output.py    From PySimpleGUI with GNU Lesser General Public License v3.0 11 votes vote down vote up
def main():
    layout = [  [sg.Text('Enter the command you wish to run')],
                [sg.Input(key='_IN_')],
                [sg.Output(size=(60,15))],
                [sg.Button('Run'), sg.Button('Exit')] ]

    window = sg.Window('Realtime Shell Command Output', layout)

    while True:             # Event Loop
        event, values = window.Read()
        # print(event, values)
        if event in (None, 'Exit'):
            break
        elif event == 'Run':
            runCommand(cmd=values['_IN_'], window=window)
    window.Close() 
Example #3
Source File: Demo_Button_Toggle.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def main():
    layout = [[sg.Text('A toggle button example')],
              [sg.T('A graphical version'), sg.B('', image_data=toggle_btn_off, key='_TOGGLE_GRAPHIC_', button_color=sg.COLOR_SYSTEM_DEFAULT,border_width=0),],
              [sg.Button('On', size=(3,1), button_color=('white', 'green'), key='_B_'), sg.Button('Exit')]]

    window = sg.Window('Toggle Button Example', layout)

    down = True
    graphic_off = True
    while True:             # Event Loop
        event, values = window.Read()
        print(event, values)
        if event in (None, 'Exit'):
            break
        elif event == '_B_':                # if the normal button that changes color and text
            down = not down
            window.Element('_B_').Update(('Off','On')[down], button_color=(('white', ('red', 'green')[down])))
        elif event == '_TOGGLE_GRAPHIC_':   # if the graphical button that changes images
            graphic_off = not graphic_off
            window.Element('_TOGGLE_GRAPHIC_').Update(image_data=(toggle_btn_on, toggle_btn_off)[graphic_off])

    window.Close() 
Example #4
Source File: Demo_Multiline_cprint_Printing.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def main():

    MLINE_KEY = '-ML-'+sg.WRITE_ONLY_KEY        # multiline element's key. Indicate it's an output only element
    MLINE_KEY2 = '-ML2-'+sg.WRITE_ONLY_KEY        # multiline element's key. Indicate it's an output only element
    MLINE_KEY3 = '-ML3-'+sg.WRITE_ONLY_KEY        # multiline element's key. Indicate it's an output only element

    output_key = MLINE_KEY


    layout = [  [sg.Text('Multiline Color Print Demo', font='Any 18')],
                [sg.Multiline('Multiline\n', size=(80,20), key=MLINE_KEY)],
                [sg.Multiline('Multiline2\n', size=(80,20), key=MLINE_KEY2)],
                [sg.Text('Text color:'), sg.Combo(list(color_map.keys()), size=(12,20), key='-TEXT COLOR-'),
                 sg.Text('on Background color:'), sg.Combo(list(color_map.keys()), size=(12,20), key='-BG COLOR-')],
                [sg.Input('Type text to output here', size=(80,1), key='-IN-')],
                [sg.Button('Print', bind_return_key=True), sg.Button('Print short'),
                 sg.Button('Force 1'), sg.Button('Force 2'),
                 sg.Button('Use Input for colors'), sg.Button('Toggle Output Location'), sg.Button('Exit')]  ]

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

    sg.cprint_set_output_destination(window, output_key)

    while True:             # Event Loop
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        if event == 'Print':
            sg.cprint(values['-IN-'], text_color=values['-TEXT COLOR-'], background_color=values['-BG COLOR-'])
        elif event == 'Print short':
            sg.cprint(values['-IN-'], c=(values['-TEXT COLOR-'], values['-BG COLOR-']))
        elif event.startswith('Use Input'):
            sg.cprint(values['-IN-'], colors=values['-IN-'])
        elif event.startswith('Toggle'):
            output_key = MLINE_KEY if output_key == MLINE_KEY2 else MLINE_KEY2
            sg.cprint_set_output_destination(window, output_key)
            sg.cprint('Switched to this output element', c='white on red')
        elif event == 'Force 1':
            sg.cprint(values['-IN-'], c=(values['-TEXT COLOR-'], values['-BG COLOR-']), key=MLINE_KEY)
        elif event == 'Force 2':
            sg.cprint(values['-IN-'], c=(values['-TEXT COLOR-'], values['-BG COLOR-']), key=MLINE_KEY2)

    window.close() 
Example #5
Source File: Demo_Script_Launcher_ANSI_Color_Output.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def main():
    layout = [
        [sg.Multiline(size=(110, 30), font='courier 10', background_color='black', text_color='white', key='-MLINE-')],
        [sg.T('Promt> '), sg.Input(key='-IN-', focus=True, do_not_clear=False)],
        [sg.Button('Run', bind_return_key=True), sg.Button('Exit')]]

    window = sg.Window('Realtime Shell Command Output', layout)

    while True:  # Event Loop
        event, values = window.read()
        # print(event, values)
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        elif event == 'Run':
            runCommand(cmd=values['-IN-'], window=window)
    window.close() 
Example #6
Source File: Demo_Touch_Keyboard.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def __init__(self, location=(None, None), font=('Arial', 16)):
        self.font = font
        numberRow = '1234567890'
        topRow = 'QWERTYUIOP'
        midRow = 'ASDFGHJKL'
        bottomRow = 'ZXCVBNM'
        keyboard_layout = [[sg.Button(c, key=c, size=(4, 2), font=self.font) for c in numberRow] + [
            sg.Button('⌫', key='back', size=(4, 2), font=self.font),
            sg.Button('Esc', key='close', size=(4, 2), font=self.font)],
                           [sg.T(' ' * 4)] + [sg.Button(c, key=c, size=(4, 2), font=self.font) for c in
                                              topRow] + [sg.Stretch()],
                           [sg.T(' ' * 11)] + [sg.Button(c, key=c, size=(4, 2), font=self.font) for c in
                                               midRow] + [sg.Stretch()],
                           [sg.T(' ' * 18)] + [sg.Button(c, key=c, size=(4, 2), font=self.font) for c in
                                               bottomRow] + [sg.Stretch()]]

        self.window = sg.Window('keyboard',
                                grab_anywhere=True,
                                keep_on_top=True,
                                alpha_channel=0,
                                no_titlebar=True,
                                element_padding=(0,0),
                                location=location
                                ).Layout(keyboard_layout).Finalize()
        self.hide() 
Example #7
Source File: Demo_Touch_Keyboard.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, location=(None, None), font=('Arial', 16)):
        self.font = font
        numberRow = '1234567890'
        topRow = 'QWERTYUIOP'
        midRow = 'ASDFGHJKL'
        bottomRow = 'ZXCVBNM'
        keyboard_layout = [[sg.Button(c, key=c, size=(4, 2), font=self.font) for c in numberRow] + [
            sg.Button('⌫', key='back', size=(4, 2), font=self.font),
            sg.Button('Esc', key='close', size=(4, 2), font=self.font)],
            [sg.Text(' ' * 4)] + [sg.Button(c, key=c, size=(4, 2), font=self.font) for c in
                               topRow] + [sg.Stretch()],
            [sg.Text(' ' * 11)] + [sg.Button(c, key=c, size=(4, 2), font=self.font) for c in
                                midRow] + [sg.Stretch()],
            [sg.Text(' ' * 18)] + [sg.Button(c, key=c, size=(4, 2), font=self.font) for c in
                                bottomRow] + [sg.Stretch()]]

        self.window = sg.Window('keyboard', keyboard_layout,
                                grab_anywhere=True, keep_on_top=True, alpha_channel=0,
                                no_titlebar=True, element_padding=(0, 0), location=location, finalize=True)
        self.hide() 
Example #8
Source File: Demo_Settings_Save_Load.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def create_settings_window(settings):
    sg.theme(settings['theme'])

    def TextLabel(text): return sg.Text(text+':', justification='r', size=(15,1))

    layout = [  [sg.Text('Settings', font='Any 15')],
                [TextLabel('Max Users'), sg.Input(key='-MAX USERS-')],
                [TextLabel('User Folder'),sg.Input(key='-USER FOLDER-'), sg.FolderBrowse(target='-USER FOLDER-')],
                [TextLabel('Zipcode'),sg.Input(key='-ZIPCODE-')],
                [TextLabel('Theme'),sg.Combo(sg.theme_list(), size=(20, 20), key='-THEME-')],
                [sg.Button('Save'), sg.Button('Exit')]  ]

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

    for key in SETTINGS_KEYS_TO_ELEMENT_KEYS:   # update window with the values read from settings file
        try:
            window[SETTINGS_KEYS_TO_ELEMENT_KEYS[key]].update(value=settings[key])
        except Exception as e:
            print(f'Problem updating PySimpleGUI window from settings. Key = {key}')

    return window

########################################## Main Program Window & Event Loop ########################################## 
Example #9
Source File: Demo_Multithreaded_Logging.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():

    layout = [
            [sg.Multiline(size=(50, 15), key='-LOG-')],
            [sg.Button('Start', bind_return_key=True, key='-START-'), sg.Button('Exit')]
        ]

    window = sg.Window('Log window', layout,
            default_element_size=(30, 2),
            font=('Helvetica', ' 10'),
            default_button_element_size=(8, 2),)

    appStarted = False

    # Setup logging and start app
    logging.basicConfig(level=logging.DEBUG)
    log_queue = queue.Queue()
    queue_handler = QueueHandler(log_queue)
    logger.addHandler(queue_handler)
    threadedApp = ThreadedApp()

    # Loop taking in user input and querying queue
    while True:
        # Wake every 100ms and look for work
        event, values = window.read(timeout=100)

        if event == '-START-':
            if appStarted is False:
                threadedApp.start()
                logger.debug('App started')
                window['-START-'].update(disabled=True)
                appStarted = True
        elif event in  (None, 'Exit'):
            break

        # Poll queue
        try:
            record = log_queue.get(block=False)
        except queue.Empty:
            pass
        else:
            msg = queue_handler.format(record)
            window['-LOG-'].update(msg+'\n', append=True)

    window.close() 
Example #10
Source File: Demo_Save_Window_As_Image.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():

    col = [[sg.Text('This is the first line')],
           [sg.In()],
           [sg.Button('Save'), sg.Button('Exit')]]

    layout = [[sg.Column(col, key='-COLUMN-')]]     # put entire layout into a column so it can be saved

    window = sg.Window("Drawing and Moving Stuff Around", layout)

    while True:
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Exit'):
            break  # exit
        elif event == 'Save':
            filename = sg.popup_get_file('Choose file (PNG, JPG, GIF) to save to', save_as=True)
            save_element_as_file(window['-COLUMN-'], filename)

    window.close() 
Example #11
Source File: Demo_Buttons_Mac.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def show_win():
    sg.SetOptions(border_width=0, margins=(0,0), element_padding=(5,3))


    frame_layout = [ [sg.Button('', image_data=mac_red, button_color=('white', sg.COLOR_SYSTEM_DEFAULT), key='_exit_'),
                sg.Button('', image_data=mac_orange, button_color=('white', sg.COLOR_SYSTEM_DEFAULT)),
                sg.Button('', image_data=mac_green, button_color=('white', sg.COLOR_SYSTEM_DEFAULT), key='_minimize_'),
                      sg.Text(' '*40)],]

    layout = [[sg.Frame('',frame_layout)],
               [sg.T('')],
                [ sg.Text('   My Mac-alike window', size=(25,2)) ],]

    window = sg.Window('My new window',
                       no_titlebar=True,
                       grab_anywhere=True,
                       alpha_channel=0,
                       ).Layout(layout).Finalize()

    for i in range(100):
        window.SetAlpha(i/100)
        time.sleep(.01)

    while True:     # Event Loop
        event, values = window.Read()
        if event is None or event == '_exit_':
            break
        if event == '_minimize_':
            # window.Minimize()     # cannot minimize a window with no titlebar
            pass
        print(event, values) 
Example #12
Source File: Demo_Script_Launcher.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def Launcher2():
    sg.theme('GreenTan')

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

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

    window = sg.Window('Script launcher', layout)

    # ---===--- Loop taking in user input  --- #
    while True:
        event, values = window.read()
        if event in ('EXIT', None):
            break           # exit button clicked
        if event 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 event == 'Run':
            for index, file in enumerate(values['demolist']):
                print('Launching %s' % file)
                window.refresh()          # make the print appear immediately
                if values['wait']:
                    execute_command_blocking(LOCATION_OF_YOUR_SCRIPTS + file)
                else:
                    execute_command_nonblocking(
                        LOCATION_OF_YOUR_SCRIPTS + file)

    window.close() 
Example #13
Source File: Demo_Game_Frontend_Battleship_No_List_Comprehensions.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def Battleship():
    sg.theme('Dark Blue 3')
    MAX_ROWS = MAX_COL = 10

    # Start building layout with the top 2 rows that contain Text elements
    layout =   [[sg.Text('BATTLESHIP', font='Default 25')],
                [sg.Text(size=(15,1), key='-MESSAGE-', font='Default 20')]]

    # Build the "board", a grid of Buttons
    board = []
    for row in range(MAX_ROWS):
        layout_row = []
        for col in range(MAX_COL):
            layout_row.append(sg.Button(str('O'), size=(4, 2), pad=(0,0), border_width=0, key=(row,col)))
        board.append(layout_row)

    # Add the board to the layout
    layout += board
    # Add the exit button as the last row
    layout += [[sg.Button('Exit', button_color=('white', 'red'))]]

    window = sg.Window('Battleship', layout)

    while True:         # The Event Loop
        event, values = window.read()
        print(event, values)
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        if randint(1,10) < 5:           # simulate a hit or a miss
            window[event].update('H', button_color=('white','red'))
            window['-MESSAGE-'].update('Hit')
        else:
            window[event].update('M', button_color=('white','black'))
            window['-MESSAGE-'].update('Miss')
    window.close() 
Example #14
Source File: Demo_OpenCV_Webcam.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():

    sg.theme('Black')

    # define the window layout
    layout = [[sg.Text('OpenCV Demo', size=(40, 1), justification='center', font='Helvetica 20')],
              [sg.Image(filename='', key='image')],
              [sg.Button('Record', size=(10, 1), font='Helvetica 14'),
               sg.Button('Stop', size=(10, 1), font='Any 14'),
               sg.Button('Exit', size=(10, 1), font='Helvetica 14'), ]]

    # create the window and show it without the plot
    window = sg.Window('Demo Application - OpenCV Integration',
                       layout, location=(800, 400))

    # ---===--- Event LOOP Read and display frames, operate the GUI --- #
    cap = cv2.VideoCapture(0)
    recording = False

    while True:
        event, values = window.read(timeout=20)
        if event == 'Exit' or event == sg.WIN_CLOSED:
            return

        elif event == 'Record':
            recording = True

        elif event == 'Stop':
            recording = False
            img = np.full((480, 640), 255)
            # this is faster, shorter and needs less includes
            imgbytes = cv2.imencode('.png', img)[1].tobytes()
            window['image'].update(data=imgbytes)

        if recording:
            ret, frame = cap.read()
            imgbytes = cv2.imencode('.png', frame)[1].tobytes()  # ditto
            window['image'].update(data=imgbytes) 
Example #15
Source File: Demo_Touch_Keyboard.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        layout = [[sg.Text('Enter Text')],
                  [sg.Input('', size=(17, 1), key='input1')],
                  [sg.InputText('', size=(17, 1), key='input2')],
                  [sg.Button('on-screen keyboard', key='keyboard')],
                  [sg.Button('close', key='close')]]

        self.mainWindow = sg.Window('On-screen test', layout,
                                    grab_anywhere=True, no_titlebar=False, finalize=True)
        location = self.mainWindow.current_location()
        location = location[0]-200, location[1]+200
        self.keyboard = keyboard(location)
        self.focus = None 
Example #16
Source File: Demo_Matplotlib_Animated_Scatter.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    # define the form layout
    layout = [[sg.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')],
              [sg.Canvas(size=(640, 480), key='-CANVAS-')],
              [sg.Button('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]]

    # create the form and show it without the plot
    window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', layout, finalize=True)

    canvas_elem = window['-CANVAS-']
    canvas = canvas_elem.TKCanvas
    # draw the intitial scatter plot
    fig, ax = plt.subplots()
    ax.grid(True)
    fig_agg = draw_figure(canvas, fig)

    while True:
        event, values = window.read(timeout=10)
        if event in ('Exit', None):
            exit(69)

        ax.cla()
        ax.grid(True)
        for color in ['red', 'green', 'blue']:
            n = 750
            x, y = rand(2, n)
            scale = 200.0 * rand(n)
            ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none')
        ax.legend()
        fig_agg.draw()
    window.close() 
Example #17
Source File: Demo_Game_Frontend_Battleship.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def Battleship():
    sg.theme('Dark Blue 3')
    MAX_ROWS = MAX_COL = 10

    # Start building layout with the top 2 rows that contain Text elements
    layout =   [[sg.Text('BATTLESHIP', font='Default 25')],
               [sg.Text(size=(15,1), key='-MESSAGE-', font='Default 20')]]
    # Add the board, a grid a buttons
    layout +=  [[sg.Button(str('O'), size=(4, 2), pad=(0,0), border_width=0, key=(row,col)) for col in range(MAX_COL)] for row in range(MAX_ROWS)]
    # Add the exit button as the last row
    layout +=  [[sg.Button('Exit', button_color=('white', 'red'))]]

    window = sg.Window('Battleship', layout)

    while True:         # The Event Loop
        event, values = window.read()
        print(event, values)
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        if randint(1,10) < 5:           # simulate a hit or a miss
            window[event].update('H', button_color=('white','red'))
            window['-MESSAGE-'].update('Hit')
        else:
            window[event].update('M', button_color=('white','black'))
            window['-MESSAGE-'].update('Miss')
    window.close() 
Example #18
Source File: Demo_MIDI_Player.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def PlayerPlaybackGUIStart(self, NumFiles=1):
        # -------  Make a new FlexForm  ------- #

        self.TextElem = sg.Text('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')

        def pbutton(image_data, key):
            return sg.Button(image_data=image_data, key=key, image_size=(50,50), image_subsample=2, border_width=0, button_color=(sg.theme_background_color(), sg.theme_background_color()))

        layout = [
            [sg.Text('MIDI File Player', size=(30, 1), font=("Helvetica", 25))],
            [self.TextElem],
            [self.SliderElem],
            [pbutton(image_pause,'PAUSE'), sg.Text(' '),
             pbutton(image_next, 'NEXT'), sg.Text(' '),
             pbutton(image_restart, key='Restart Song'), sg.Text(' '),
             pbutton(image_exit, 'EXIT')]
        ]

        window = sg.Window('MIDI File Player', layout, default_element_size=(
            30, 1), font=("Helvetica", 25), finalize=True)
        self.Window = window

    # ------------------------------------------------------------------------- #
    #  PlayerPlaybackGUIUpdate                                                  #
    #   Refresh the GUI for the main playback interface (must call periodically #
    # ------------------------------------------------------------------------- # 
Example #19
Source File: Demo_Matplotlib_Ping_Graph.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global g_my_globals

    # define the form layout
    layout = [
        [ sg.Canvas(size=SIZE, background_color='white',key='canvas'),
            sg.Button('Exit', pad=(0, (210, 0)))]
    ]

    # create the form and show it without the plot
    window = sg.Window('Ping Graph', layout, background_color='white', grab_anywhere=True, finalize=True)

    canvas_elem = window['canvas']
    canvas = canvas_elem.TKCanvas

    fig = plt.figure(figsize=(3.1, 2.25), tight_layout={'pad':0})
    g_my_globals.axis_ping = fig.add_subplot(1,1,1)
    plt.rcParams['xtick.labelsize'] = 8
    plt.rcParams['ytick.labelsize'] = 8
    set_chart_labels()
    plt.tight_layout()

    while True:
        event, values = window.read(timeout=0)
        if event in ('Exit', None):
            break

        run_a_ping_and_graph()
        photo = draw(fig, canvas)
    
    window.close() 
Example #20
Source File: Demo_Event_Callback_Simulation.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def button2(event, values):
    sg.popup_quick_message('Button 2 callback',
                           background_color='green',
                           text_color='white') 
Example #21
Source File: Demo_Email_Send.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    sg.theme('Dark Blue 3')
    layout = [[sg.Text('Send an Email', font='Default 18')],
              [sg.T('From:', size=(8,1)), sg.Input(key='-EMAIL FROM-', size=(35,1))],
              [sg.T('To:', size=(8,1)), sg.Input(key='-EMAIL TO-', size=(35,1))],
              [sg.T('Subject:', size=(8,1)), sg.Input(key='-EMAIL SUBJECT-', size=(35,1))],
              [sg.T('Mail login information', font='Default 18')],
              [sg.T('User:', size=(8,1)), sg.Input(key='-USER-', size=(35,1))],
              [sg.T('Password:', size=(8,1)), sg.Input(password_char='*', key='-PASSWORD-', size=(35,1))],
              [sg.Multiline('Type your message here', size=(60,10), key='-EMAIL TEXT-')],
              [sg.Button('Send'), sg.Button('Exit')]]

    window = sg.Window('Send An Email', layout)

    while True:  # Event Loop
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        if event == 'Send':
            if sg.__name__ != 'PySimpleGUIWeb':     # auto close popups not yet supported in PySimpleGUIWeb
                sg.popup_quick_message('Sending your message... this will take a moment...', background_color='red')
            send_an_email(from_address=values['-EMAIL FROM-'],
                          to_address=values['-EMAIL TO-'],
                          subject=values['-EMAIL SUBJECT-'],
                          message_text=values['-EMAIL TEXT-'],
                          user=values['-USER-'],
                          password=values['-PASSWORD-'])

    window.close() 
Example #22
Source File: Demo_Floating_Toolbar.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():

    def tbutton(image_data, key):
        return sg.Button(image_data=image_data, button_color=('white', 'black'), pad=(0,0), key=key)

    toolbar_buttons = [[tbutton(close64, '-CLOSE-'),
                        tbutton(timer64, '-TIMER-'),
                        tbutton(house64, '-HOUSE-'),
                        tbutton(cpu64, '-CPU-') ]]

    # layout = toolbar_buttons
    layout = [[sg.Col(toolbar_buttons, background_color='black')]]

    window = sg.Window('Toolbar', layout, no_titlebar=True,
                       grab_anywhere=True, background_color='black', margins=(0, 0))

    # ---===--- Loop taking in user input --- #
    while True:
        button, value = window.read()
        print(button)
        if button == '-CLOSE-' or button is None:
            break                       # exit button clicked
        elif button == '-TIMER-':
            # add your call to launch a timer program
            print('Timer Button')
        elif button == '-CPU-':
            # add your call to launch a CPU measuring utility
            print('CPU Button')
        elif button == '-HOUSE-':
            print('Home Button')

    window.close() 
Example #23
Source File: Demo_System_Tray_GUI_Window_Design_Pattern.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_a_window():

    layout = [  [sg.Text(f'{delay_time // 60 % 60:2}:{delay_time % 60:02}', key='-OUT-', size=(20, 2), justification='c', font='Any 24')],
                [sg.Button('Start', size=(10,1))],[sg.Button('Minimize\nTo Tray', size=(10,2))]  ]

    return sg.Window('Window Title', layout, element_justification='c', icon=icon) 
Example #24
Source File: Demo_Save_Windows_As_Images.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_win(filename=None, title=None, crop=True):
    """
    Saves a window with the title provided as a file using the provided filename.
    If one of them is missing, then a window is created and the information collected

    :param filename:
    :param title:
    :return:
    """
    C = 7 if crop else 0  # pixels to crop
    if filename is None or title is None:
        layout = [[sg.T('Choose window to save', font='Any 18')],
                  [sg.T('The extension you choose for filename will determine the image format')],
                  [sg.T('Window Title:', size=(12, 1)), sg.I(title if title is not None else '', key='-T-')],
                  [sg.T('Filename:', size=(12, 1)), sg.I(filename if filename is not None else '', key='-F-')],
                  [sg.Button('Ok', bind_return_key=True), sg.Button('Cancel')]]
        event, values = sg.Window('Choose Win Title and Filename', layout).read(close=True)
        if event != 'Ok':  # if cancelled or closed the window
            print('Cancelling the save')
            return
        filename, title = values['-F-'], values['-T-']
    try:
        fceuxHWND = win32gui.FindWindow(None, title)
        rect = win32gui.GetWindowRect(fceuxHWND)
        rect_cropped = (rect[0] + C, rect[1], rect[2] - C, rect[3] - C)
        frame = np.array(ImageGrab.grab(bbox=rect_cropped), dtype=np.uint8)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        cv2.imwrite(filename, frame)
        sg.cprint('Wrote image to file:', filename)
    except Exception as e:
        sg.popup('Error trying to save screenshot file', e, keep_on_top=True) 
Example #25
Source File: Demo_Youtube-dl_Frontend.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def DownloadSubtitlesGUI():
    sg.theme('Dark')

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

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

    # ---===--- Loop taking in user input and using it to query HowDoI --- #
    while True:
        event, values = window.read()
        if event in ('Exit', None):
            break           # exit button clicked
        link = values['link']
        if event == 'Get List':
            print('Getting list of subtitles....')
            window.refresh()
            command = [youtube_executable + f' --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 event == 'Download':
            lang = values['lang'] or 'en'
            print(f'Downloading subtitle for {lang}...')
            window.refresh()
            command = [youtube_executable + f' --sub-lang {lang} --write-sub {link}', ]
            print(ExecuteCommandSubprocess(command, wait=True, quiet=False))
            print('Done')
    window.close() 
Example #26
Source File: Demo_GoodColors_2.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    s10 = (10, 2)

    window = sg.Window('GoodColors', [
        [sg.Text('Having trouble picking good colors? Try this')],
        [sg.Text('Here come the good colors as defined by PySimpleGUI')],
        [sg.Text('Button Colors Using PySimpleGUI.BLUES')],

        [*[sg.Button('BLUES[{}]\n{}'.format(j, c), button_color=(sg.YELLOWS[0], c), size=s10)
           for j, c in enumerate(sg.BLUES)]],
        [sg.Text('_' * 100, size=(65, 1))],
        [sg.Text('Button Colors Using PySimpleGUI.PURPLES')],

        [*[sg.Button('PURPLES[{}]\n{}'.format(j, c), button_color=(sg.YELLOWS[0], c), size=s10)
           for j, c in enumerate(sg.PURPLES)]],
        [sg.Text('_' * 100, size=(65, 1))],
        [sg.Text('Button Colors Using PySimpleGUI.GREENS')],

        [*[sg.Button('GREENS[{}]\n{}'.format(j, c), button_color=(sg.YELLOWS[0], c), size=s10)
           for j, c in enumerate(sg.GREENS)]],
        [sg.Text('_' * 100, size=(65, 1))],
        [sg.Text('Button Colors Using PySimpleGUI.TANS')],

        [*[sg.Button('TANS[{}]\n{}'.format(j, c), button_color=(sg.GREENS[0], c), size=s10)
           for j, c in enumerate(sg.TANS)]],
        [sg.Text('_' * 100, size=(65, 1))],
        [sg.Text('Button Colors Using PySimpleGUI.YELLOWS')],

        [*[sg.Button('YELLOWS[{}]\n{}'.format(j, c), button_color=('black', c), size=s10)
           for j, c in enumerate(sg.YELLOWS)]],

        [sg.Text('_' * 100, size=(65, 1))],
        [sg.Button('Click ME!')]
    ], default_element_size=(30, 2))

    event, values = window.read()
    window.close() 
Example #27
Source File: Demo_Matplotlib_Ping_Graph_Large.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global g_my_globals

    # define the form layout
    layout = [[sg.Text('Animated Ping', size=(40, 1),
                    justification='center', font='Helvetica 20')],
              [sg.Canvas(size=(640, 480), key='canvas')],
              [sg.Button('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]]

    # create the form and show it without the plot
    window = sg.Window(
        'Demo Application - Embedding Matplotlib In PySimpleGUI', layout, finalize=True)

    canvas_elem = window['canvas']
    canvas = canvas_elem.TKCanvas

    fig = plt.figure()
    g_my_globals.axis_ping = fig.add_subplot(1, 1, 1)
    set_chart_labels()
    plt.tight_layout()

    while True:
        event, values = window.read(timeout=0)
        if event in ('Exit', None):
            break

        run_a_ping_and_graph()
        photo = draw(fig, canvas) 
Example #28
Source File: python_easy_chess_gui.py    From Python-Easy-Chess-GUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def render_square(self, image, key, location):
        """ Returns an RButton (Read Button) with image image """
        if (location[0] + location[1]) % 2:
            color = self.sq_dark_color  # Dark square
        else:
            color = self.sq_light_color
        return sg.RButton('', image_filename=image, size=(1, 1),
                          border_width=0, button_color=('white', color),
                          pad=(0, 0), key=key) 
Example #29
Source File: Demo_Media_Player.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def MediaPlayerGUI():
    background = '#F0F0F0'
    sg.set_options(background_color=background,
                   element_background_color=background)

    def ImageButton(title, key):
        return sg.Button(title, button_color=(background, background),
                    border_width=0, key=key)

    # define layout of the rows
    layout = [[sg.Text('Media File Player', font=("Helvetica", 25))],
              [sg.Text('', size=(15, 2), font=("Helvetica", 14), key='output')],
              [ImageButton('restart', key='Restart Song'), sg.Text(' ' * 2),
               ImageButton('pause', key='Pause'), sg.Text(' ' * 2),
               ImageButton('next', key='Next'), sg.Text(' ' * 2),
               sg.Text(' ' * 2), ImageButton('exit', key='Exit')],
              ]

    window = sg.Window('Media File Player', layout,
                       default_element_size=(20, 1),
                       font=("Helvetica", 25))

    while True:
        event, values = window.read(timeout=100)
        if event == 'Exit' or event == sg.WIN_CLOSED:
            break
        # If a button was pressed, display it on the GUI by updating the text element
        if event != sg.TIMEOUT_KEY:
            window['output'].update(event)

    window.close() 
Example #30
Source File: Demo_Layout_Generation.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def layout3():
    # in terms of formatting, the layout to the RIGHT of the = sign looks like a 2-line GUI (ignore the layout +=
    layout =  [[sg.Button(i) for i in range(4)]]
    layout += [[sg.OK()]]               # this row is better than, but is the same as
    layout.append([sg.Cancel()])        # .. this row in that they both add a new ROW with a button on it

    window = sg.Window('Generated Layouts', layout)

    event, values = window.Read()

    print(event, values)
    window.Close()