WIN_CLOSED bulk update. No more test for event is None, use WIN_CLOSED instead

This commit is contained in:
PySimpleGUI 2020-05-07 06:22:59 -04:00
parent 6174b355a6
commit 0076b461f5
135 changed files with 395 additions and 349 deletions

View File

@ -5,8 +5,8 @@ Example of (almost) all widgets, that you can use in PySimpleGUI.
import PySimpleGUI as sg import PySimpleGUI as sg
# sg.theme('Dark Red')
# sg.theme('Default1') sg.theme('Dark Red')
# sg.set_options(text_color='black', background_color='#A6B2BE', text_element_background_color='#A6B2BE') # sg.set_options(text_color='black', background_color='#A6B2BE', text_element_background_color='#A6B2BE')
# ------ Menu Definition ------ # # ------ Menu Definition ------ #
menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']], menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']],
@ -17,7 +17,7 @@ menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']],
column1 = [[sg.Text('Column 1', justification='center', size=(10, 1))], column1 = [[sg.Text('Column 1', justification='center', size=(10, 1))],
[sg.Spin(values=('Spin Box 1', '2', '3'), [sg.Spin(values=('Spin Box 1', '2', '3'),
initial_value='Spin Box 1')], initial_value='Spin Box 1')],
[sg.Spin(values=('Spin Box 1', '2', '3'), [sg.Spin(values=['Spin Box 1', '2', '3'],
initial_value='Spin Box 2')], initial_value='Spin Box 2')],
[sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]]
@ -50,10 +50,9 @@ layout = [
sg.InputText('Default Folder'), sg.FolderBrowse()], sg.InputText('Default Folder'), sg.FolderBrowse()],
[sg.Submit(tooltip='Click to submit this form'), sg.Cancel()]] [sg.Submit(tooltip='Click to submit this form'), sg.Cancel()]]
window = sg.Window('Everything bagel', layout, no_titlebar=True, window = sg.Window('Everything bagel', layout)
default_element_size=(40, 1), grab_anywhere=False)
event, values = window.read() event, values = window.read(close=True)
sg.popup('Title', sg.popup('Title',
'The results of the window.', 'The results of the window.',
'The button clicked was "{}"'.format(event), 'The button clicked was "{}"'.format(event),

View File

@ -30,7 +30,7 @@ gifs = [ring_blue, red_dots_ring, ring_black_dots, ring_gray_segments, ring_line
# first show how to use popup_animated using built-in GIF image # first show how to use popup_animated using built-in GIF image
for i in range(100000): for i in range(100000):
sg.popup_animated(sg.DEFAULT_BASE64_LOADING_GIF, background_color='white', time_between_frames=100) sg.popup_animated(sg.DEFAULT_BASE64_LOADING_GIF, no_titlebar=False, background_color='white', time_between_frames=100)
sg.popup_animated(None) # close all Animated Popups sg.popup_animated(None) # close all Animated Popups
# Next demo is to show how to create custom windows with animations # Next demo is to show how to create custom windows with animations
@ -49,7 +49,7 @@ offset = 0
gif = gifs[0] gif = gifs[0]
while True: # Event Loop while True: # Event Loop
event, values = window.read(timeout=10) # loop every 10 ms to show that the 100 ms value below is used for animation event, values = window.read(timeout=10) # loop every 10 ms to show that the 100 ms value below is used for animation
if event in (None, 'Exit', 'Cancel'): if event in (sg.WIN_CLOSED, 'Exit', 'Cancel'):
break break
elif event == '-IMAGE-': # if clicked on the image elif event == '-IMAGE-': # if clicked on the image

View File

@ -37,7 +37,7 @@ window = sg.Window('Window Title', layout)
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
graph.erase() graph.erase()

View File

@ -30,5 +30,5 @@ window = sg.Window("Borderless Window",
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break

View File

@ -12,7 +12,7 @@ window = sg.Window('Temperature Manager', layout, font='Default -24', return_key
while True: # Event Loop while True: # Event Loop
event, values = window.read(timeout=500) # returns every 500 ms event, values = window.read(timeout=500) # returns every 500 ms
print(event, values) if event != sg.TIMEOUT_KEY else None # a debug print print(event, values) if event != sg.TIMEOUT_KEY else None # a debug print
if event in (None, 'Quit'): if event in (sg.WIN_CLOSED, 'Quit'):
break break
if event == 'Set': if event == 'Set':
print('setting temperature to ', values['-IN-']) print('setting temperature to ', values['-IN-'])

View File

@ -24,7 +24,7 @@ window = sg.Window('Window Title', layout)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
# When choice has been made, then fill in the listbox with the choices # When choice has been made, then fill in the listbox with the choices
if event == '-IN-': if event == '-IN-':

View File

@ -32,7 +32,7 @@ window = sg.Window('Button Callback Simulation', layout)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event is None: if event == sg.WIN_CLOSED:
break break
elif event == 'Button 1': elif event == 'Button 1':
callback_function1() # call the "Callback" function callback_function1() # call the "Callback" function

View File

@ -36,7 +36,7 @@ recording = have_data = False
while True: while True:
event, values = window.read() event, values = window.read()
print(event) print(event)
if event is None: if event == sg.WIN_CLOSED:
break break
if event == '-Start-': if event == '-Start-':
for key, state in {'-Start-': True, '-Stop-': False, '-Reset-': False, '-Submit-': True}.items(): for key, state in {'-Start-': True, '-Stop-': False, '-Reset-': False, '-Submit-': True}.items():

View File

@ -31,7 +31,7 @@ graphic_off = True
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event == '-B-': # if the normal button that changes color and text elif event == '-B-': # if the normal button that changes color and text
down = not down down = not down

View File

@ -24,7 +24,7 @@ window = sg.Window('Window Title', layout)
while True: # Event Loop while True: # Event Loop
event, values = window.read() # type: str, dict event, values = window.read() # type: str, dict
print(event, values) print(event, values)
if event in (None, 'Exit'): # If the user exits if event in (sg.WIN_CLOSED, 'Exit'): # If the user exits
break break
window['-OUT-'].Update(event) # Output the event to the window window['-OUT-'].Update(event) # Output the event to the window
window.close(); del window # Exiting so clean up window.close(); del window # Exiting so clean up

View File

@ -30,7 +30,7 @@ def show_win():
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event is None or event == '-exit-': if event == sg.WIN_CLOSED or event == '-exit-':
break break
if event == '-minimize-': if event == '-minimize-':
# window.Minimize() # cannot minimize a window with no titlebar # window.Minimize() # cannot minimize a window with no titlebar

View File

@ -4,11 +4,11 @@ import PySimpleGUI as sg
""" """
Simple test harness to demonstate how to use the CalendarButton and the get date popup Simple test harness to demonstate how to use the CalendarButton and the get date popup
""" """
sg.theme('Dark Red') # sg.theme('Dark Red')
layout = [[sg.Text('Date Chooser Test Harness', key='-TXT-')], layout = [[sg.Text('Date Chooser Test Harness', key='-TXT-')],
[sg.Input(key='-IN-', size=(20,1)), sg.CalendarButton('Cal US No Buttons Location (0,0)', close_when_date_chosen=True, target='-IN-', location=(0,0), no_titlebar=False, )], [sg.Input(key='-IN-', size=(20,1)), sg.CalendarButton('Cal US No Buttons Location (0,0)', close_when_date_chosen=True, target='-IN-', location=(0,0), no_titlebar=False, )],
[sg.Input(key='-IN3-', size=(20,1)), sg.CalendarButton('Cal Monday', title='Pick a date any date', no_titlebar=True, close_when_date_chosen=False, target='-IN3-', begin_at_sunday_plus=1, month_names=('студзень', 'люты', 'сакавік', 'красавік', 'май', 'чэрвень', 'ліпень', 'жнівень', 'верасень', 'кастрычнік', 'лістапад', 'снежань'), day_abbreviations=('Дш', 'Шш', 'Шр', 'Бш', 'Жм', 'Иш', 'Жш'))], [sg.Input(key='-IN3-', size=(20,1)), sg.CalendarButton('Cal Monday', title='Pick a date any date', no_titlebar=True, close_when_date_chosen=False, target='-IN3-', begin_at_sunday_plus=1, month_names=('студзень', 'люты', 'сакавік', 'красавік', 'май', 'чэрвень', 'ліпень', 'жнівень', 'верасень', 'кастрычнік', 'лістапад', 'снежань'), day_abbreviations=('Дш', 'Шш', 'Шр', 'Бш', 'Жм', 'Иш', 'Жш'))],
[sg.Input(key='-IN2-', size=(20,1)), sg.CalendarButton('Cal German Feb 2020', target='-IN2-', default_date_m_d_y=(2,None,2020), locale='de DE', begin_at_sunday_plus=1 )], [sg.Input(key='-IN2-', size=(20,1)), sg.CalendarButton('Cal German Feb 2020', target='-IN2-', default_date_m_d_y=(2,None,2020), locale='de_DE', begin_at_sunday_plus=1 )],
[sg.Input(key='-IN4-', size=(20,1)), sg.CalendarButton('Cal Format %m-%d Jan 2020', target='-IN4-', format='%m-%d', default_date_m_d_y=(1,None,2020), )], [sg.Input(key='-IN4-', size=(20,1)), sg.CalendarButton('Cal Format %m-%d Jan 2020', target='-IN4-', format='%m-%d', default_date_m_d_y=(1,None,2020), )],
[sg.Button('Read'), sg.Button('Date Popup'), sg.Exit()]] [sg.Button('Read'), sg.Button('Date Popup'), sg.Exit()]]
@ -17,7 +17,7 @@ window = sg.Window('window', layout)
while True: while True:
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event == 'Date Popup': elif event == 'Date Popup':
sg.popup('You chose:', sg.popup_get_date()) sg.popup('You chose:', sg.popup_get_date())

View File

@ -12,7 +12,7 @@ cir = window['canvas'].TKCanvas.create_oval(50, 50, 100, 100)
while True: while True:
event, values = window.read() event, values = window.read()
if event is None: if event == sg.WIN_CLOSED:
break break
if event in ('Blue', 'Red'): if event in ('Blue', 'Red'):
window['canvas'].TKCanvas.itemconfig(cir, fill=event) window['canvas'].TKCanvas.itemconfig(cir, fill=event)

View File

@ -40,7 +40,7 @@ window = sg.Window('Demonstration of InputText with change_submits',
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event is None: if event == sg.WIN_CLOSED:
break break
window.close() window.close()

View File

@ -18,7 +18,7 @@ window = sg.Window('Chat window', layout, font=('Helvetica', ' 13'), default_but
while True: # The Event Loop while True: # The Event Loop
event, value = window.read() event, value = window.read()
if event in (None, 'EXIT'): # quit if exit button or X if event in (sg.WIN_CLOSED, 'EXIT'): # quit if exit button or X
break break
if event == 'SEND': if event == 'SEND':
query = value['-QUERY-'].rstrip() query = value['-QUERY-'].rstrip()

View File

@ -48,7 +48,7 @@ def ChatBotWithHistory():
window['query'].update('') window['query'].update('')
window['history'].update('\n'.join(command_history[-3:])) window['history'].update('\n'.join(command_history[-3:]))
elif event in (None, 'EXIT'): # quit if exit event or X elif event in (sg.WIN_CLOSED, 'EXIT'): # quit if exit event or X
break break
elif 'Up' in event and len(command_history): elif 'Up' in event and len(command_history):

View File

@ -1687,7 +1687,7 @@ def main():
event, values = sg.Window('Color Demo', layout, auto_size_buttons=False).read() event, values = sg.Window('Color Demo', layout, auto_size_buttons=False).read()
# ------- OUTPUT results portion ------- # # ------- OUTPUT results portion ------- #
if event == 'Quit' or event is None: if event == 'Quit' or event == sg.WIN_CLOSED:
exit(0) exit(0)
elif event == 'Many buttons': elif event == 'Many buttons':
show_all_colors_on_buttons() show_all_colors_on_buttons()

View File

@ -689,8 +689,8 @@ def popup_color_chooser(look_and_feel=None):
color_chosen = None color_chosen = None
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'OK'): if event in (sg.WIN_CLOSED, 'OK'):
if event is None: if event == sg.WIN_CLOSED:
color_chosen = None color_chosen = None
break break
window['-OUT-'](f'You chose {event[0]} : {event[1]}') window['-OUT-'](f'You chose {event[0]} : {event[1]}')
@ -708,7 +708,7 @@ if __name__ == '__main__':
window = sg.Window('My application', layout) window = sg.Window('My application', layout)
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Cancel'): if event in (sg.WIN_CLOSED, 'Cancel'):
break break
if event.startswith('Color'): if event.startswith('Color'):
window.hide() window.hide()

View File

@ -696,7 +696,7 @@ window = sg.Window('Color Viewer', layout, font='Any 9', element_padding=(0,0),
# -- Event loop -- # -- Event loop --
while True: while True:
event, values = window.read() event, values = window.read()
if event is None: if event == sg.WIN_CLOSED:
break break
# -- Create a secondary window that shows white and black text on chosen color # -- Create a secondary window that shows white and black text on chosen color
layout2 = [[ layout2 = [[

View File

@ -114,7 +114,7 @@ window = sg.Window('Color Viewer', layout, grab_anywhere=False, font=('any 9'))
# -- Event loop -- # -- Event loop --
while True: while True:
event, values = window.read() event, values = window.read()
if event is None: if event == sg.WIN_CLOSED:
break break
# -- Create a secondary window that shows white and black text on chosen color # -- Create a secondary window that shows white and black text on chosen color
layout2 = [[sg.DummyButton(event, button_color=('white', event)), layout2 = [[sg.DummyButton(event, button_color=('white', event)),

View File

@ -19,10 +19,10 @@ col2 = Column([[Frame('Accounts:', [[Column([[Listbox(['Account '+str(i) for i i
col1 = Column([ col1 = Column([
# Categories frame # Categories frame
[Frame('Categories:', [[Radio('Websites', 'radio1', default=True, key='-WEBSITES-', size=(10, 1)), [Frame('Categories:', [[ Radio('Websites', 'radio1', default=True, key='-WEBSITES-', size=(10, 1)),
Radio('Software', 'radio1', key='-SOFTWARE-', size=(10, 1))]],)], Radio('Software', 'radio1', key='-SOFTWARE-', size=(10, 1))]],)],
# Information frame # Information frame
[Frame('Information:', [[Column([[Text('Account:')], [Frame('Information:', [[Text(), Column([[Text('Account:')],
[Input(key='-ACCOUNT-IN-', size=(19, 1))], [Input(key='-ACCOUNT-IN-', size=(19, 1))],
[Text('User Id:')], [Text('User Id:')],
[Input(key='-USERID-IN-', size=(19, 1)), [Input(key='-USERID-IN-', size=(19, 1)),
@ -47,7 +47,7 @@ window = Window('Passwords', layout)
while True: while True:
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event is None: if event == sg.WIN_CLOSED:
break break
window.close() window.close()

View File

@ -32,7 +32,7 @@ layout = 1 # The currently visible layout
while True: while True:
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == 'Cycle Layout': if event == 'Cycle Layout':
window[f'-COL{layout}-'].update(visible=False) window[f'-COL{layout}-'].update(visible=False)

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
import PySimpleGUI as sg import PySimpleGUI as sg
print(sg.version, sg)
''' '''
Usage of Column Element Usage of Column Element
''' '''
@ -9,7 +9,7 @@ sg.theme('BlueMono')
# Column layout # Column layout
col = [[sg.Text('col Row 1', text_color='white', background_color='blue')], col = [[sg.Text('col Row 1', text_color='white', background_color='blue')],
[sg.Text('col Row 2', text_color='white', background_color='blue'), sg.Input('col input 1')], [sg.Text('col Row 2', text_color='white', background_color='blue', pad=(0,(25,0))),sg.T('Another item'), sg.T('another'), sg.Input('col input 1')],
[sg.Text('col Row 3', text_color='white', background_color='blue'), sg.Input('col input 2')]] [sg.Text('col Row 3', text_color='white', background_color='blue'), sg.Input('col input 2')]]
# Window layout # Window layout
layout = [[sg.Listbox(values=('Listbox Item 1', 'Listbox Item 2', 'Listbox Item 3'), layout = [[sg.Listbox(values=('Listbox Item 1', 'Listbox Item 2', 'Listbox Item 3'),
@ -19,7 +19,7 @@ layout = [[sg.Listbox(values=('Listbox Item 1', 'Listbox Item 2', 'Listbox Item
[sg.OK()]] [sg.OK()]]
# Display the window and get values # Display the window and get values
window = sg.Window('Compact 1-line form with column', layout) window = sg.Window('Compact 1-line form with column', layout, margins=(0,0), element_padding=(0,0))
event, values = window.read() event, values = window.read()
sg.popup(event, values, line_width=200) sg.popup(event, values, line_width=200)

View File

@ -141,7 +141,7 @@ class GameOfLife:
j * (BOX_SIZE) + BOX_SIZE), j * (BOX_SIZE) + BOX_SIZE),
line_color='black', fill_color='yellow') line_color='black', fill_color='yellow')
event, values = self.window.read(timeout=self.delay) event, values = self.window.read(timeout=self.delay)
if event in (None, '-DONE-'): if event in (sg.WIN_CLOSED, '-DONE-'):
sg.popup('Click OK to exit the program...') sg.popup('Click OK to exit the program...')
self.window.close() self.window.close()
exit() exit()
@ -159,7 +159,7 @@ class GameOfLife:
ids[i].append(0) ids[i].append(0)
while True: # Event Loop while True: # Event Loop
event, values = self.window.read() event, values = self.window.read()
if event is None or event == '-DONE-': if event == sg.WIN_CLOSED or event == '-DONE-':
break break
self.window['-S1-OUT-'].update(values['-SLIDER-']) self.window['-S1-OUT-'].update(values['-SLIDER-'])
self.window['-S2-OUT-'].update(values['-SLIDER2-']) self.window['-S2-OUT-'].update(values['-SLIDER2-'])
@ -181,7 +181,7 @@ class GameOfLife:
line_color='black', fill_color='yellow') line_color='black', fill_color='yellow')
ids[box_x][box_y] = id_val ids[box_x][box_y] = id_val
self.old_grid[box_x][box_y] = 1 self.old_grid[box_x][box_y] = 1
if event is None: if event == sg.WIN_CLOSED:
self.window.close() self.window.close()
else: else:
self.window['-DONE-'].update(text='Exit') self.window['-DONE-'].update(text='Exit')

View File

@ -35,7 +35,7 @@ for row in range(16):
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
mouse = values['-GRAPH-'] mouse = values['-GRAPH-']

View File

@ -35,7 +35,7 @@ window['Exit'].set_cursor(cursor='no')
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == '-LINK-': if event == '-LINK-':
# if the text was clicked, open a browser using the text as the address # if the text was clicked, open a browser using the text as the address

View File

@ -168,7 +168,7 @@ old_zoom = False
while True: while True:
event, value = window.read() event, value = window.read()
if event is None and (value is None or value['-PageNumber-'] is None): if event == sg.WIN_CLOSED and (value is None or value['-PageNumber-'] is None):
break break
if event in quit_buttons: if event in quit_buttons:
break break

View File

@ -13,7 +13,6 @@ import itertools
Copyright 2020 PySimpleGUI Copyright 2020 PySimpleGUI
""" """
sg.theme('Dark Red')
def popup_get_date(start_mon=None, start_day=None, start_year=None, begin_at_sunday_plus=0, no_titlebar=True, title='Choose Date', keep_on_top=True, location=(None, None), close_when_chosen=False, icon=None, locale=None, month_names=None, day_abbreviations=None): def popup_get_date(start_mon=None, start_day=None, start_year=None, begin_at_sunday_plus=0, no_titlebar=True, title='Choose Date', keep_on_top=True, location=(None, None), close_when_chosen=False, icon=None, locale=None, month_names=None, day_abbreviations=None):
""" """
@ -129,7 +128,7 @@ def popup_get_date(start_mon=None, start_day=None, start_year=None, begin_at_sun
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Cancel'): if event in (sg.WIN_CLOSED, 'Cancel'):
chosen_mon_day_year = None chosen_mon_day_year = None
break break
if event == 'Ok': if event == 'Ok':

View File

@ -40,7 +40,7 @@ sg.show_debugger_popout_window()
while True: # Your Event Loop while True: # Your Event Loop
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event == 'Enable': elif event == 'Enable':
window.enable_debugger() window.enable_debugger()

View File

@ -37,7 +37,7 @@ counter = 0
while True: # Your Event Loop while True: # Your Event Loop
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event == 'Enable': elif event == 'Enable':
window.enable_debugger() window.enable_debugger()

View File

@ -39,7 +39,7 @@ counter = 0
while True: # Your Event Loop while True: # Your Event Loop
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event == 'Ok': elif event == 'Ok':
print('You clicked Ok.... this is where print output goes') print('You clicked Ok.... this is where print output goes')

View File

@ -23,7 +23,7 @@ while True: # Event Loop
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event != sg.TIMEOUT_KEY: if event != sg.TIMEOUT_KEY:
print(i, event, values) print(i, event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event == 'Popup': elif event == 'Popup':
sg.popup('This is a BLOCKING popup','all windows remain inactive while popup active') sg.popup('This is a BLOCKING popup','all windows remain inactive while popup active')
@ -44,7 +44,7 @@ while True: # Event Loop
# print("win2 ", event) # print("win2 ", event)
if event != sg.TIMEOUT_KEY: if event != sg.TIMEOUT_KEY:
print("win2 ", event) print("win2 ", event)
if event == 'Exit' or event is None: if event == 'Exit' or event == sg.WIN_CLOSED:
# print("Closing window 2", event) # print("Closing window 2", event)
win2_active = False win2_active = False
window2.close() window2.close()

View File

@ -29,7 +29,7 @@ while True:
if window2_active: if window2_active:
event2 = window2.read()[0] event2 = window2.read()[0]
if event2 in (None, 'Exit', '< Prev'): if event2 in (sg.WIN_CLOSED, 'Exit', '< Prev'):
window2_active = False window2_active = False
window2.close() window2.close()
window.un_hide() window.un_hide()
@ -48,7 +48,7 @@ while True:
window3_active = False window3_active = False
window2_active = True window2_active = True
window2.un_hide() window2.un_hide()
elif ev3 in (None, 'Exit'): elif ev3 in (sg.WIN_CLOSED, 'Exit'):
break break
window.close() window.close()

View File

@ -12,7 +12,7 @@ window = sg.Window('Window Title', layout)
while True: while True:
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == 'Show': if event == 'Show':
# change the "output" element to be the value of "input" element # change the "output" element to be the value of "input" element

View File

@ -3,59 +3,69 @@ When creating a new PySimpleGUI program from scratch, start here.
These are the accepted design patterns that cover the two primary use cases These are the accepted design patterns that cover the two primary use cases
1. A "One Shot" window 1. A "One Shot" window
2. A persistent window that stays open after button clicks (uses an event loop) 2. A "One Shot" window in 1 line of code
3. A persistent window that need to perform update of an element before the window.read 3. A persistent window that stays open after button clicks (uses an event loop)
4. A persistent window that need to perform update of an element before the window.read
""" """
# ---------------------------------# # -----------------------------------#
# DESIGN PATTERN 1 - Simple Window # # DESIGN PATTERN 1 - One-shot Window #
# ---------------------------------# # -----------------------------------#
import PySimpleGUI as sg import PySimpleGUI as sg
sg.theme('Dark Blue 3')
layout = [[ sg.Text('My Oneshot') ], layout = [[ sg.Text('My Oneshot') ],
[ sg.Input(key='-IN-') ],
[ sg.Button('OK') ]] [ sg.Button('OK') ]]
window = sg.Window('My Oneshot', layout) window = sg.Window('Design Pattern 1', layout)
event, values = window.read() event, values = window.read()
window.close() window.close()
# ---------------------------------------------#
# DESIGN PATTERN 2 - One-shot Window in 1 line #
# ---------------------------------------------#
import PySimpleGUI as sg
event, values = sg.Window('Design Pattern 2', [[sg.Text('My Oneshot')],[sg.Input(key='-IN-')], [ sg.Button('OK') ]]).read(close=True)
# -------------------------------------# # -------------------------------------#
# DESIGN PATTERN 2 - Persistent Window # # DESIGN PATTERN 3 - Persistent Window #
# -------------------------------------# # -------------------------------------#
import PySimpleGUI as sg import PySimpleGUI as sg
sg.theme('Dark Blue 3') layout = [[sg.Text('My layout')],
[sg.Input(key='-INPUT-')],
[sg.Button('OK'), sg.Button('Cancel')] ]
layout = [[ sg.Text('My layout', text_color='red') ], window = sg.Window('Design Pattern 3 - Persistent Window', layout)
[ sg.Input(key='-INPUT-')],
[ sg.Button('OK'), sg.Button('Cancel') ]]
window = sg.Window('Design Pattern 2 - Persistent Window', layout)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Cancel'): if event == sg.WIN_CLOSED or event == 'Cancel':
break break
window.close() window.close()
# ------------------------------------------------------------------# # ------------------------------------------------------------------#
# DESIGN PATTERN 3 - Persistent Window with "early update" required # # DESIGN PATTERN 4 - Persistent Window with "early update" required #
# ------------------------------------------------------------------# # ------------------------------------------------------------------#
import PySimpleGUI as sg import PySimpleGUI as sg
sg.theme('Dark Blue 3') layout = [[ sg.Text('My layout') ],
[sg.Input(key='-INPUT-')],
layout = [[ sg.Text('My layout', key='-TEXT-KEY-') ], [sg.Text('Some text will be output here', key='-TEXT-KEY-')],
[ sg.Button('OK'), sg.Button('Cancel') ]] [ sg.Button('OK'), sg.Button('Cancel') ]]
window = sg.Window('Design Pattern 3', layout, finalize=True) window = sg.Window('Design Pattern 4', layout, finalize=True)
window['-TEXT-KEY-'].update('NEW Text') # Change the text field. Finalize allows us to do this # Change the text field. Finalize allows us to do this
window['-TEXT-KEY-'].update('Modified before event loop')
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Cancel'): if event == sg.WIN_CLOSED or event == 'Cancel':
break break
if event == 'OK':
window['-TEXT-KEY-'].update(values['-INPUT-'])
window.close() window.close()

View File

@ -46,7 +46,7 @@ def Launcher():
# ---===--- Loop taking in user input and executing appropriate program --- # # ---===--- Loop taking in user input and executing appropriate program --- #
while True: while True:
event, values = window.read() event, values = window.read()
if event == 'EXIT' or event is None: if event == 'EXIT' or event == sg.WIN_CLOSED:
break # exit button clicked break # exit button clicked
if event == 'Program 1': if event == 'Program 1':
print('Run your program 1 here!') print('Run your program 1 here!')

View File

@ -5,15 +5,21 @@ import psutil
""" """
Desktop floating widget - CPU Cores Desktop floating widget - CPU Cores
Uses psutil to display: Uses psutil to display:
CPU usage on each individual core CPU usage of each individual core
Information is updated once a second and is shown as an area graph that scrolls CPU utilization is updated every 500 ms by default
Utiliziation is shown as a scrolling area graph
To achieve a "rainmeter-style" of window, these featurees were used:
An alpha-channel setting of 0.8 to give a little transparency
No titlebar
Grab anywhere, making window easy to move around
Copyright 2020 PySimpleGUI
""" """
GRAPH_WIDTH = 120 # each individual graph size in pixels GRAPH_WIDTH = 120 # each individual graph size in pixels
GRAPH_HEIGHT = 40 GRAPH_HEIGHT = 40
TRANSPARENCY = .8 # how transparent the window looks. 0 = invisible, 1 = normal window TRANSPARENCY = .8 # how transparent the window looks. 0 = invisible, 1 = normal window
NUM_COLS = 4 NUM_COLS = 4
POLL_FREQUENCY = 500 # how often to update graphs in milliseconds POLL_FREQUENCY = 1500 # how often to update graphs in milliseconds
colors = ('#23a0a0', '#56d856', '#be45be', '#5681d8', '#d34545', '#BE7C29') colors = ('#23a0a0', '#56d856', '#be45be', '#5681d8', '#d34545', '#BE7C29')
@ -21,19 +27,22 @@ colors = ('#23a0a0', '#56d856', '#be45be', '#5681d8', '#d34545', '#BE7C29')
class DashGraph(object): class DashGraph(object):
def __init__(self, graph_elem, text_elem, starting_count, color): def __init__(self, graph_elem, text_elem, starting_count, color):
self.graph_current_item = 0 self.graph_current_item = 0
self.graph_elem = graph_elem self.graph_elem = graph_elem # type: sg.Graph
self.text_elem = text_elem self.text_elem = text_elem
self.prev_value = starting_count self.prev_value = starting_count
self.max_sent = 1 self.max_sent = 1
self.color = color self.color = color
self.line_list = [] # list of currently visible lines. Used to delete oild figures
def graph_percentage_abs(self, value): def graph_percentage_abs(self, value):
self.graph_elem.draw_line( self.line_list.append(self.graph_elem.draw_line( # draw a line and add to list of lines
(self.graph_current_item, 0), (self.graph_current_item, 0),
(self.graph_current_item, value), (self.graph_current_item, value),
color=self.color) color=self.color))
if self.graph_current_item >= GRAPH_WIDTH: if self.graph_current_item >= GRAPH_WIDTH:
self.graph_elem.move(-1,0) self.graph_elem.move(-1,0)
self.graph_elem.delete_figure(self.line_list[0]) # delete the oldest line
self.line_list = self.line_list[1:] # remove line id from list of lines
else: else:
self.graph_current_item += 1 self.graph_current_item += 1
@ -41,16 +50,13 @@ class DashGraph(object):
self.text_elem.update(text) self.text_elem.update(text)
def main(): def main():
# A couple of "Uber Elements" that combine several elements and enable bulk edits # A couple of "User defined elements" that combine several elements and enable bulk edits
def Txt(text, **kwargs): def Txt(text, **kwargs):
return(sg.Text(text, font=('Helvetica 8'), **kwargs)) return(sg.Text(text, font=('Helvetica 8'), **kwargs))
def GraphColumn(name, key): def GraphColumn(name, key):
col = sg.Col([[Txt(name, key=key+'_TXT_'), ], return sg.Column([[Txt(name, size=(10,1), key=key+'_TXT_'), ],
[sg.Graph((GRAPH_WIDTH, GRAPH_HEIGHT), (0, 0), (GRAPH_WIDTH, 100), background_color='black', [sg.Graph((GRAPH_WIDTH, GRAPH_HEIGHT), (0, 0), (GRAPH_WIDTH, 100), background_color='black', key=key+'_GRAPH_')]], pad=(2, 2))
key=key+'_GRAPH_')]], pad=(2, 2))
return col
num_cores = len(psutil.cpu_percent(percpu=True)) # get the number of cores in the CPU num_cores = len(psutil.cpu_percent(percpu=True)) # get the number of cores in the CPU
@ -59,15 +65,13 @@ def main():
# the clever Red X graphic # the clever Red X graphic
red_x = "R0lGODlhEAAQAPeQAIsAAI0AAI4AAI8AAJIAAJUAAJQCApkAAJoAAJ4AAJkJCaAAAKYAAKcAAKcCAKcDA6cGAKgAAKsAAKsCAKwAAK0AAK8AAK4CAK8DAqUJAKULAKwLALAAALEAALIAALMAALMDALQAALUAALYAALcEALoAALsAALsCALwAAL8AALkJAL4NAL8NAKoTAKwbAbEQALMVAL0QAL0RAKsREaodHbkQELMsALg2ALk3ALs+ALE2FbgpKbA1Nbc1Nb44N8AAAMIWAMsvAMUgDMcxAKVABb9NBbVJErFYEq1iMrtoMr5kP8BKAMFLAMxKANBBANFCANJFANFEB9JKAMFcANFZANZcANpfAMJUEMZVEc5hAM5pAMluBdRsANR8AM9YOrdERMpIQs1UVMR5WNt8X8VgYMdlZcxtYtx4YNF/btp9eraNf9qXXNCCZsyLeNSLd8SSecySf82kd9qqc9uBgdyBgd+EhN6JgtSIiNuJieGHhOGLg+GKhOKamty1ste4sNO+ueenp+inp+HHrebGrefKuOPTzejWzera1O7b1vLb2/bl4vTu7fbw7ffx7vnz8f///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJAALAAAAAAQABAAAAjUACEJHEiwYEEABniQKfNFgQCDkATQwAMokEU+PQgUFDAjjR09e/LUmUNnh8aBCcCgUeRmzBkzie6EeQBAoAAMXuA8ciRGCaJHfXzUMCAQgYooWN48anTokR8dQk4sELggBhQrU9Q8evSHiJQgLCIIfMDCSZUjhbYuQkLFCRAMAiOQGGLE0CNBcZYmaRIDLqQFGF60eTRoSxc5jwjhACFWIAgMLtgUocJFy5orL0IQRHAiQgsbRZYswbEhBIiCCH6EiJAhAwQMKU5DjHCi9gnZEHMTDAgAOw==" red_x = "R0lGODlhEAAQAPeQAIsAAI0AAI4AAI8AAJIAAJUAAJQCApkAAJoAAJ4AAJkJCaAAAKYAAKcAAKcCAKcDA6cGAKgAAKsAAKsCAKwAAK0AAK8AAK4CAK8DAqUJAKULAKwLALAAALEAALIAALMAALMDALQAALUAALYAALcEALoAALsAALsCALwAAL8AALkJAL4NAL8NAKoTAKwbAbEQALMVAL0QAL0RAKsREaodHbkQELMsALg2ALk3ALs+ALE2FbgpKbA1Nbc1Nb44N8AAAMIWAMsvAMUgDMcxAKVABb9NBbVJErFYEq1iMrtoMr5kP8BKAMFLAMxKANBBANFCANJFANFEB9JKAMFcANFZANZcANpfAMJUEMZVEc5hAM5pAMluBdRsANR8AM9YOrdERMpIQs1UVMR5WNt8X8VgYMdlZcxtYtx4YNF/btp9eraNf9qXXNCCZsyLeNSLd8SSecySf82kd9qqc9uBgdyBgd+EhN6JgtSIiNuJieGHhOGLg+GKhOKamty1ste4sNO+ueenp+inp+HHrebGrefKuOPTzejWzera1O7b1vLb2/bl4vTu7fbw7ffx7vnz8f///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJAALAAAAAAQABAAAAjUACEJHEiwYEEABniQKfNFgQCDkATQwAMokEU+PQgUFDAjjR09e/LUmUNnh8aBCcCgUeRmzBkzie6EeQBAoAAMXuA8ciRGCaJHfXzUMCAQgYooWN48anTokR8dQk4sELggBhQrU9Q8evSHiJQgLCIIfMDCSZUjhbYuQkLFCRAMAiOQGGLE0CNBcZYmaRIDLqQFGF60eTRoSxc5jwjhACFWIAgMLtgUocJFy5orL0IQRHAiQgsbRZYswbEhBIiCCH6EiJAhAwQMKU5DjHCi9gnZEHMTDAgAOw=="
layout = [[ sg.Button('', image_data=red_x, button_color=('black', 'black'), key='Exit', tooltip='Closes window'), layout = [[ sg.Button(image_data=red_x, button_color=('black', 'black'), key='Exit', tooltip='Closes window'),
sg.Text(' CPU Core Usage')] ] sg.Text(' CPU Core Usage')] ]
# add on the graphs # add on the graphs
for rows in range(num_cores//NUM_COLS+1): for rows in range(num_cores//NUM_COLS+1):
row = [] # for cols in range(min(num_cores-rows*NUM_COLS, NUM_COLS)):
for cols in range(min(num_cores-rows*NUM_COLS, NUM_COLS)): layout += [[GraphColumn('CPU '+str(rows*NUM_COLS+cols), '_CPU_'+str(rows*NUM_COLS+cols)) for cols in range(min(num_cores-rows*NUM_COLS, NUM_COLS))]]
row.append(GraphColumn('CPU '+str(rows*NUM_COLS+cols), '_CPU_'+str(rows*NUM_COLS+cols)))
layout.append(row)
# ---------------- Create Window ---------------- # ---------------- Create Window ----------------
window = sg.Window('PSG System Dashboard', layout, window = sg.Window('PSG System Dashboard', layout,
@ -82,28 +86,25 @@ def main():
finalize=True) finalize=True)
# setup graphs & initial values # setup graphs & initial values
graphs = [] graphs = [DashGraph(window['_CPU_'+str(i)+'_GRAPH_'],
for i in range(num_cores):
graphs.append(DashGraph(window['_CPU_'+str(i)+'_GRAPH_'],
window['_CPU_'+str(i) + '_TXT_'], window['_CPU_'+str(i) + '_TXT_'],
0, colors[i%6])) 0, colors[i%6]) for i in range(num_cores) ]
# ---------------- main loop ---------------- # ---------------- main loop ----------------
while True : while True :
# --------- Read and update window once every Polling Frequency -------- # --------- Read and update window once every Polling Frequency --------
event, values = window.read(timeout=POLL_FREQUENCY) event, values = window.read(timeout=POLL_FREQUENCY)
if event in (None, 'Exit'): # Be nice and give an exit if event in (sg.WIN_CLOSED, 'Exit'): # Be nice and give an exit
break break
# read CPU for each core # read CPU for each core
stats = psutil.cpu_percent(percpu=True) stats = psutil.cpu_percent(percpu=True)
# update each graph # update each graph
for i in range(num_cores): for i, util in enumerate(stats):
graphs[i].graph_percentage_abs(stats[i]) graphs[i].graph_percentage_abs(util)
graphs[i].text_display('{} CPU {:2.0f}'.format(i, stats[i])) graphs[i].text_display('{} CPU {:2.0f}'.format(i, util))
window.close() window.close()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
import PySimpleGUI as sg import PySimpleGUI as sg
import time
import random import random
import psutil import psutil
from threading import Thread from threading import Thread
@ -57,8 +56,7 @@ def main():
last_cpu = i = 0 last_cpu = i = 0
prev_x, prev_y = 0, 0 prev_x, prev_y = 0, 0
while True: # the Event Loop while True: # the Event Loop
time.sleep(.5) event, values = window.read(timeout=500)
event, values = window.read(timeout=0)
if event in ('Quit', None): # always give ths user a way out if event in ('Quit', None): # always give ths user a way out
break break
# do CPU measurement and graph it # do CPU measurement and graph it

View File

@ -50,7 +50,7 @@ def main():
sg.Spin([x+1 for x in range(10)], 3, key='spin')] sg.Spin([x+1 for x in range(10)], 3, key='spin')]
] ]
window = sg.Window('CPU Utilization', layout window = sg.Window('CPU Utilization', layout,
no_titlebar=True, keep_on_top=True, alpha_channel=.8, grab_anywhere=True) no_titlebar=True, keep_on_top=True, alpha_channel=.8, grab_anywhere=True)
# start cpu measurement thread # start cpu measurement thread
@ -63,7 +63,7 @@ def main():
# --------- Read and update window -------- # --------- Read and update window --------
event, values = window.read(timeout=timeout_value, timeout_key='Timeout') event, values = window.read(timeout=timeout_value, timeout_key='Timeout')
# --------- Do Button Operations -------- # --------- Do Button Operations --------
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
timeout_value = int(values['spin']) * 1000 timeout_value = int(values['spin']) * 1000

View File

@ -26,7 +26,7 @@ while True:
# --------- Read and update window -------- # --------- Read and update window --------
event, values = window.read(timeout=interval) event, values = window.read(timeout=interval)
# --------- Do Button Operations -------- # --------- Do Button Operations --------
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
interval = int(values['-spin-'])*1000 interval = int(values['-spin-'])*1000
@ -38,4 +38,4 @@ while True:
window['-text-'].update(f'CPU {cpu_percent:02.0f}%') window['-text-'].update(f'CPU {cpu_percent:02.0f}%')
# Broke out of main loop. Close the window. # Broke out of main loop. Close the window.
window.CloseNonBlocking() window.close()

View File

@ -47,7 +47,7 @@ while True:
else: else:
event, values = window.read() event, values = window.read()
# --------- Do Button Operations -------- # --------- Do Button Operations --------
if event in (None, 'Exit'): # ALWAYS give a way out of program if event in (sg.WIN_CLOSED, 'Exit'): # ALWAYS give a way out of program
break break
if event == '-RESET-': if event == '-RESET-':
paused_time = start_time = time_as_int() paused_time = start_time = time_as_int()

View File

@ -115,7 +115,7 @@ def main():
# --------- Read and update window once a second-------- # --------- Read and update window once a second--------
event, values = window.read(timeout=1000) event, values = window.read(timeout=1000)
# Be nice and give an exit, expecially since there is no titlebar # Be nice and give an exit, expecially since there is no titlebar
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
# ----- Network Graphs ----- # ----- Network Graphs -----
netio = psutil.net_io_counters() netio = psutil.net_io_counters()

View File

@ -52,7 +52,7 @@ for key in key_list:
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'exit'): if event in (sg.WIN_CLOSED, 'exit'):
break break
elif event == 'Disable': elif event == 'Disable':
for key in key_list: for key in key_list:

View File

@ -46,7 +46,7 @@ def Launcher():
folder_to_remove = os.path.join(source_path, source_filename[:-3]) folder_to_remove = os.path.join(source_path, source_filename[:-3])
file_to_remove = os.path.join( file_to_remove = os.path.join(
source_path, source_filename[:-3]+'.spec') source_path, source_filename[:-3]+'.spec')
command_line = 'pyinstaller -wF "{}" {} {} {} {}'.format( command_line = 'pyinstaller -wF --clean "{}" {} {} {} {}'.format(
source_file, icon_option, workpath_option, dispath_option, specpath_option) source_file, icon_option, workpath_option, dispath_option, specpath_option)
if event == 'Make EXE': if event == 'Make EXE':

View File

@ -76,7 +76,7 @@ def main():
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == 'Send': if event == 'Send':
if sg.__name__ != 'PySimpleGUIWeb': # auto close popups not yet supported in PySimpleGUIWeb if sg.__name__ != 'PySimpleGUIWeb': # auto close popups not yet supported in PySimpleGUIWeb

View File

@ -30,6 +30,6 @@ window['-IN-'].bind('<FocusIn>', '+INPUT FOCUS+')
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
window.close() window.close()

View File

@ -34,7 +34,7 @@ window = sg.Window('My new window', layout)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
text_elem = window['-text-'] text_elem = window['-text-']
print(event, values) print(event, values)

View File

@ -17,7 +17,7 @@ sz = fontSize
window = sg.Window("Font size selector", layout, grab_anywhere=False) window = sg.Window("Font size selector", layout, grab_anywhere=False)
while True: while True:
event, values = window.read() event, values = window.read()
if event is None or event == 'Quit': if event == sg.WIN_CLOSED or event == 'Quit':
break break
sz_spin = int(values['spin']) sz_spin = int(values['spin'])
sz_slider = int(values['slider']) sz_slider = int(values['slider'])

View File

@ -20,7 +20,7 @@ window = sg.Window('Font string builder', layout)
text_elem = window['-text-'] text_elem = window['-text-']
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
font_string = 'Helvitica ' font_string = 'Helvitica '
font_string += str(values['-slider-']) font_string += str(values['-slider-'])

View File

@ -19,7 +19,7 @@ def Battleship():
while True: # The Event Loop while True: # The Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if randint(1,10) < 5: # simulate a hit or a miss if randint(1,10) < 5: # simulate a hit or a miss
window[event].update('H', button_color=('white','red')) window[event].update('H', button_color=('white','red'))

View File

@ -28,7 +28,7 @@ def Battleship():
while True: # The Event Loop while True: # The Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if randint(1,10) < 5: # simulate a hit or a miss if randint(1,10) < 5: # simulate a hit or a miss
window[event].update('H', button_color=('white','red')) window[event].update('H', button_color=('white','red'))

View File

@ -22,7 +22,7 @@ def Battleship():
while True: # The Event Loop while True: # The Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if randint(1,10) < 5: # simulate a hit or a miss if randint(1,10) < 5: # simulate a hit or a miss
window[event].update('H', button_color=('white','red')) window[event].update('H', button_color=('white','red'))

View File

@ -24,7 +24,7 @@ i = 0
mixer.init() mixer.init()
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
# Get the text and convert to mp3 file # Get the text and convert to mp3 file
tts = gTTS(text=values[0], lang='en',slow=False) tts = gTTS(text=values[0], lang='en',slow=False)

View File

@ -94,7 +94,7 @@ graph_elem.draw_line((0,300),(300,300))
while True: # Event Loop while True: # Event Loop
event, values = window.read(timeout=10) event, values = window.read(timeout=10)
# print(event, values) # print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
area.space.step(0.01) area.space.step(0.01)

View File

@ -33,7 +33,7 @@ start_point = end_point = prior_rect = None
while True: while True:
event, values = window.read() event, values = window.read()
if event is None: if event == sg.WIN_CLOSED:
break # exit break # exit
if event == "-GRAPH-": # if there's a "Graph" event, then it's a mouse if event == "-GRAPH-": # if there's a "Graph" event, then it's a mouse

View File

@ -8,17 +8,18 @@ layout = [[sg.Graph(canvas_size=(400, 400), graph_bottom_left=(0, 0), graph_top_
window = sg.Window('Graph test', layout, finalize=True) window = sg.Window('Graph test', layout, finalize=True)
graph = window['graph'] graph = window['graph'] # type: sg.Graph
circle = graph.draw_circle((75, 75), 25, fill_color='black', line_color='white') circle = graph.draw_circle((75, 75), 25, fill_color='black', line_color='white')
point = graph.draw_point((75, 75), 10, color='green') point = graph.draw_point((75, 75), 10, color='green')
oval = graph.draw_oval((25, 300), (100, 280), fill_color='purple', line_color='purple') oval = graph.draw_oval((25, 300), (100, 280), fill_color='purple', line_color='purple')
rectangle = graph.draw_rectangle((25, 300), (100, 280), line_color='purple') rectangle = graph.draw_rectangle((25, 300), (100, 280), line_color='purple')
line = graph.draw_line((0, 0), (100, 100)) line = graph.draw_line((0, 0), (100, 100))
arc = graph.draw_arc((0, 0), (400, 400), 160, 10, style='arc', arc_color='blue') arc = graph.draw_arc((0, 0), (400, 400), 160, 10, style='arc', arc_color='blue')
poly = graph.draw_polygon(((10,10), (20,0), (40,200), (10,10)), fill_color='green')
while True: while True:
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event is None: if event == sg.WIN_CLOSED:
break break
if event in ('Blue', 'Red'): if event in ('Blue', 'Red'):
graph.TKCanvas.itemconfig(circle, fill=event) graph.TKCanvas.itemconfig(circle, fill=event)
@ -28,5 +29,6 @@ while True:
graph.MoveFigure(oval, 10, 10) graph.MoveFigure(oval, 10, 10)
graph.MoveFigure(rectangle, 10, 10) graph.MoveFigure(rectangle, 10, 10)
graph.MoveFigure(arc, 10, 10) graph.MoveFigure(arc, 10, 10)
graph.MoveFigure(poly, 10, 10)
window.close() window.close()

View File

@ -29,7 +29,7 @@ def main():
[sg.R('Draw Rectangles', 1, key='-RECT-', enable_events=True)], [sg.R('Draw Rectangles', 1, key='-RECT-', enable_events=True)],
[sg.R('Draw Circle', 1, key='-CIRCLE-', enable_events=True)], [sg.R('Draw Circle', 1, key='-CIRCLE-', enable_events=True)],
[sg.R('Draw Line', 1, key='-LINE-', enable_events=True)], [sg.R('Draw Line', 1, key='-LINE-', enable_events=True)],
[sg.R('Draw point', 1, key='-POINT-', enable_events=True)], [sg.R('Draw points', 1, key='-POINT-', enable_events=True)],
[sg.R('Erase item', 1, key='-ERASE-', enable_events=True)], [sg.R('Erase item', 1, key='-ERASE-', enable_events=True)],
[sg.R('Erase all', 1, key='-CLEAR-', enable_events=True)], [sg.R('Erase all', 1, key='-CLEAR-', enable_events=True)],
[sg.R('Send to back', 1, key='-BACK-', enable_events=True)], [sg.R('Send to back', 1, key='-BACK-', enable_events=True)],
@ -40,14 +40,14 @@ def main():
] ]
layout = [[sg.Graph( layout = [[sg.Graph(
canvas_size=(400, 400), canvas_size=(400, 400),
graph_bottom_left=(0, 0), graph_bottom_left=(0, 0),
graph_top_right=(400, 400), graph_top_right=(800, 800),
key="-GRAPH-", key="-GRAPH-",
change_submits=True, # mouse click events enable_events=True,
background_color='lightblue', background_color='lightblue',
drag_submits=True), sg.Col(col) ], drag_submits=True), sg.Col(col) ],
[sg.Text(key='info', size=(60, 1))]] [sg.Text(key='info', size=(60, 1))]]
window = sg.Window("Drawing and Moving Stuff Around", layout, finalize=True) window = sg.Window("Drawing and Moving Stuff Around", layout, finalize=True)
@ -60,7 +60,8 @@ def main():
graph.bind('<Button-3>', '+RIGHT+') graph.bind('<Button-3>', '+RIGHT+')
while True: while True:
event, values = window.read() event, values = window.read()
if event is None: print(event, values)
if event == sg.WIN_CLOSED:
break # exit break # exit
if event in ('-MOVE-', '-MOVEALL-'): if event in ('-MOVE-', '-MOVEALL-'):
graph.Widget.config(cursor='fleur') graph.Widget.config(cursor='fleur')
@ -94,7 +95,7 @@ def main():
elif values['-LINE-']: elif values['-LINE-']:
prior_rect = graph.draw_line(start_point, end_point, width=4) prior_rect = graph.draw_line(start_point, end_point, width=4)
elif values['-POINT-']: elif values['-POINT-']:
prior_rect = graph.draw_point(start_point, size=1) graph.draw_point((x,y), size=8)
elif values['-ERASE-']: elif values['-ERASE-']:
for figure in drag_figures: for figure in drag_figures:
graph.delete_figure(figure) graph.delete_figure(figure)

View File

@ -48,7 +48,7 @@ def main():
while True: while True:
event, values = window.read(timeout=200) event, values = window.read(timeout=200)
if event == 'Quit' or event is None: if event == 'Quit' or event == sg.WIN_CLOSED:
break break
if g_response_time is None or prev_response_time == g_response_time: if g_response_time is None or prev_response_time == g_response_time:
continue continue

View File

@ -43,7 +43,7 @@ window = sg.Window('Graph of Sine Function', layout)
while True: while True:
event, values = window.read() event, values = window.read()
if event is None: if event == sg.WIN_CLOSED:
break break
graph.erase() graph.erase()
draw_axis() draw_axis()

View File

@ -24,7 +24,7 @@ def main():
window = sg.Window('Enter graph size', layout) window = sg.Window('Enter graph size', layout)
event, values = window.read() event, values = window.read()
if event is None or event == 'Cancel': if event == sg.WIN_CLOSED or event == 'Cancel':
return return
CANVAS_SIZE = int(values['w']), int(values['h']) CANVAS_SIZE = int(values['w']), int(values['h'])
@ -54,7 +54,7 @@ def main():
figures = [] figures = []
while True: while True:
event, values = window.read(timeout=0) event, values = window.read(timeout=0)
if event == 'Quit' or event is None: if event == 'Quit' or event == sg.WIN_CLOSED:
break break
graph_offset = random.randint(-10, 10) graph_offset = random.randint(-10, 10)

View File

@ -74,7 +74,7 @@ area.add_balls()
while True: # Event Loop while True: # Event Loop
event, values = window.read(timeout=0) event, values = window.read(timeout=0)
# print(event, values) # print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
area.space.step(0.02) area.space.step(0.02)

View File

@ -24,7 +24,7 @@ window = sg.Window('Window Title', layout, return_keyboard_events=True)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event) print(event)
if event is None or event == 'Exit': if event == sg.WIN_CLOSED or event == 'Exit':
break break
elem = window.find_element_with_focus() elem = window.find_element_with_focus()

View File

@ -88,7 +88,7 @@ while True:
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
# perform button and keyboard operations # perform button and keyboard operations
if event is None: if event == sg.WIN_CLOSED:
break break
elif event in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34'): elif event in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34'):
i += 1 i += 1

View File

@ -5,12 +5,12 @@ import re
Demo of using a borderless window to show possible matches for autocomplete feature Demo of using a borderless window to show possible matches for autocomplete feature
''' '''
def autocomplete_popup_show(text_list): def autocomplete_popup_show(text_list):
layout = [[ sg.Listbox(values=text_list, layout = [[ sg.Listbox(values=text_list,
size=(15, len(text_list)), size=(15, len(text_list)),
change_submits=True, bind_return_key=True, change_submits=True, bind_return_key=True,
key='-FLOATING-LISTBOX-', enable_events=True) ]] key='-FLOATING-LISTBOX-', enable_events=True) ]]
return sg.Window("Borderless Window", return sg.Window("Borderless Window",
layout, layout,
default_element_size=(12, 1), default_element_size=(12, 1),
@ -22,7 +22,6 @@ def autocomplete_popup_show(text_list):
default_button_element_size=(12, 1), default_button_element_size=(12, 1),
location=(1320, 622), finalize=True) location=(1320, 622), finalize=True)
def predict_text(input, lista): def predict_text(input, lista):
pattern = re.compile('.*' + input + '.*') pattern = re.compile('.*' + input + '.*')
return [w for w in lista if re.match(pattern, w)] return [w for w in lista if re.match(pattern, w)]
@ -43,7 +42,7 @@ def main():
while True: # Event Loop while True: # Event Loop
event, values = window.read(timeout=500) event, values = window.read(timeout=500)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event != sg.TIMEOUT_KEY: if event != sg.TIMEOUT_KEY:

View File

@ -14,7 +14,7 @@ window = sg.Window('Window Title', layout)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
# if last char entered not a digit # if last char entered not a digit
if len(values['-INPUT-']) and values['-INPUT-'][-1] not in ('0123456789'): if len(values['-INPUT-']) and values['-INPUT-'][-1] not in ('0123456789'):

View File

@ -17,7 +17,7 @@ window = sg.Window('Window Title', layout)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == 'Invisible': if event == 'Invisible':
window['-COL-'].update(visible=False) window['-COL-'].update(visible=False)

View File

@ -29,7 +29,7 @@ window = sg.Window('My new window', layout,
return_keyboard_events=True) return_keyboard_events=True)
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event is None: if event == sg.WIN_CLOSED:
break break
if event in ('\r', QT_ENTER_KEY1, QT_ENTER_KEY2): # Check for ENTER key if event in ('\r', QT_ENTER_KEY1, QT_ENTER_KEY2): # Check for ENTER key
# go find element with Focus # go find element with Focus

View File

@ -18,7 +18,7 @@ while True:
print('%s - %s' % (event, ord(event))) print('%s - %s' % (event, ord(event)))
else: else:
print(event) print(event)
elif event is None: elif event == sg.WIN_CLOSED:
break break
window.close() window.close()

View File

@ -29,7 +29,7 @@ window = sg.Window('Keypad', layout,
keys_entered = '' keys_entered = ''
while True: while True:
event, values = window.read() # read the form event, values = window.read() # read the form
if event is None: # if the X button clicked, just exit if event == sg.WIN_CLOSED: # if the X button clicked, just exit
break break
if event == 'Clear': # clear keys if clear button if event == 'Clear': # clear keys if clear button
keys_entered = '' keys_entered = ''

View File

@ -128,7 +128,7 @@ def led_clock():
while True: while True:
# Wake up once a second to update the clock and weather # Wake up once a second to update the clock and weather
event, values = gui.window.read(timeout=1000) event, values = gui.window.read(timeout=1000)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
# update clock # update clock
gui.update_clock() gui.update_clock()

View File

@ -35,7 +35,7 @@ window = sg.Window('My new window', layout, default_element_size=(12, 1), auto_s
i = 0 i = 0
while True: # Event Loop while True: # Event Loop
event, value = window.read(timeout=400) event, value = window.read(timeout=400)
if event == 'Exit' or event is None: if event == 'Exit' or event == sg.WIN_CLOSED:
break break
if value is None: if value is None:
break break

View File

@ -22,7 +22,7 @@ i = 0
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == '-B1-': if event == '-B1-':
window.extend_layout(window['-COL1-'], [[sg.T('A New Input Line'), sg.I(key=f'-IN-{i}-')]]) window.extend_layout(window['-COL1-'], [[sg.T('A New Input Line'), sg.I(key=f'-IN-{i}-')]])

View File

@ -297,7 +297,7 @@ def layout8():
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
if event in (None, 'SUBMIT'): if event in (sg.WIN_CLOSED, 'SUBMIT'):
break break
sg.popup('The answers submitted were', values) sg.popup('The answers submitted were', values)
window.close() window.close()

View File

@ -13,7 +13,7 @@ window = sg.Window('Listbox with Search', layout)
# Event Loop # Event Loop
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): # always check for closed window if event in (sg.WIN_CLOSED, 'Exit'): # always check for closed window
break break
if values['-INPUT-'] != '': # if a keystroke entered in search field if values['-INPUT-'] != '': # if a keystroke entered in search field
search = values['-INPUT-'] search = values['-INPUT-']

File diff suppressed because one or more lines are too long

View File

@ -23,78 +23,81 @@ Basic steps are:
# ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE ------------------------------- # ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE -------------------------------
#
# Fixing random state for reproducibility # # Goal is to have your plot contained in the variable "fig"
np.random.seed(19680801) #
# # Fixing random state for reproducibility
# make up some data in the interval ]0, 1[ # np.random.seed(19680801)
y = np.random.normal(loc=0.5, scale=0.4, size=1000) #
y = y[(y > 0) & (y < 1)] # # make up some data in the interval ]0, 1[
y.sort() # y = np.random.normal(loc=0.5, scale=0.4, size=1000)
x = np.arange(len(y)) # y = y[(y > 0) & (y < 1)]
# y.sort()
# plot with various axes scales # x = np.arange(len(y))
plt.figure(1) #
# # plot with various axes scales
# linear # plt.figure(1)
plt.subplot(221) #
plt.plot(x, y) # # linear
plt.yscale('linear') # plt.subplot(221)
plt.title('linear') # plt.plot(x, y)
plt.grid(True) # plt.yscale('linear')
# plt.title('linear')
# plt.grid(True)
#
# # log
# plt.subplot(222)
# plt.plot(x, y)
# plt.yscale('log')
# plt.title('log')
# plt.grid(True)
#
# # symmetric log
# plt.subplot(223)
# plt.plot(x, y - y.mean())
# plt.yscale('symlog', linthreshy=0.01)
# plt.title('symlog')
# plt.grid(True)
#
# # logit
# plt.subplot(224)
# plt.plot(x, y)
# plt.yscale('logit')
# plt.title('logit')
# plt.grid(True)
# plt.gca().yaxis.set_minor_formatter(NullFormatter())
# plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
# wspace=0.35)
# fig = plt.gcf()
#
# log fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
plt.subplot(222) t = np.arange(0, 3, .01)
plt.plot(x, y) fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
plt.gca().yaxis.set_minor_formatter(NullFormatter())
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
fig = plt.gcf() # if using Pyplot then get the figure from the plot
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
# ------------------------------- END OF YOUR MATPLOTLIB CODE ------------------------------- # ------------------------------- END OF YOUR MATPLOTLIB CODE -------------------------------
# ------------------------------- Beginning of Matplotlib helper code ----------------------- # ------------------------------- Beginning of Matplotlib helper code -----------------------
def draw_figure(canvas, figure):
def draw_figure(canvas, figure, loc=(0, 0)):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas) figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw() figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1) figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg return figure_canvas_agg
# ------------------------------- Beginning of GUI CODE ------------------------------- # ------------------------------- Beginning of GUI CODE -------------------------------
# define the window layout # define the window layout
layout = [[sg.Text('Plot test', font='Any 18')], layout = [[sg.Text('Plot test')],
[sg.Canvas(size=(figure_w, figure_h), key='canvas')], [sg.Canvas(key='-CANVAS-')],
[sg.OK(pad=((figure_w / 2, 0), 3), size=(4, 2))]] [sg.Button('Ok')]]
# create the form and show it without the plot # create the form and show it without the plot
window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', layout, finalize=True, element_justification='center', font='Helvetica 18')
layout, finalize=True)
# add the plot to the window # add the plot to the window
fig_canvas_agg = draw_figure(window['canvas'].TKCanvas, fig) fig_canvas_agg = draw_figure(window['-CANVAS-'].TKCanvas, fig)
event, values = window.read() event, values = window.read()

View File

@ -865,7 +865,7 @@ figure_agg = None
while True: while True:
event, values = window.read() event, values = window.read()
# print(event, values) # helps greatly when debugging # print(event, values) # helps greatly when debugging
if event in (None, 'Exit'): # if user closed window or clicked Exit button if event in (sg.WIN_CLOSED, 'Exit'): # if user closed window or clicked Exit button
break break
if figure_agg: if figure_agg:
# ** IMPORTANT ** Clean up previous drawing before drawing again # ** IMPORTANT ** Clean up previous drawing before drawing again

View File

@ -890,7 +890,7 @@ figure_agg = None
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if figure_agg: if figure_agg:

View File

@ -57,7 +57,7 @@ window = sg.Window('Graph with controls', layout)
while True: while True:
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): # always, always give a way out! if event in (sg.WIN_CLOSED, 'Exit'): # always, always give a way out!
break break
elif event is 'Plot': elif event is 'Plot':
# ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE # ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE

View File

@ -16,7 +16,6 @@ from numpy import cos
x = pylab.linspace(-3, 3, 30) x = pylab.linspace(-3, 3, 30)
y = x**2 y = x**2
pylab.plot(x, sin(x)) pylab.plot(x, sin(x))
pylab.plot(x, cos(x), 'r-') pylab.plot(x, cos(x), 'r-')
pylab.plot(x, -sin(x), 'g--') pylab.plot(x, -sin(x), 'g--')

View File

@ -20,7 +20,7 @@ window = sg.Window('Have some Matplotlib....', layout)
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Cancel'): if event in (sg.WIN_CLOSED, 'Cancel'):
break break
elif event == 'Plot': elif event == 'Plot':
draw_plot() draw_plot()

View File

@ -33,7 +33,7 @@ def MediaPlayerGUI():
while True: while True:
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event == 'Exit' or event is None: if event == 'Exit' or event == sg.WIN_CLOSED:
break break
# If a button was pressed, display it on the GUI by updating the text element # If a button was pressed, display it on the GUI by updating the text element
if event != sg.TIMEOUT_KEY: if event != sg.TIMEOUT_KEY:

View File

@ -41,7 +41,7 @@ else:
#------------ The Event Loop ------------# #------------ The Event Loop ------------#
while True: while True:
event, values = window.read(timeout=1000) # run with a timeout so that current location can be updated event, values = window.read(timeout=1000) # run with a timeout so that current location can be updated
if event is None: if event == sg.WIN_CLOSED:
break break
if event == 'play': if event == 'play':

View File

@ -49,7 +49,7 @@ def test_menus():
# ------ Loop & Process button menu choices ------ # # ------ Loop & Process button menu choices ------ #
while True: while True:
event, values = window.read() event, values = window.read()
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
print(event, values) print(event, values)
# ------ Process menu choices ------ # # ------ Process menu choices ------ #

View File

@ -1,12 +1,12 @@
import PySimpleGUI as sg import PySimpleGUI as sg
# import PySimpleGUIQt as sg # import PySimpleGUIQt as sg
print(sg.version)
""" """
Demonstration of how to work with multiple colors when outputting text to a multiline element Demonstration of how to work with multiple colors when outputting text to a multiline element
""" """
sg.theme('Dark Blue 3')
MLINE_KEY = '-MLINE-'+sg.WRITE_ONLY_KEY MLINE_KEY = '-MLINE-'+sg.WRITE_ONLY_KEY
layout = [ [sg.Text('Demonstration of Multiline Element\'s ability to show multiple colors ')], layout = [ [sg.Text('Demonstration of Multiline Element\'s ability to show multiple colors ')],
[sg.Multiline(size=(60,20), key=MLINE_KEY)], [sg.Multiline(size=(60,20), key=MLINE_KEY)],
@ -15,19 +15,21 @@ layout = [ [sg.Text('Demonstration of Multiline Element\'s ability to show mult
window = sg.Window('Demonstration of Multicolored Multline Text', layout) window = sg.Window('Demonstration of Multicolored Multline Text', layout)
# print = lambda *args, **kwargs: window[MLINE_KEY].print(*args, **kwargs, text_color='red')
while True: while True:
event, values = window.read() # type: (str, dict) event, values = window.read() # type: (str, dict)
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if 'Text Blue' in event: if 'Text Blue' in event:
window[MLINE_KEY].update('This is blue text', text_color_for_value='blue', append=True) window[MLINE_KEY].update('This is blue text\n', text_color_for_value='blue', append=True)
if 'Text Green' in event: if 'Text Green' in event:
window[MLINE_KEY].update('This is green text', text_color_for_value='green', append=True) window[MLINE_KEY].update('This is green text\n', text_color_for_value='green', append=True)
if 'Background Blue' in event: if 'Background Blue' in event:
window[MLINE_KEY].update('This is Blue Background', background_color_for_value='blue', append=True) window[MLINE_KEY].update('This is Blue Background\n', background_color_for_value='blue', append=True)
if 'Background Green' in event: if 'Background Green' in event:
window[MLINE_KEY].update('This is Green Backgroundt', background_color_for_value='green', append=True) window[MLINE_KEY].update('This is Green Background\n', background_color_for_value='green', append=True)
if 'White on Green' in event: if 'White on Green' in event:
window[MLINE_KEY].update('This is white text on a green background', text_color_for_value='white', background_color_for_value='green', append=True) window[MLINE_KEY].update('This is white text on a green background', text_color_for_value='white', background_color_for_value='green', append=True)
if event == 'Plain': if event == 'Plain':

View File

@ -28,19 +28,19 @@ window3 = sg.Window('My new window', layout3, location=(800,750), return_keyboar
while True: # Event Loop while True: # Event Loop
event, values = window1.read(timeout=0) event, values = window1.read(timeout=0)
if event is None: if event == sg.WIN_CLOSED:
break break
elif event != '__timeout__': elif event != '__timeout__':
print(event, values) print(event, values)
event, values = window2.read(timeout=0) event, values = window2.read(timeout=0)
if event is None: if event == sg.WIN_CLOSED:
break break
elif event != '__timeout__': elif event != '__timeout__':
print(event, values) print(event, values)
event, values = window3.read(timeout=0) event, values = window3.read(timeout=0)
if event is None: if event == sg.WIN_CLOSED:
break break
elif event != '__timeout__': elif event != '__timeout__':
print(event, values) print(event, values)

View File

@ -2,6 +2,7 @@ import subprocess
import PySimpleGUI as sg import PySimpleGUI as sg
import threading import threading
""" """
Demo - Run a shell command while displaying an animated GIF to inform the user the Demo - Run a shell command while displaying an animated GIF to inform the user the
program is still running. program is still running.
@ -32,5 +33,6 @@ while True:
sg.popup_animated(None) sg.popup_animated(None)
output = proc.__str__().replace('\\r\\n', '\n') output = proc.__str__().replace('\\r\\n', '\n')
sg.popup_scrolled(output) sg.popup_scrolled(output, font='Courier 10')

View File

@ -115,7 +115,7 @@ def the_gui(gui_queue):
while True: while True:
# wait for up to 100 ms for a GUI event # wait for up to 100 ms for a GUI event
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
# --------------- Loop through all messages coming in from threads --------------- # --------------- Loop through all messages coming in from threads ---------------
while True: # loop executes until runs out of messages in Queue while True: # loop executes until runs out of messages in Queue

View File

@ -13,6 +13,8 @@ import PySimpleGUI as sg
# Here we're running a simple "pip list" command and using the built-in animated GIF. # Here we're running a simple "pip list" command and using the built-in animated GIF.
output = sg.shell_with_animation('pip', ('list',), message='Loading...', font='Helvetica 15') output = sg.shell_with_animation('pip', ('list',), message='Loading...', font='Helvetica 15')
sg.popup_scrolled(output, font='Courier 10')
output = sg.shell_with_animation('dir', message='Loading...', font='Helvetica 15')
# output = sg.shell_with_animation(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", message='Loading...', font='Helvetica 15') # output = sg.shell_with_animation(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", message='Loading...', font='Helvetica 15')
sg.popup_scrolled(output, font='Courier 10') sg.popup_scrolled(output, font='Courier 10')

View File

@ -64,7 +64,7 @@ def the_gui():
# --------------------- EVENT LOOP --------------------- # --------------------- EVENT LOOP ---------------------
while True: while True:
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event.startswith('Do') and not thread: elif event.startswith('Do') and not thread:
print('Thread Starting! Long work....sending value of {} seconds'.format(float(values['-SECONDS-']))) print('Thread Starting! Long work....sending value of {} seconds'.format(float(values['-SECONDS-'])))

View File

@ -58,7 +58,7 @@ def the_gui():
# --------------------- EVENT LOOP --------------------- # --------------------- EVENT LOOP ---------------------
while True: while True:
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event.startswith('Do'): elif event.startswith('Do'):
try: try:

View File

@ -72,7 +72,7 @@ def the_gui():
while True: while True:
# wait for up to 100 ms for a GUI event # wait for up to 100 ms for a GUI event
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == 'Go': # clicking "Go" starts a long running work item by starting thread if event == 'Go': # clicking "Go" starts a long running work item by starting thread
window['-OUTPUT-'].update('Starting long work %s' % work_id) window['-OUTPUT-'].update('Starting long work %s' % work_id)

View File

@ -3,17 +3,19 @@ import textwrap
from multiprocessing import Process from multiprocessing import Process
''' '''
Notification Window Demo Program Multiprocessing based Notification Window Demo Program
Shamelessly stolen from PySimpleGUI user ncotrb
The PySimpleGUI code for showing the windows themselves ovolved from code supplied by PySimpleGUI user ncotrb
Displays a small informational window with an Icon and a message in the lower right corner of the display Displays a small informational window with an Icon and a message in the lower right corner of the display
Option to fade in/out or immediatealy display. Option to fade in/out or immediatealy display.
You can click on the notification window to speed things along. The idea is that if you click while fading in, you should immediately see the info. If You can click on the notification window to speed things along. The idea is that if you click while fading in, you should immediately see the info. If you click while info is displaying or while fading out, the window closes immediately.
you click while info is displaying or while fading out, the window closes immediately.
Note - In order to import and use these calls, you must make the call from a "main program". Note - In order to import and use these calls, you must make the call from a "main program".
Copyright 2020 PySimpleGUI
''' '''
@ -37,10 +39,12 @@ image64_success = b'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAA3NCSVQICAjb
def _display_notification(title, message, icon=image64_success, display_duration_in_ms=DEFAULT_DISPLAY_DURATION_IN_MILLISECONDS, fade_in_duration=DEFAULT_FADE_IN_DURATION, alpha=0.9, location=None): def _display_notification(title, message, icon=image64_success, display_duration_in_ms=DEFAULT_DISPLAY_DURATION_IN_MILLISECONDS, fade_in_duration=DEFAULT_FADE_IN_DURATION, alpha=0.9, location=None):
""" """
The PROCESS that is started when a toaster message is to be displayed.
Note that this is not a user callable function.
It does the actual work of creating and showing the window on the screen
Displays a "notification window", usually in the bottom right corner of your display. Has an icon, a title, and a message Displays a "notification window", usually in the bottom right corner of your display. Has an icon, a title, and a message
The window will slowly fade in and out if desired. Clicking on the window will cause it to move through the end the current "phase". For The window will slowly fade in and out if desired. Clicking on the window will cause it to move through the end the current "phase". For example, if the window was fading in and it was clicked, then it would immediately stop fading in and instead be fully visible. It's a way for the user to quickly dismiss the window.
example, if the window was fading in and it was clicked, then it would immediately stop fading in and instead be fully visible. It
a way for the user to quickly dismiss the window.
:param title: (str) Text to be shown at the top of the window in a larger font :param title: (str) Text to be shown at the top of the window in a larger font
:param message: (str) Text message that makes up the majority of the window :param message: (str) Text message that makes up the majority of the window
:param icon: (base64) A base64 encoded PNG/GIF image that will be displayed in the window :param icon: (base64) A base64 encoded PNG/GIF image that will be displayed in the window
@ -94,9 +98,7 @@ def _display_notification(title, message, icon=image64_success, display_duration
def display_notification(title, message, icon=image64_success, display_duration_in_ms=DEFAULT_DISPLAY_DURATION_IN_MILLISECONDS, fade_in_duration=DEFAULT_FADE_IN_DURATION, alpha=0.9, location=None): def display_notification(title, message, icon=image64_success, display_duration_in_ms=DEFAULT_DISPLAY_DURATION_IN_MILLISECONDS, fade_in_duration=DEFAULT_FADE_IN_DURATION, alpha=0.9, location=None):
""" """
Displays a "notification window", usually in the bottom right corner of your display. Has an icon, a title, and a message Displays a "notification window", usually in the bottom right corner of your display. Has an icon, a title, and a message
The window will slowly fade in and out if desired. Clicking on the window will cause it to move through the end the current "phase". For The window will slowly fade in and out if desired. Clicking on the window will cause it to move through the end the current "phase". For example, if the window was fading in and it was clicked, then it would immediately stop fading in and instead be fully visible. It's a way for the user to quickly dismiss the window.
example, if the window was fading in and it was clicked, then it would immediately stop fading in and instead be fully visible. It
a way for the user to quickly dismiss the window.
:param title: (str) Text to be shown at the top of the window in a larger font :param title: (str) Text to be shown at the top of the window in a larger font
:param message: (str) Text message that makes up the majority of the window :param message: (str) Text message that makes up the majority of the window
:param icon: (base64) A base64 encoded PNG/GIF image that will be displayed in the window :param icon: (base64) A base64 encoded PNG/GIF image that will be displayed in the window

View File

@ -4,7 +4,7 @@ window = sg.Window('Demo Application - OpenCV Integration', [[sg.Image(filename=
cap = cv2.VideoCapture(0) # Setup the camera as a capture device cap = cv2.VideoCapture(0) # Setup the camera as a capture device
while True: # The PSG "Event Loop" while True: # The PSG "Event Loop"
event, values = window.read(timeout=20, timeout_key='timeout') # get events for the window with 20ms max wait event, values = window.read(timeout=20, timeout_key='timeout') # get events for the window with 20ms max wait
if event is None: break # if user closed window, quit if event == sg.WIN_CLOSED: break # if user closed window, quit
window['image'].update(data=cv2.imencode('.png', cap.read()[1])[1].tobytes()) # Update image in window window['image'].update(data=cv2.imencode('.png', cap.read()[1])[1].tobytes()) # Update image in window
""" """

View File

@ -29,7 +29,7 @@ def main():
while True: while True:
event, values = window.read(timeout=20) event, values = window.read(timeout=20)
if event == 'Exit' or event is None: if event == 'Exit' or event == sg.WIN_CLOSED:
return return
elif event == 'Record': elif event == 'Record':

View File

@ -59,7 +59,7 @@ cap = cv2.VideoCapture(0)
while True: while True:
event, values = window.read(timeout=0) event, values = window.read(timeout=0)
if event in ('Exit', None): if event in ('Exit', sg.WIN_CLOSED):
break break
# Read image from capture device (camera) # Read image from capture device (camera)
ret, frame = cap.read() ret, frame = cap.read()

View File

@ -123,7 +123,7 @@ while True:
event, values = window.read(timeout=100) event, values = window.read(timeout=100)
zoom = 0 zoom = 0
force_page = False force_page = False
if event is None: if event == sg.WIN_CLOSED:
break break
if event in ("Escape:27",): # this spares me a 'Quit' button! if event in ("Escape:27",): # this spares me a 'Quit' button!

View File

@ -98,7 +98,7 @@ while True:
event, values = window.read() event, values = window.read()
display_index = values['-slider-'] display_index = values['-slider-']
# --------------------- Button & Keyboard --------------------- # --------------------- Button & Keyboard ---------------------
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
elif event in ('MouseWheel:Down', 'Down:40',) and display_index < len(png_files)-1: elif event in ('MouseWheel:Down', 'Down:40',) and display_index < len(png_files)-1:
display_index += 4 display_index += 4

View File

@ -46,7 +46,7 @@ def main():
event, values = window.read() event, values = window.read()
# --------------------- Button & Keyboard --------------------- # --------------------- Button & Keyboard ---------------------
if event is None: if event == sg.WIN_CLOSED:
break break
elif event in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34') and i < len(png_files)-1: elif event in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34') and i < len(png_files)-1:
i += 1 i += 1

View File

@ -39,7 +39,7 @@ window = sg.Window('Window Title', layout, border_depth=5,
while True: # Event Loop while True: # Event Loop
event, values = window.read() event, values = window.read()
print(event, values) print(event, values)
if event in (None, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == 'Remove': if event == 'Remove':
window['-COL2-'].update(visible=False) window['-COL2-'].update(visible=False)

Some files were not shown because too many files have changed in this diff Show More