Python PySimpleGUI.Window() Examples

The following are 30 code examples of PySimpleGUI.Window(). 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_Progress_Meters.py    From PySimpleGUI with GNU Lesser General Public License v3.0 9 votes vote down vote up
def custom_meter_example():
    # layout the form
    layout = [[sg.Text('A typical custom progress meter')],
              [sg.ProgressBar(1, orientation='h', size=(20,20), key='progress')],
              [sg.Cancel()]]

    # create the form`
    window = sg.Window('Custom Progress Meter').Layout(layout)
    progress_bar = window.FindElement('progress')
    # loop that would normally do something useful
    for i in range(10000):
        # check to see if the cancel button was clicked and exit loop if clicked
        event, values = window.Read(timeout=0)
        if event == 'Cancel' or event == None:
            break
        # update bar with loop value +1 so that bar eventually reaches the maximum
        progress_bar.UpdateBar(i+1, 10000)
    # done with loop... need to destroy the window as it's still open
    window.Close() 
Example #4
Source File: test_utilities.py    From pynvme with BSD 3-Clause "New" or "Revised" License 9 votes vote down vote up
def test_get_dell_smart_attributes(nvme0):
    import PySimpleGUI as sg
    
    smart = d.Buffer()
    nvme0.getlogpage(0xCA, smart, 512).waitdone()

    l = []
    l.append('Byte |  Value  | Attribute')
    l.append('   0 |  %5d  | Re-Assigned Sector Count' % smart.data(0))
    l.append('   1 |  %5d  | Program Fail Count (Worst Case Component)' % smart.data(1))
    l.append('   2 |  %5d  | Program Fail Count (SSD Total)' % smart.data(2))
    l.append('   3 |  %5d  | Erase Fail Count (Worst Case Component)' % smart.data(3))
    l.append('   4 |  %5d  | Erase Fail Count (SSD Total)' % smart.data(4))
    l.append('   5 |  %5d  | Wear Leveling Count' % smart.data(5))
    l.append('   6 |  %5d  | Used Reserved Block Count (Worst Case Component)' % smart.data(6))
    l.append('   7 |  %5d  | Used Reserved Block Count (SSD Total)' % smart.data(7))
    l.append('11:8 |  %5d  | Reserved Block Count (SSD Total)' % smart.data(11, 8))

    layout = [[sg.Listbox(l, size=(70, 10))]]
    sg.Window("Dell SMART Attributes",
              layout+[[sg.OK()]],
              font=('monospace', 16)).Read() 
Example #5
Source File: Demo_Machine_Learning.py    From PySimpleGUI with GNU Lesser General Public License v3.0 9 votes vote down vote up
def CustomMeter():
    # layout the form
    layout = [[sg.Text('A custom progress meter')],
              [sg.ProgressBar(1000, orientation='h', size=(20,20), key='progress')],
              [sg.Cancel()]]

    # create the form`
    window = sg.Window('Custom Progress Meter').Layout(layout)
    progress_bar = window.FindElement('progress')
    # loop that would normally do something useful
    for i in range(1000):
        # check to see if the cancel button was clicked and exit loop if clicked
        event, values = window.Read(timeout=0, timeout_key='timeout')
        if event == 'Cancel' or event == None:
            break
        # update bar with loop value +1 so that bar eventually reaches the maximum
        progress_bar.UpdateBar(i+1)
    # done with loop... need to destroy the window as it's still open
    window.CloseNonBlocking() 
Example #6
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 #7
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 #8
Source File: python_easy_chess_gui.py    From Python-Easy-Chess-GUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def create_new_window(self, window, flip=False):
        """ Close the window param just before turning the new window """

        loc = window.CurrentLocation()
        window.Disable()
        if flip:
            self.is_user_white = not self.is_user_white

        layout = self.build_main_layout(self.is_user_white)

        w = sg.Window('{} {}'.format(APP_NAME, APP_VERSION),
            layout,
            default_button_element_size=(12, 1),
            auto_size_buttons=False,
            location=(loc[0], loc[1]),
            icon=ico_path[platform]['pecg'])

        # Initialize White and black boxes
        while True:
            button, value = w.Read(timeout=50)
            self.update_labels_and_game_tags(w, human=self.username)
            break

        window.Close()
        return w 
