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
# 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')
# ------ Menu Definition ------ #
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))],
[sg.Spin(values=('Spin Box 1', '2', '3'),
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')],
[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.Submit(tooltip='Click to submit this form'), sg.Cancel()]]
window = sg.Window('Everything bagel', layout, no_titlebar=True,
default_element_size=(40, 1), grab_anywhere=False)
window = sg.Window('Everything bagel', layout)
event, values = window.read()
event, values = window.read(close=True)
sg.popup('Title',
'The results of the window.',
'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
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
# Next demo is to show how to create custom windows with animations
@ -49,7 +49,7 @@ offset = 0
gif = gifs[0]
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
if event in (None, 'Exit', 'Cancel'):
if event in (sg.WIN_CLOSED, 'Exit', 'Cancel'):
break
elif event == '-IMAGE-': # if clicked on the image

View File

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

View File

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

View File

@ -12,7 +12,7 @@ window = sg.Window('Temperature Manager', layout, font='Default -24', return_key
while True: # Event Loop
event, values = window.read(timeout=500) # returns every 500 ms
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
if event == 'Set':
print('setting temperature to ', values['-IN-'])

View File

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

View File

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

View File

@ -36,7 +36,7 @@ recording = have_data = False
while True:
event, values = window.read()
print(event)
if event is None:
if event == sg.WIN_CLOSED:
break
if event == '-Start-':
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
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == '-B-': # if the normal button that changes color and text
down = not down

View File

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

View File

@ -30,7 +30,7 @@ def show_win():
while True: # Event Loop
event, values = window.read()
if event is None or event == '-exit-':
if event == sg.WIN_CLOSED or event == '-exit-':
break
if event == '-minimize-':
# 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
"""
sg.theme('Dark Red')
# sg.theme('Dark Red')
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='-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.Button('Read'), sg.Button('Date Popup'), sg.Exit()]]
@ -17,7 +17,7 @@ window = sg.Window('window', layout)
while True:
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == 'Date Popup':
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:
event, values = window.read()
if event is None:
if event == sg.WIN_CLOSED:
break
if event in ('Blue', 'Red'):
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
event, values = window.read()
print(event, values)
if event is None:
if event == sg.WIN_CLOSED:
break
window.close()

View File

@ -18,7 +18,7 @@ window = sg.Window('Chat window', layout, font=('Helvetica', ' 13'), default_but
while True: # The Event Loop
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
if event == 'SEND':
query = value['-QUERY-'].rstrip()

View File

@ -48,7 +48,7 @@ def ChatBotWithHistory():
window['query'].update('')
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
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()
# ------- OUTPUT results portion ------- #
if event == 'Quit' or event is None:
if event == 'Quit' or event == sg.WIN_CLOSED:
exit(0)
elif event == 'Many buttons':
show_all_colors_on_buttons()

View File

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

View File

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

View File

@ -114,7 +114,7 @@ window = sg.Window('Color Viewer', layout, grab_anywhere=False, font=('any 9'))
# -- Event loop --
while True:
event, values = window.read()
if event is None:
if event == sg.WIN_CLOSED:
break
# -- Create a secondary window that shows white and black text on chosen color
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([
# 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))]],)],
# Information frame
[Frame('Information:', [[Column([[Text('Account:')],
[Frame('Information:', [[Text(), Column([[Text('Account:')],
[Input(key='-ACCOUNT-IN-', size=(19, 1))],
[Text('User Id:')],
[Input(key='-USERID-IN-', size=(19, 1)),
@ -47,7 +47,7 @@ window = Window('Passwords', layout)
while True:
event, values = window.read()
print(event, values)
if event is None:
if event == sg.WIN_CLOSED:
break
window.close()

View File

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

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python
import PySimpleGUI as sg
print(sg.version, sg)
'''
Usage of Column Element
'''
@ -9,7 +9,7 @@ sg.theme('BlueMono')
# Column layout
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')]]
# Window layout
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()]]
# 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()
sg.popup(event, values, line_width=200)

View File

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

View File

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

View File

@ -35,7 +35,7 @@ window['Exit'].set_cursor(cursor='no')
while True: # Event Loop
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == '-LINK-':
# 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:
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
if event in quit_buttons:
break

View File

@ -13,7 +13,6 @@ import itertools
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):
"""
@ -129,7 +128,7 @@ def popup_get_date(start_mon=None, start_day=None, start_year=None, begin_at_sun
while True: # Event Loop
event, values = window.read()
if event in (None, 'Cancel'):
if event in (sg.WIN_CLOSED, 'Cancel'):
chosen_mon_day_year = None
break
if event == 'Ok':

View File

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

View File

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

View File

@ -39,7 +39,7 @@ counter = 0
while True: # Your Event Loop
event, values = window.read(timeout=100)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == 'Ok':
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)
if event != sg.TIMEOUT_KEY:
print(i, event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == 'Popup':
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)
if event != sg.TIMEOUT_KEY:
print("win2 ", event)
if event == 'Exit' or event is None:
if event == 'Exit' or event == sg.WIN_CLOSED:
# print("Closing window 2", event)
win2_active = False
window2.close()

View File

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

View File

@ -12,7 +12,7 @@ window = sg.Window('Window Title', layout)
while True:
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == 'Show':
# 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
1. A "One Shot" window
2. A persistent window that stays open after button clicks (uses an event loop)
3. A persistent window that need to perform update of an element before the window.read
2. A "One Shot" window in 1 line of code
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
sg.theme('Dark Blue 3')
layout = [[ sg.Text('My Oneshot') ],
[ sg.Input(key='-IN-') ],
[ sg.Button('OK') ]]
window = sg.Window('My Oneshot', layout)
window = sg.Window('Design Pattern 1', layout)
event, values = window.read()
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
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') ],
[ sg.Input(key='-INPUT-')],
[ sg.Button('OK'), sg.Button('Cancel') ]]
window = sg.Window('Design Pattern 2 - Persistent Window', layout)
window = sg.Window('Design Pattern 3 - Persistent Window', layout)
while True: # Event Loop
event, values = window.read()
if event in (None, 'Cancel'):
if event == sg.WIN_CLOSED or event == 'Cancel':
break
window.close()
# ------------------------------------------------------------------#
# DESIGN PATTERN 3 - Persistent Window with "early update" required #
# DESIGN PATTERN 4 - Persistent Window with "early update" required #
# ------------------------------------------------------------------#
import PySimpleGUI as sg
sg.theme('Dark Blue 3')
layout = [[ sg.Text('My layout', key='-TEXT-KEY-') ],
layout = [[ sg.Text('My layout') ],
[sg.Input(key='-INPUT-')],
[sg.Text('Some text will be output here', key='-TEXT-KEY-')],
[ 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
event, values = window.read()
if event in (None, 'Cancel'):
if event == sg.WIN_CLOSED or event == 'Cancel':
break
if event == 'OK':
window['-TEXT-KEY-'].update(values['-INPUT-'])
window.close()

View File

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

View File

@ -5,15 +5,21 @@ import psutil
"""
Desktop floating widget - CPU Cores
Uses psutil to display:
CPU usage on each individual core
Information is updated once a second and is shown as an area graph that scrolls
CPU usage of each individual core
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_HEIGHT = 40
TRANSPARENCY = .8 # how transparent the window looks. 0 = invisible, 1 = normal window
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')
@ -21,19 +27,22 @@ colors = ('#23a0a0', '#56d856', '#be45be', '#5681d8', '#d34545', '#BE7C29')
class DashGraph(object):
def __init__(self, graph_elem, text_elem, starting_count, color):
self.graph_current_item = 0
self.graph_elem = graph_elem
self.graph_elem = graph_elem # type: sg.Graph
self.text_elem = text_elem
self.prev_value = starting_count
self.max_sent = 1
self.color = color
self.line_list = [] # list of currently visible lines. Used to delete oild figures
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, value),
color=self.color)
color=self.color))
if self.graph_current_item >= GRAPH_WIDTH:
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:
self.graph_current_item += 1
@ -41,16 +50,13 @@ class DashGraph(object):
self.text_elem.update(text)
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):
return(sg.Text(text, font=('Helvetica 8'), **kwargs))
def GraphColumn(name, key):
col = sg.Col([[Txt(name, key=key+'_TXT_'), ],
[sg.Graph((GRAPH_WIDTH, GRAPH_HEIGHT), (0, 0), (GRAPH_WIDTH, 100), background_color='black',
key=key+'_GRAPH_')]], pad=(2, 2))
return col
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', key=key+'_GRAPH_')]], pad=(2, 2))
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
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')] ]
# add on the graphs
for rows in range(num_cores//NUM_COLS+1):
row = []
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)
# 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))]]
# ---------------- Create Window ----------------
window = sg.Window('PSG System Dashboard', layout,
@ -82,28 +86,25 @@ def main():
finalize=True)
# setup graphs & initial values
graphs = []
for i in range(num_cores):
graphs.append(DashGraph(window['_CPU_'+str(i)+'_GRAPH_'],
graphs = [DashGraph(window['_CPU_'+str(i)+'_GRAPH_'],
window['_CPU_'+str(i) + '_TXT_'],
0, colors[i%6]))
0, colors[i%6]) for i in range(num_cores) ]
# ---------------- main loop ----------------
while True :
# --------- Read and update window once every Polling 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
# read CPU for each core
stats = psutil.cpu_percent(percpu=True)
# update each graph
for i in range(num_cores):
graphs[i].graph_percentage_abs(stats[i])
graphs[i].text_display('{} CPU {:2.0f}'.format(i, stats[i]))
for i, util in enumerate(stats):
graphs[i].graph_percentage_abs(util)
graphs[i].text_display('{} CPU {:2.0f}'.format(i, util))
window.close()
if __name__ == "__main__":
main()

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python
import PySimpleGUI as sg
import time
import random
import psutil
from threading import Thread
@ -57,8 +56,7 @@ def main():
last_cpu = i = 0
prev_x, prev_y = 0, 0
while True: # the Event Loop
time.sleep(.5)
event, values = window.read(timeout=0)
event, values = window.read(timeout=500)
if event in ('Quit', None): # always give ths user a way out
break
# 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')]
]
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)
# start cpu measurement thread
@ -63,7 +63,7 @@ def main():
# --------- Read and update window --------
event, values = window.read(timeout=timeout_value, timeout_key='Timeout')
# --------- Do Button Operations --------
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
timeout_value = int(values['spin']) * 1000

View File

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

View File

@ -47,7 +47,7 @@ while True:
else:
event, values = window.read()
# --------- 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
if event == '-RESET-':
paused_time = start_time = time_as_int()

View File

@ -115,7 +115,7 @@ def main():
# --------- Read and update window once a second--------
event, values = window.read(timeout=1000)
# 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
# ----- Network Graphs -----
netio = psutil.net_io_counters()

View File

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

View File

@ -46,7 +46,7 @@ def Launcher():
folder_to_remove = os.path.join(source_path, source_filename[:-3])
file_to_remove = os.path.join(
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)
if event == 'Make EXE':

View File

@ -76,7 +76,7 @@ def main():
while True: # Event Loop
event, values = window.read()
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == 'Send':
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
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
window.close()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -24,7 +24,7 @@ i = 0
mixer.init()
while True:
event, values = window.read()
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
# Get the text and convert to mp3 file
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
event, values = window.read(timeout=10)
# print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
area.space.step(0.01)

View File

@ -33,7 +33,7 @@ start_point = end_point = prior_rect = None
while True:
event, values = window.read()
if event is None:
if event == sg.WIN_CLOSED:
break # exit
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)
graph = window['graph']
graph = window['graph'] # type: sg.Graph
circle = graph.draw_circle((75, 75), 25, fill_color='black', line_color='white')
point = graph.draw_point((75, 75), 10, color='green')
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')
line = graph.draw_line((0, 0), (100, 100))
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:
event, values = window.read()
print(event, values)
if event is None:
if event == sg.WIN_CLOSED:
break
if event in ('Blue', 'Red'):
graph.TKCanvas.itemconfig(circle, fill=event)
@ -28,5 +29,6 @@ while True:
graph.MoveFigure(oval, 10, 10)
graph.MoveFigure(rectangle, 10, 10)
graph.MoveFigure(arc, 10, 10)
graph.MoveFigure(poly, 10, 10)
window.close()

View File

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

View File

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

View File

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

View File

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

View File

@ -74,7 +74,7 @@ area.add_balls()
while True: # Event Loop
event, values = window.read(timeout=0)
# print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
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
event, values = window.read()
print(event)
if event is None or event == 'Exit':
if event == sg.WIN_CLOSED or event == 'Exit':
break
elem = window.find_element_with_focus()

View File

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

View File

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

View File

@ -14,7 +14,7 @@ window = sg.Window('Window Title', layout)
while True: # Event Loop
event, values = window.read()
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
# if last char entered not a digit
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
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == 'Invisible':
window['-COL-'].update(visible=False)

View File

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

View File

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

View File

@ -29,7 +29,7 @@ window = sg.Window('Keypad', layout,
keys_entered = ''
while True:
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
if event == 'Clear': # clear keys if clear button
keys_entered = ''

View File

@ -128,7 +128,7 @@ def led_clock():
while True:
# Wake up once a second to update the clock and weather
event, values = gui.window.read(timeout=1000)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
# 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
while True: # Event Loop
event, value = window.read(timeout=400)
if event == 'Exit' or event is None:
if event == 'Exit' or event == sg.WIN_CLOSED:
break
if value is None:
break

View File

@ -22,7 +22,7 @@ i = 0
while True: # Event Loop
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == '-B1-':
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
event, values = window.read()
if event in (None, 'SUBMIT'):
if event in (sg.WIN_CLOSED, 'SUBMIT'):
break
sg.popup('The answers submitted were', values)
window.close()

View File

@ -13,7 +13,7 @@ window = sg.Window('Listbox with Search', layout)
# Event Loop
while True:
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
if values['-INPUT-'] != '': # if a keystroke entered in search field
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 -------------------------------
# Fixing random state for reproducibility
np.random.seed(19680801)
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
plt.figure(1)
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
#
# # Goal is to have your plot contained in the variable "fig"
#
# # Fixing random state for reproducibility
# np.random.seed(19680801)
#
# # make up some data in the interval ]0, 1[
# y = np.random.normal(loc=0.5, scale=0.4, size=1000)
# y = y[(y > 0) & (y < 1)]
# y.sort()
# x = np.arange(len(y))
#
# # plot with various axes scales
# plt.figure(1)
#
# # linear
# plt.subplot(221)
# plt.plot(x, y)
# 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
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() # if using Pyplot then get the figure from the plot
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
# ------------------------------- END OF YOUR MATPLOTLIB CODE -------------------------------
# ------------------------------- Beginning of Matplotlib helper code -----------------------
def draw_figure(canvas, figure, loc=(0, 0)):
def draw_figure(canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg
# ------------------------------- Beginning of GUI CODE -------------------------------
# define the window layout
layout = [[sg.Text('Plot test', font='Any 18')],
[sg.Canvas(size=(figure_w, figure_h), key='canvas')],
[sg.OK(pad=((figure_w / 2, 0), 3), size=(4, 2))]]
layout = [[sg.Text('Plot test')],
[sg.Canvas(key='-CANVAS-')],
[sg.Button('Ok')]]
# create the form and show it without the plot
window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI',
layout, finalize=True)
window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', layout, finalize=True, element_justification='center', font='Helvetica 18')
# 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()

View File

@ -865,7 +865,7 @@ figure_agg = None
while True:
event, values = window.read()
# 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
if figure_agg:
# ** IMPORTANT ** Clean up previous drawing before drawing again

View File

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

View File

@ -57,7 +57,7 @@ window = sg.Window('Graph with controls', layout)
while True:
event, values = window.read()
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
elif event is 'Plot':
# ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE

View File

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

View File

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

View File

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

View File

@ -41,7 +41,7 @@ else:
#------------ The Event Loop ------------#
while True:
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
if event == 'play':

View File

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

View File

@ -1,12 +1,12 @@
import PySimpleGUI as sg
# import PySimpleGUIQt as sg
print(sg.version)
"""
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
layout = [ [sg.Text('Demonstration of Multiline Element\'s ability to show multiple colors ')],
[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)
# print = lambda *args, **kwargs: window[MLINE_KEY].print(*args, **kwargs, text_color='red')
while True:
event, values = window.read() # type: (str, dict)
print(event, values)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
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:
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:
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:
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:
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':

View File

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

View File

@ -2,6 +2,7 @@ import subprocess
import PySimpleGUI as sg
import threading
"""
Demo - Run a shell command while displaying an animated GIF to inform the user the
program is still running.
@ -32,5 +33,6 @@ while True:
sg.popup_animated(None)
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:
# wait for up to 100 ms for a GUI event
event, values = window.read(timeout=100)
if event in (None, 'Exit'):
if event in (sg.WIN_CLOSED, 'Exit'):
break
# --------------- Loop through all messages coming in from threads ---------------
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.
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')
sg.popup_scrolled(output, font='Courier 10')

View File

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

View File

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

View File

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

View File

@ -3,17 +3,19 @@ import textwrap
from multiprocessing import Process
'''
Notification Window Demo Program
Shamelessly stolen from PySimpleGUI user ncotrb
Multiprocessing based Notification Window Demo Program
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
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 click while info is displaying or while fading out, the window closes immediately.
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.
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):
"""
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
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
a way for the user to quickly dismiss the window.
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.
: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 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):
"""
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
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.
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.
: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 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
while True: # The PSG "Event Loop"
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
"""

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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