Example #9
Source File: Demo_Floating_Toolbar_Includes_Buttons.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def ShowMeTheButtons():

    sg.SetOptions(auto_size_buttons=True, margins=(0,0), button_color=sg.COLOR_SYSTEM_DEFAULT)

    toolbar_buttons = [[sg.RButton('', image_data=get_image_bytes(close64),button_color=('white', 'black'), pad=(0,0), key='_close_'),
                        sg.RButton('', image_data=get_image_bytes(timer64), button_color=('white', 'black'), pad=(0, 0), key='_timer_'),
                        sg.RButton('', image_data=get_image_bytes(house64), button_color=('white', 'black'), pad=(0, 0), key='_house_'),
                        ]]

    # layout = toolbar_buttons
    layout =  [[sg.Frame('Launcher', toolbar_buttons,title_color='white', background_color='black')]]

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

    # ---===--- 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_':
            pass        # add your call to launch a timer program
        elif button == '_cpu_':
            pass        # add your call to launch a CPU measuring utility 
Example #10
Source File: Demo_OpenCV_Draw_On_Webcam_Image.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def main():
    layout = [[sg.Graph((600,450),(0,450), (600,0), key='_GRAPH_', enable_events=True, drag_submits=True)],]

    window = sg.Window('Demo Application - OpenCV Integration', layout)

    graph_elem = window.Element('_GRAPH_')      # type: sg.Graph

    id = None
    # ---===--- Event LOOP Read and display frames, operate the GUI --- #
    cap = cv2.VideoCapture(0)
    while True:
        event, values = window.Read(timeout=0)
        if event in ('Exit', None):
            break

        ret, frame = cap.read()
        imgbytes=cv2.imencode('.png', frame)[1].tobytes()
        if id:
            graph_elem.DeleteFigure(id)             # delete previous image
        id = graph_elem.DrawImage(data=imgbytes, location=(0,0))    # draw new image
        graph_elem.TKCanvas.tag_lower(id)           # move image to the "bottom" of all other drawings

        if event == '_GRAPH_':
            graph_elem.DrawCircle(values['_GRAPH_'], 5, fill_color='red', line_color='red')
    window.Close() 
Example #11
Source File: Demo_Menus.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def second_window():

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

    window = sg.Window('Second Form', layout)
    event, values = window.read()
    window.close() 
Example #12
Source File: Demo_Color.py    From PySimpleGUI with GNU Lesser General Public License v3.0 7 votes vote down vote up
def show_all_colors_on_buttons():
    global reverse
    global colorhex
    global colors
    window = sg.Window('Colors on Buttons Demo', default_element_size=(3, 1), location=(0, 0), icon=MY_WINDOW_ICON, font=("Helvetica", 7))
    row = []
    row_len = 20
    for i, c in enumerate(colors):
        hex = get_hex_from_name(c)
        button1 = sg.CButton(button_text=c, button_color=(get_complementary_hex(hex), hex), size=(8, 1))
        button2 = sg.CButton(button_text=c, button_color=(hex, get_complementary_hex(hex)), size=(8, 1))
        row.append(button1)
        row.append(button2)
        if (i+1) % row_len == 0:
            window.AddRow(*row)
            row = []
    if row != []:
        window.AddRow(*row)
    window.Show() 
Example #13
Source File: Demo_Password_Login.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
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:
        event, values = window.Read()
        if event 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

# ----------------------------- Paste this code into your program / script -----------------------------
# determine if a password matches the secret password by comparing SHA1 hash codes 
Example #14
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 #15
Source File: Demo_Menus.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_menus():


    sg.change_look_and_feel('LightGreen')
    sg.set_options(element_padding=(0, 0))

    # ------ Menu Definition ------ #
    menu_def = [['&File', ['&Open', '&Save', '&Properties', 'E&xit' ]],
                ['&Edit', ['&Paste', ['Special', 'Normal',], 'Undo'],],
                ['&Toolbar', ['---', 'Command &1', 'Command &2', '---', 'Command &3', 'Command &4']],
                ['&Help', '&About...'],]

    # ------ GUI Defintion ------ #
    layout = [
              [sg.Menu(menu_def, tearoff=False, pad=(20,1))],
              [sg.Output(size=(60,20))],
              ]

    window = sg.Window("Windows-like program",
                       layout,
                       default_element_size=(12, 1),
                       auto_size_text=False,
                       auto_size_buttons=False,
                       default_button_element_size=(12, 1))

    # ------ Loop & Process button menu choices ------ #
    while True:
        event, values = window.read()
        if event is None or event == 'Exit':
            return
        print('Event = ', event)
        # ------ Process menu choices ------ #
        if event == 'About...':
            window.disappear()
            sg.popup('About this program','Version 1.0', 'PySimpleGUI rocks...', grab_anywhere=True)
            window.reappear()
        elif event == 'Open':
            filename = sg.popup_get_file('file to open', no_window=True)
            print(filename)
        elif event == 'Properties':
            second_window() 
Example #16
Source File: Demo_PyGame_Snake_Game.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, x, y):
        # Call the parent's constructor
        super().__init__()

        # Set height, width
        self.image = pygame.Surface([segment_width, segment_height])
        self.image.fill(WHITE)

        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

# --------------------------- GUI Setup & Create Window ------------------------------- 
Example #17
Source File: Demo_Desktop_Widget_CPU_Utilization.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    global g_interval,  g_procs, g_exit

    # ----------------  Create Form  ----------------
    sg.ChangeLookAndFeel('Black')
    layout = [[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), size=(9,1)),
                  sg.Spin([x+1 for x in range(10)], 3, key='spin')],]

    window = sg.Window('CPU Utilization',
                       no_titlebar=True,
                       keep_on_top=True,
                       alpha_channel=.8,
                       grab_anywhere=True).Layout(layout)

    # start cpu measurement thread
    thread = Thread(target=CPU_thread,args=(None,))
    thread.start()
    timeout_value = 1             # make first read really quick
    g_interval = 1
    # ----------------  main loop  ----------------
    while (True):
        # --------- Read and update window --------
        event, values = window.Read(timeout=timeout_value, timeout_key='Timeout')
        # --------- Do Button Operations --------
        if event is None or event == 'Exit':
            break

        timeout_value = int(values['spin']) * 1000

        cpu_percent = g_cpu_percent
        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 and proceses in window --------
        window.FindElement('text').Update('CPU {}'.format(cpu_percent))
        window.FindElement('processes').Update(display_string)

    g_exit = True
    thread.join() 
Example #18
Source File: Demo_Progress_Meters.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def demo_one_line_progress_meter():
    # 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, 'meter key','MY MESSAGE1', 'MY MESSAGE 2', orientation='h', bar_color=('white', 'red')):
            print('Hit the break')
            break
    for i in range(10000):
        if not sg.OneLineProgressMeter('My 1-line progress meter', i+1, 10000, 'meter key', 'MY MESSAGE1', 'MY MESSAGE 2',orientation='v' ):
            print('Hit the break')
            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'), sg.In(default_text='100', size=(5,1), key='CountInner', do_not_clear=True) ,
                 sg.T('Delay'), sg.In(default_text='10', key='TimeInner', size=(5,1), do_not_clear=True), sg.T('ms')],
                [sg.Button('Show', pad=((0,0), 3), bind_return_key=True), sg.T('me the meters!')]
              ]

    window = sg.Window('One-Line Progress Meter Demo').Layout(layout)

    while True:
        event, values = window.Read()
        if event is None:
            break
        if event == 'Show':
            max_outer = int(values['CountOuter'])
            max_inner = int(values['CountInner'])
            delay_inner = int(values['TimeInner'])
            delay_outer = int(values['TimeOuter'])
            for i in range(max_outer):
                if not sg.OneLineProgressMeter('Outer Loop', i+1, max_outer, 'outer'):
                    break
                sleep(delay_outer/1000)
                for j in range(max_inner):
                    if not sg.OneLineProgressMeter('Inner Loop', j+1, max_inner, 'inner'):
                        break
                    sleep(delay_inner/1000) 
Example #19
Source File: Demo_Buttons_Nice_Graphics.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def ShowMeTheButtons():

    sg.ChangeLookAndFeel('Black')

    frame_layout    = [ [sg.Text('Who says Windows have to be ugly when using tkinter?', size=(45,3))],
                        [sg.Text('All of these buttons are part of the code itself', size=(45,2))],
                        [GraphicButton('Next', '-NEXT-', button64),
                         GraphicButton('Submit', '-SUBMIT-', red_pill64),
                         GraphicButton('OK', '-OK-', green_pill64),
                         GraphicButton('Exit', '-EXIT-', orange64)],]

    layout =  [[sg.Frame('Nice Buttons', frame_layout, font=('any 18'), background_color='black')]]

    window = sg.Window('Demo of Nice Looking Buttons', layout,
                       grab_anywhere=True,
                       keep_on_top=True,
                       no_titlebar=True,
                       use_default_focus=False,
                       font='any 15',
                       background_color='black')

    # ---===--- The event loop --- #
    while True:
        event, values = window.Read()
        print(event)
        if event in ('-EXIT-', None):   # Exit button or X
            break 
Example #20
Source File: Demo_Progress_Meters.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def manually_updated_meter_test():
    # layout the form
    layout = [[sg.Text('This meter is manually updated 4 times')],
              [sg.ProgressBar(max_value=10, orientation='h', size=(20,20), key='progress')]]

    # create the form`
    window = sg.Window('Custom Progress Meter', layout).Finalize()  # must finalize since not running an event loop

    progress_bar = window.FindElement('progress')                   # Get the element to make updating easier

    # -------------------- Your Program Code --------------------
    # Spot #1 to indicate progress
    progress_bar.UpdateBar(1)         # show 10% complete
    sleep(2)

    # more of your code.... perhaps pages and pages of code.
    # Spot #2 to indicate progress
    progress_bar.UpdateBar(2)         # show 20% complete
    sleep(2)

    # more of your code.... perhaps pages and pages of code.
    # Spot #3 to indicate progress
    progress_bar.UpdateBar(6)         # show 60% complete
    sleep(2)

    # more of your code.... perhaps pages and pages of code.
    # Spot #4 to indicate progress
    progress_bar.UpdateBar(9)         # show 90% complete
    sleep(2)
    window.Close() 
Example #21
Source File: Demo_OpenCV_Draw_On_Webcam_Image.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    layout = [[sg.Graph((600,450),(0,450), (600,0), key='-GRAPH-', enable_events=True, drag_submits=True)],]

    window = sg.Window('Demo Application - OpenCV Integration', layout)
    graph_elem = window['-GRAPH-']      # type: sg.Graph
    a_id = None
    # ---===--- Event LOOP Read and display frames, operate the GUI --- #
    cap = cv2.VideoCapture(0)
    while True:
        event, values = window.read(timeout=0)
        if event in ('Exit', None):
            break

        ret, frame = cap.read()
        imgbytes=cv2.imencode('.png', frame)[1].tobytes()
        if a_id:
            graph_elem.delete_figure(a_id)             # delete previous image
        a_id = graph_elem.draw_image(data=imgbytes, location=(0,0))    # draw new image
        graph_elem.TKCanvas.tag_lower(a_id)           # move image to the "bottom" of all other drawings

        if event == '-GRAPH-':
            graph_elem.draw_circle(values['-GRAPH-'], 5, fill_color='red', line_color='red')

    window.close() 
Example #22
Source File: Demo_Script_Launcher.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def Launcher2():
    sg.ChangeLookAndFeel('GreenTan')
    window = sg.Window('Script launcher')

    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.Checkbox('Wait for program to complete', default=False, key='wait')],
                [sg.Button('Run'), sg.Button('Shortcut 1'), sg.Button('Fav Program'), sg.Button('EXIT')],
                ]

    window.Layout(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) 
Example #23
Source File: Demo_Desktop_Floating_Toolbar.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
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') ]

    if len(namesonly) == 0:
        namesonly = ['test 1', 'test 2', 'test 3']

    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.Button('Run', button_color=('white', '#00168B')),
                sg.Button('Program 1'),
                sg.Button('Program 2'),
                sg.Button('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, grab_anywhere=True, keep_on_top=True).Layout(layout)


    # ---===--- Loop taking in user input and executing appropriate program --- #
    while True:
        (event, values) = window.Read()
        if event == 'EXIT' or event is None:
            break           # exit button clicked
        if event == 'Program 1':
            print('Run your program 1 here!')
        elif event == 'Program 2':
            print('Run your program 2 here!')
        elif event == 'Run':
            file = values['demofile']
            print('Launching %s'%file)
            ExecuteCommandSubprocess('python', os.path.join(ROOT_PATH, file))
        else:
            print(event) 
Example #24
Source File: Demo_Graph_Element.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
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:
        event, values = window.Read(timeout=200)
        if event == 'Quit' or event 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() 
Example #25
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.FindElement('-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() 
Example #26
Source File: Demo_NonBlocking_Form.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def StatusOutputExample():
    # Create a text element that will be updated with status information on the GUI itself
    # Create the rows
    layout = [[sg.Text('Non-blocking GUI with updates')],
                 [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='output')],
                 [sg.Button('LED On'), sg.Button('LED Off'), sg.Button('Quit')]]
    # Layout the rows of the Window and perform a read. Indicate the Window is non-blocking!
    window = sg.Window('Running Timer', auto_size_text=True).Layout(layout)

    #
    # Some place later in your code...
    # You need to perform a Read on your window every now and then or
    # else it won't refresh.
    #
    # your program's main loop
    i=0
    while (True):
        # This is the code that reads and updates your window
        event, values = window.Read(timeout=10)
        window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100))
        if event in ('Quit', None):
            break
        if event == 'LED On':
            print('Turning on the LED')
        elif event == 'LED Off':
            print('Turning off the LED')

        i += 1
        # Your code begins here

    # Broke out of main loop. Close the window.
    window.Close() 
Example #27
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', do_not_clear=True)],
                  [sg.InputText(size=(17, 1), key='input2', do_not_clear=True)],
                  [sg.Button('on-screen keyboard', key='keyboard')],
                  [sg.Button('close', key='close')]]

        self.mainWindow = sg.Window('On-screen test',
                                    grab_anywhere=True,
                                    no_titlebar=False,
                                    ).Layout(layout).Finalize()
        location = self.mainWindow.CurrentLocation()
        location = location[0]-200, location[1]+200
        self.keyboard = keyboard(location)
        self.focus = None 
Example #28
Source File: Demo_Threaded_Work.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def the_gui():
    gui_queue = queue.Queue()  # queue used to communicate between the gui and long-running code

    layout = [[sg.Text('Multithreaded Work Example')],
              [sg.Text('Click Go to start a long-running function call')],
              [sg.Text('', size=(25, 1), key='_OUTPUT_')],
              [sg.Text('', size=(25, 1), key='_OUTPUT2_')],
              [sg.Graph((10,10),(0,0),(10,10),background_color='black',key=i) for i in range(20)],
              [sg.Button('Go'), sg.Button('Popup'), sg.Button('Exit')], ]

    window = sg.Window('Multithreaded Window').Layout(layout)
    # --------------------- EVENT LOOP ---------------------
    work_id = 0
    while True:
        event, values = window.Read(timeout=100)  # wait for up to 100 ms for a GUI event
        if event is None or event == 'Exit':
            break
        if event == 'Go':           # clicking "Go" starts a long running work item by starting thread
            window.Element('_OUTPUT_').Update('Starting long work %s'%work_id)
            window.Element(work_id).Update(background_color='red')
            # LOCATION 2
            # STARTING long run by starting a thread
            thread_id = threading.Thread(target=long_function_wrapper, args=(work_id, gui_queue,), daemon=True)
            thread_id.start()
            work_id = work_id+1 if work_id < 19 else 0
        # --------------- Read next message coming in from threads ---------------
        try:
            message = gui_queue.get_nowait()    # see if something has been posted to Queue
        except queue.Empty:                     # get_nowait() will get exception when Queue is empty
            message = None                      # nothing in queue so do nothing

        # if message received from queue, then some work was completed
        if message is not None:
            # LOCATION 3
            # this is the place you would execute code at ENDING of long running task
            # You can check the completed_work_id variable to see exactly which long-running function completed
            completed_work_id = int(message[:message.index(' :::')])
            window.Element('_OUTPUT2_').Update('Complete Work ID "{}"'.format(completed_work_id))
            window.Element(completed_work_id).Update(background_color='green')

        if event == 'Popup':
            sg.Popup('This is a popup showing that the GUI is running')
    # if user exits the window, then close the window and exit the GUI func
    window.Close()

############################# Main ############################# 
Example #29
Source File: Demo_Table_CSV.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def table_example():
    filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),))
    # --- populate table with file contents --- #
    if filename == '':
        sys.exit(69)
    data = []
    header_list = []
    button = sg.PopupYesNo('Does this file have column names already?')
    if filename is not None:
        with open(filename, "r") as infile:
            reader = csv.reader(infile)
            if button == 'Yes':
                header_list = next(reader)
            try:
                data = list(reader)  # read everything else into a list of rows
                if button == 'No':
                    header_list = ['column' + str(x) for x in range(len(data[0]))]
            except:
                sg.PopupError('Error reading file')
                sys.exit(69)
    sg.SetOptions(element_padding=(0, 0))

    layout = [[sg.Table(values=data,
                            headings=header_list,
                            max_col_width=25,
                            auto_size_columns=True,
                            justification='right',
                            alternating_row_color='lightblue',
                            num_rows=min(len(data), 20))]]


    window = sg.Window('Table', grab_anywhere=False).Layout(layout)
    event, values = window.Read()

    sys.exit(69) 
Example #30
Source File: Demo_NonBlocking_Form.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
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
        event, values = window.Read(timeout=0, timeout_key='timeout')
        if event != 'timeout':
            print(event)
        if event in ('Quit', None):
            break

    window.Close()