diff --git a/ButtonClick.wav b/ButtonClick.wav new file mode 100644 index 000000000..f774f70e4 Binary files /dev/null and b/ButtonClick.wav differ diff --git a/ButtonGraphics/Exit.png b/ButtonGraphics/Exit.png new file mode 100644 index 000000000..f2ef87d2f Binary files /dev/null and b/ButtonGraphics/Exit.png differ diff --git a/ButtonGraphics/Loop.png b/ButtonGraphics/Loop.png new file mode 100644 index 000000000..cb303d8f8 Binary files /dev/null and b/ButtonGraphics/Loop.png differ diff --git a/ButtonGraphics/Next.png b/ButtonGraphics/Next.png new file mode 100644 index 000000000..c331ac4a3 Binary files /dev/null and b/ButtonGraphics/Next.png differ diff --git a/ButtonGraphics/Pause.png b/ButtonGraphics/Pause.png new file mode 100644 index 000000000..284b1e52e Binary files /dev/null and b/ButtonGraphics/Pause.png differ diff --git a/ButtonGraphics/Restart.png b/ButtonGraphics/Restart.png new file mode 100644 index 000000000..8f30e7cb6 Binary files /dev/null and b/ButtonGraphics/Restart.png differ diff --git a/ButtonGraphics/Rewind.png b/ButtonGraphics/Rewind.png new file mode 100644 index 000000000..af1872973 Binary files /dev/null and b/ButtonGraphics/Rewind.png differ diff --git a/ButtonGraphics/RobotBack.png b/ButtonGraphics/RobotBack.png new file mode 100644 index 000000000..dfb51e5a2 Binary files /dev/null and b/ButtonGraphics/RobotBack.png differ diff --git a/ButtonGraphics/RobotForward.png b/ButtonGraphics/RobotForward.png new file mode 100644 index 000000000..91bdfc065 Binary files /dev/null and b/ButtonGraphics/RobotForward.png differ diff --git a/ButtonGraphics/RobotLeft.png b/ButtonGraphics/RobotLeft.png new file mode 100644 index 000000000..2b3d89e6f Binary files /dev/null and b/ButtonGraphics/RobotLeft.png differ diff --git a/ButtonGraphics/RobotRight.png b/ButtonGraphics/RobotRight.png new file mode 100644 index 000000000..fc7549f1d Binary files /dev/null and b/ButtonGraphics/RobotRight.png differ diff --git a/ButtonGraphics/Stop.png b/ButtonGraphics/Stop.png new file mode 100644 index 000000000..28c7a0d1a Binary files /dev/null and b/ButtonGraphics/Stop.png differ diff --git a/Color-Guide.png b/Color-Guide.png new file mode 100644 index 000000000..bd9edbe4a Binary files /dev/null and b/Color-Guide.png differ diff --git a/Color-names.png b/Color-names.png new file mode 100644 index 000000000..f81654f70 Binary files /dev/null and b/Color-names.png differ diff --git a/Colours.gif b/Colours.gif new file mode 100644 index 000000000..e730fd303 Binary files /dev/null and b/Colours.gif differ diff --git a/Demo_All_Widgets.py b/Demo_All_Widgets.py new file mode 100644 index 000000000..939a1ad69 --- /dev/null +++ b/Demo_All_Widgets.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +sg.ChangeLookAndFeel('GreenTan') + +# ------ Menu Definition ------ # +menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']], + ['&Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ], + ['&Help', '&About...'], ] + +# ------ Column Definition ------ # +column1 = [[sg.Text('Column 1', background_color='#F7F3EC', 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'), initial_value='Spin Box 2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] + +layout = [ + [sg.Menu(menu_def, tearoff=True)], + [sg.Text('All graphic widgets in one form!', size=(30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text')], + [sg.Frame(layout=[ + [sg.Checkbox('Checkbox', size=(10,1)), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10,1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), + sg.Multiline(default_text='A second multi-line', size=(35, 3))], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], + [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), + sg.Frame('Labelled Group',[[ + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), + sg.Column(column1, background_color='#F7F3EC')]])], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder'), sg.FolderBrowse()], + [sg.Submit(tooltip='Click to submit this form'), sg.Cancel()] + ] + +window = sg.Window('Everything bagel', default_element_size=(40, 1), grab_anywhere=False).Layout(layout) + +button, values = window.Read() + +sg.Popup('Title', + 'The results of the window.', + 'The button clicked was "{}"'.format(button), + 'The values are', values) + + diff --git a/Demo_Borderless_Window.py b/Demo_Borderless_Window.py new file mode 100644 index 000000000..f1e07b364 --- /dev/null +++ b/Demo_Borderless_Window.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +""" +Turn off padding in order to get a really tight looking layout. +""" + +sg.ChangeLookAndFeel('Dark') +sg.SetOptions(element_padding=(0, 0)) +layout = [[sg.T('User:', pad=((3, 0), 0)), sg.OptionMenu(values=('User 1', 'User 2'), size=(20, 1)), + sg.T('0', size=(8, 1))], + [sg.T('Customer:', pad=((3, 0), 0)), sg.OptionMenu(values=('Customer 1', 'Customer 2'), size=(20, 1)), + sg.T('1', size=(8, 1))], + [sg.T('Notes:', pad=((3, 0), 0)), sg.In(size=(44, 1), background_color='white', text_color='black')], + [sg.ReadButton('Start', button_color=('white', 'black')), + sg.ReadButton('Stop', button_color=('gray50', 'black')), + sg.ReadButton('Reset', button_color=('white', '#9B0023')), + sg.ReadButton('Submit', button_color=('gray60', 'springgreen4')), + sg.Button('Exit', button_color=('white', '#00406B'))]] + +window = sg.Window("Time Tracker", default_element_size=(12, 1), text_justification='r', auto_size_text=False, + auto_size_buttons=False, no_titlebar=True, + default_button_element_size=(12, 1)) + +window.Layout(layout) + +while True: + button, values = window.Read() + if button is None or button == 'Exit': + break + + diff --git a/Demo_Button_Click.py b/Demo_Button_Click.py new file mode 100644 index 000000000..28528a467 --- /dev/null +++ b/Demo_Button_Click.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +import winsound + + +sg.ChangeLookAndFeel('Dark') +sg.SetOptions(element_padding=(0,0)) + +layout = [ + [sg.ReadButton('Start', button_color=('white', 'black'), key='start'), + sg.ReadButton('Stop', button_color=('white', 'black'), key='stop'), + sg.ReadButton('Reset', button_color=('white', 'firebrick3'), key='reset'), + sg.ReadButton('Submit', button_color=('white', 'springgreen4'), key='submit')] + ] + +window = sg.Window("Button Click", default_element_size=(12,1), text_justification='r', auto_size_text=False, auto_size_buttons=False, default_button_element_size=(12,1), use_default_focus=False).Layout(layout).Finalize() + +window.FindElement('submit').Update(disabled=True) + +recording = have_data = False +while True: + button, values = window.Read() + if button is None: + sys.exit(69) + winsound.PlaySound("ButtonClick.wav", 1) diff --git a/Demo_Button_States.py b/Demo_Button_States.py new file mode 100644 index 000000000..729fa5ba6 --- /dev/null +++ b/Demo_Button_States.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +""" +Demonstrates using a "tight" layout with a Dark theme. +Shows how button states can be controlled by a user application. The program manages the disabled/enabled +states for buttons and changes the text color to show greyed-out (disabled) buttons +""" + +sg.ChangeLookAndFeel('Dark') +sg.SetOptions(element_padding=(0,0)) + +layout = [[sg.T('User:', pad=((3,0),0)), sg.OptionMenu(values = ('User 1', 'User 2'), size=(20,1)), sg.T('0', size=(8,1))], + [sg.T('Customer:', pad=((3,0),0)), sg.OptionMenu(values=('Customer 1', 'Customer 2'), size=(20,1)), sg.T('1', size=(8,1))], + [sg.T('Notes:', pad=((3,0),0)), sg.In(size=(44,1), background_color='white', text_color='black')], + [sg.ReadButton('Start', button_color=('white', 'black'), key='Start'), + sg.ReadButton('Stop', button_color=('white', 'black'), key='Stop'), + sg.ReadButton('Reset', button_color=('white', 'firebrick3'), key='Reset'), + sg.ReadButton('Submit', button_color=('white', 'springgreen4'), key='Submit')]] + +window = sg.Window("Time Tracker", default_element_size=(12,1), text_justification='r', auto_size_text=False, auto_size_buttons=False, + default_button_element_size=(12,1)).Layout(layout).Finalize() + + +for key, state in {'Start': False, 'Stop': True, 'Reset': True, 'Submit': True}.items(): + window.FindElement(key).Update(disabled=state) + +recording = have_data = False +while True: + button, values = window.Read() + print(button) + if button is None: + sys.exit(69) + if button is 'Start': + for key, state in {'Start':True, 'Stop':False, 'Reset':False, 'Submit':True}.items(): + window.FindElement(key).Update(disabled=state) + recording = True + elif button is 'Stop' and recording: + [window.FindElement(key).Update(disabled=value) for key,value in {'Start':False, 'Stop':True, 'Reset':False, 'Submit':False}.items()] + recording = False + have_data = True + elif button is 'Reset': + [window.FindElement(key).Update(disabled=value) for key,value in {'Start':False, 'Stop':True, 'Reset':True, 'Submit':True}.items()] + recording = False + have_data = False + elif button is 'Submit' and have_data: + [window.FindElement(key).Update(disabled=value) for key,value in {'Start':False, 'Stop':True, 'Reset':True, 'Submit':False}.items()] + recording = False diff --git a/Demo_Calendar.py b/Demo_Calendar.py new file mode 100644 index 000000000..0b2df6037 --- /dev/null +++ b/Demo_Calendar.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[sg.T('Calendar Test')], + [sg.In('', size=(20,1), key='input')], + [sg.CalendarButton('Choose Date', target='input', key='date')], + [sg.Ok(key=1)]] + +window = sg.Window('Calendar', grab_anywhere=False).Layout(layout) +b,v = window.Read() +sg.Popup(v['input']) diff --git a/Demo_Canvas.py b/Demo_Canvas.py new file mode 100644 index 000000000..22d77b04b --- /dev/null +++ b/Demo_Canvas.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [ + [sg.Canvas(size=(150, 150), background_color='red', key='canvas')], + [sg.T('Change circle color to:'), sg.ReadButton('Red'), sg.ReadButton('Blue')] + ] + +window = sg.Window('Canvas test').Layout(layout).Finalize() + +cir = window.FindElement('canvas').TKCanvas.create_oval(50, 50, 100, 100) + +while True: + button, values = window.Read() + if button is None: + break + if button is 'Blue': + window.FindElement('canvas').TKCanvas.itemconfig(cir, fill = "Blue") + elif button is 'Red': + window.FindElement('canvas').TKCanvas.itemconfig(cir, fill = "Red") diff --git a/Demo_Chat.py b/Demo_Chat.py new file mode 100644 index 000000000..5b235c4c8 --- /dev/null +++ b/Demo_Chat.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +''' +A chat window. Add call to your send-routine, print the response and you're done +''' + +sg.ChangeLookAndFeel('GreenTan') # give our window a spiffy set of colors + +layout = [[sg.Text('Your output will go here', size=(40, 1))], + [sg.Output(size=(127, 30), font=('Helvetica 10'))], + [sg.Multiline(size=(85, 5), enter_submits=True, key='query'), + sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True), + sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]] + +window = sg.Window('Chat window', default_element_size=(30, 2), font=('Helvetica',' 13'), default_button_element_size=(8,2)).Layout(layout) + +# ---===--- Loop taking in user input and using it --- # +while True: + (button, value) = window.Read() + if button is 'SEND': + query = value['query'].rstrip() + # EXECUTE YOUR COMMAND HERE + print('The command you entered was {}'.format(query)) + elif button is None or button is 'EXIT': # quit if exit button or X + break +sys.exit(69) + diff --git a/Demo_Chat_With_History.py b/Demo_Chat_With_History.py new file mode 100644 index 000000000..652d4ca05 --- /dev/null +++ b/Demo_Chat_With_History.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +''' +A chatbot with history +Scroll up and down through prior commands using the arrow keys +Special keyboard keys: + Up arrow - scroll up in commands + Down arrow - scroll down in commands + Escape - clear current command + Control C - exit form +''' + +def ChatBotWithHistory(): + # ------- Make a new Window ------- # + sg.ChangeLookAndFeel('GreenTan') # give our form a spiffy set of colors + + layout = [[sg.Text('Your output will go here', size=(40, 1))], + [sg.Output(size=(127, 30), font=('Helvetica 10'))], + [sg.T('Command History'), sg.T('', size=(20,3), key='history')], + [sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False), + sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True), + sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]] + + window = sg.Window('Chat window with history', default_element_size=(30, 2), font=('Helvetica',' 13'), default_button_element_size=(8,2), return_keyboard_events=True).Layout(layout) + + # ---===--- Loop taking in user input and using it --- # + command_history = [] + history_offset = 0 + while True: + (button, value) = window.Read() + if button is 'SEND': + query = value['query'].rstrip() + # EXECUTE YOUR COMMAND HERE + print('The command you entered was {}'.format(query)) + command_history.append(query) + history_offset = len(command_history)-1 + window.FindElement('query').Update('') # manually clear input because keyboard events blocks clear + window.FindElement('history').Update('\n'.join(command_history[-3:])) + elif button is None or button is 'EXIT': # quit if exit button or X + break + elif 'Up' in button and len(command_history): + command = command_history[history_offset] + history_offset -= 1 * (history_offset > 0) # decrement is not zero + window.FindElement('query').Update(command) + elif 'Down' in button and len(command_history): + history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list + command = command_history[history_offset] + window.FindElement('query').Update(command) + elif 'Escape' in button: + window.FindElement('query').Update('') + + sys.exit(69) + + +ChatBotWithHistory() diff --git a/Demo_Chatterbot.py b/Demo_Chatterbot.py new file mode 100644 index 000000000..47ad334bc --- /dev/null +++ b/Demo_Chatterbot.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +from chatterbot import ChatBot +import chatterbot.utils + + +''' +Demo_Chatterbot.py +A GUI wrapped arouind the Chatterbot package. +The GUI is used to show progress bars during the training process and +to collect user input that is sent to the chatbot. The reply is displayed in the GUI window +''' + +# Create the 'Trainer GUI' +# The Trainer GUI consists of a lot of progress bars stacked on top of each other +sg.ChangeLookAndFeel('GreenTan') +sg.DebugWin() +MAX_PROG_BARS = 20 # number of training sessions +bars = [] +texts = [] +training_layout = [[sg.T('TRAINING PROGRESS', size=(20, 1), font=('Helvetica', 17))], ] +for i in range(MAX_PROG_BARS): + bars.append(sg.ProgressBar(100, size=(30, 4))) + texts.append(sg.T(' ' * 20, size=(20, 1), justification='right')) + training_layout += [[texts[i], bars[i]],] # add a single row + +training_window = sg.Window('Training').Layout(training_layout) +current_bar = 0 + +# callback function for training runs +def print_progress_bar(description, iteration_counter, total_items, progress_bar_length=20): + global current_bar + global bars + global texts + global training_window + # update the window and the bars + button, values = training_window.ReadNonBlocking() + if button is None and values is None: # if user closed the window on us, exit + sys.exit(69) + if bars[current_bar].UpdateBar(iteration_counter, max=total_items) is False: + sys.exit(69) + texts[current_bar].Update(description) # show the training dataset name + if iteration_counter == total_items: + current_bar += 1 + +# redefine the chatbot text based progress bar with a graphical one +chatterbot.utils.print_progress_bar = print_progress_bar + +chatbot = ChatBot('Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer') + +# Train based on the english corpus +chatbot.train("chatterbot.corpus.english") + +################# GUI ################# + +layout = [[sg.Output(size=(80, 20))], + [sg.Multiline(size=(70, 5), enter_submits=True), + sg.ReadButton('SEND', bind_return_key=True), sg.ReadButton('EXIT')]] + +window = sg.Window('Chat Window', auto_size_text=True, default_element_size=(30, 2)).Layout(layout) + +# ---===--- Loop taking in user input and using it to query HowDoI web oracle --- # +while True: + button, (value,) = window.Read() + if button is not 'SEND': + break + string = value.rstrip() + print(' '+string) + # send the user input to chatbot to get a response + response = chatbot.get_response(value.rstrip()) + print(response) \ No newline at end of file diff --git a/Demo_Color.py b/Demo_Color.py new file mode 100644 index 000000000..5dcc23af7 --- /dev/null +++ b/Demo_Color.py @@ -0,0 +1,1728 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +MY_WINDOW_ICON = 'E:\\TheRealMyDocs\\Icons\\The Planets\\jupiter.ico' +reverse = {} +colorhex = {} + +colors = { + "abbey" : ( 76, 79, 86), + "acadia" : ( 27, 20, 4), + "acapulco" : (124, 176, 161), + "aero blue" : (201, 255, 229), + "affair" : (113, 70, 147), + "akaroa" : (212, 196, 168), + "alabaster" : (250, 250, 250), + "albescent white" : (245, 233, 211), + "algae green" : (147, 223, 184), + "alice blue" : (240, 248, 255), + "alizarin crimson" : (227, 38, 54), + "allports" : ( 0, 118, 163), + "almond" : (238, 217, 196), + "almond frost" : (144, 123, 113), + "alpine" : (175, 143, 44), + "alto" : (219, 219, 219), + "aluminium" : (169, 172, 182), + "amaranth" : (229, 43, 80), + "amazon" : ( 59, 122, 87), + "amber" : (255, 191, 0), + "americano" : (135, 117, 110), + "amethyst" : (153, 102, 204), + "amethyst smoke" : (163, 151, 180), + "amour" : (249, 234, 243), + "amulet" : (123, 159, 128), + "anakiwa" : (157, 229, 255), + "antique brass" : (200, 138, 101), + "antique bronze" : (112, 74, 7), + "anzac" : (224, 182, 70), + "apache" : (223, 190, 111), + "apple" : ( 79, 168, 61), + "apple blossom" : (175, 77, 67), + "apple green" : (226, 243, 236), + "apricot" : (235, 147, 115), + "apricot peach" : (251, 206, 177), + "apricot white" : (255, 254, 236), + "aqua deep" : ( 1, 75, 67), + "aqua forest" : ( 95, 167, 119), + "aqua haze" : (237, 245, 245), + "aqua island" : (161, 218, 215), + "aqua spring" : (234, 249, 245), + "aqua squeeze" : (232, 245, 242), + "aquamarine" : (127, 255, 212), + "aquamarine blue" : (113, 217, 226), + "arapawa" : ( 17, 12, 108), + "armadillo" : ( 67, 62, 55), + "arrowtown" : (148, 135, 113), + "ash" : (198, 195, 181), + "asparagus" : (123, 160, 91), + "asphalt" : ( 19, 10, 6), + "astra" : (250, 234, 185), + "astral" : ( 50, 125, 160), + "astronaut" : ( 40, 58, 119), + "astronaut blue" : ( 1, 62, 98), + "athens gray" : (238, 240, 243), + "aths special" : (236, 235, 206), + "atlantis" : (151, 205, 45), + "atoll" : ( 10, 111, 117), + "atomic tangerine" : (255, 153, 102), + "au chico" : (151, 96, 93), + "aubergine" : ( 59, 9, 16), + "australian mint" : (245, 255, 190), + "avocado" : (136, 141, 101), + "axolotl" : ( 78, 102, 73), + "azalea" : (247, 200, 218), + "aztec" : ( 13, 28, 25), + "azure" : ( 49, 91, 161), + "azure radiance" : ( 0, 127, 255), + "baby blue" : (224, 255, 255), + "bahama blue" : ( 2, 99, 149), + "bahia" : (165, 203, 12), + "baja white" : (255, 248, 209), + "bali hai" : (133, 159, 175), + "baltic sea" : ( 42, 38, 48), + "bamboo" : (218, 99, 4), + "banana mania" : (251, 231, 178), + "bandicoot" : (133, 132, 112), + "barberry" : (222, 215, 23), + "barley corn" : (166, 139, 91), + "barley white" : (255, 244, 206), + "barossa" : ( 68, 1, 45), + "bastille" : ( 41, 33, 48), + "battleship gray" : (130, 143, 114), + "bay leaf" : (125, 169, 141), + "bay of many" : ( 39, 58, 129), + "bazaar" : (152, 119, 123), + "bean " : ( 61, 12, 2), + "beauty bush" : (238, 193, 190), + "beaver" : (146, 111, 91), + "beeswax" : (254, 242, 199), + "beige" : (245, 245, 220), + "bermuda" : (125, 216, 198), + "bermuda gray" : (107, 139, 162), + "beryl green" : (222, 229, 192), + "bianca" : (252, 251, 243), + "big stone" : ( 22, 42, 64), + "bilbao" : ( 50, 124, 20), + "biloba flower" : (178, 161, 234), + "birch" : ( 55, 48, 33), + "bird flower" : (212, 205, 22), + "biscay" : ( 27, 49, 98), + "bismark" : ( 73, 113, 131), + "bison hide" : (193, 183, 164), + "bistre" : ( 61, 43, 31), + "bitter" : (134, 137, 116), + "bitter lemon" : (202, 224, 13), + "bittersweet" : (254, 111, 94), + "bizarre" : (238, 222, 218), + "black" : ( 0, 0, 0), + "black bean" : ( 8, 25, 16), + "black forest" : ( 11, 19, 4), + "black haze" : (246, 247, 247), + "black marlin" : ( 62, 44, 28), + "black olive" : ( 36, 46, 22), + "black pearl" : ( 4, 19, 34), + "black rock" : ( 13, 3, 50), + "black rose" : (103, 3, 45), + "black russian" : ( 10, 0, 28), + "black squeeze" : (242, 250, 250), + "black white" : (255, 254, 246), + "blackberry" : ( 77, 1, 53), + "blackcurrant" : ( 50, 41, 58), + "blaze orange" : (255, 102, 0), + "bleach white" : (254, 243, 216), + "bleached cedar" : ( 44, 33, 51), + "blizzard blue" : (163, 227, 237), + "blossom" : (220, 180, 188), + "blue" : ( 0, 0, 255), + "blue bayoux" : ( 73, 102, 121), + "blue bell" : (153, 153, 204), + "blue chalk" : (241, 233, 255), + "blue charcoal" : ( 1, 13, 26), + "blue chill" : ( 12, 137, 144), + "blue diamond" : ( 56, 4, 116), + "blue dianne" : ( 32, 72, 82), + "blue gem" : ( 44, 14, 140), + "blue haze" : (191, 190, 216), + "blue lagoon" : ( 1, 121, 135), + "blue marguerite" : (118, 102, 198), + "blue ribbon" : ( 0, 102, 255), + "blue romance" : (210, 246, 222), + "blue smoke" : (116, 136, 129), + "blue stone" : ( 1, 97, 98), + "blue violet" : (100, 86, 183), + "blue whale" : ( 4, 46, 76), + "blue zodiac" : ( 19, 38, 77), + "blumine" : ( 24, 88, 122), + "blush" : (180, 70, 104), + "blush pink" : (255, 111, 255), + "bombay" : (175, 177, 184), + "bon jour" : (229, 224, 225), + "bondi blue" : ( 0, 149, 182), + "bone" : (228, 209, 192), + "bordeaux" : ( 92, 1, 32), + "bossanova" : ( 78, 42, 90), + "boston blue" : ( 59, 145, 180), + "botticelli" : (199, 221, 229), + "bottle green" : ( 9, 54, 36), + "boulder" : (122, 122, 122), + "bouquet" : (174, 128, 158), + "bourbon" : (186, 111, 30), + "bracken" : ( 74, 42, 4), + "brandy" : (222, 193, 150), + "brandy punch" : (205, 132, 41), + "brandy rose" : (187, 137, 131), + "breaker bay" : ( 93, 161, 159), + "brick red" : (198, 45, 66), + "bridal heath" : (255, 250, 244), + "bridesmaid" : (254, 240, 236), + "bright gray" : ( 60, 65, 81), + "bright green" : (102, 255, 0), + "bright red" : (177, 0, 0), + "bright sun" : (254, 211, 60), + "bright turquoise" : ( 8, 232, 222), + "brilliant rose" : (246, 83, 166), + "brink pink" : (251, 96, 127), + "bronco" : (171, 161, 150), + "bronze" : ( 63, 33, 9), + "bronze olive" : ( 78, 66, 12), + "bronzetone" : ( 77, 64, 15), + "broom" : (255, 236, 19), + "brown" : (150, 75, 0), + "brown bramble" : ( 89, 40, 4), + "brown derby" : ( 73, 38, 21), + "brown pod" : ( 64, 24, 1), + "brown rust" : (175, 89, 62), + "brown tumbleweed" : ( 55, 41, 14), + "bubbles" : (231, 254, 255), + "buccaneer" : ( 98, 47, 48), + "bud" : (168, 174, 156), + "buddha gold" : (193, 160, 4), + "buff" : (240, 220, 130), + "bulgarian rose" : ( 72, 6, 7), + "bull shot" : (134, 77, 30), + "bunker" : ( 13, 17, 23), + "bunting" : ( 21, 31, 76), + "burgundy" : (144, 0, 32), + "burnham" : ( 0, 46, 32), + "burning orange" : (255, 112, 52), + "burning sand" : (217, 147, 118), + "burnt maroon" : ( 66, 3, 3), + "burnt orange" : (204, 85, 0), + "burnt sienna" : (233, 116, 81), + "burnt umber" : (138, 51, 36), + "bush" : ( 13, 46, 28), + "buttercup" : (243, 173, 22), + "buttered rum" : (161, 117, 13), + "butterfly bush" : ( 98, 78, 154), + "buttermilk" : (255, 241, 181), + "buttery white" : (255, 252, 234), + "cab sav" : ( 77, 10, 24), + "cabaret" : (217, 73, 114), + "cabbage pont" : ( 63, 76, 58), + "cactus" : ( 88, 113, 86), + "cadet blue" : (169, 178, 195), + "cadillac" : (176, 76, 106), + "cafe royale" : (111, 68, 12), + "calico" : (224, 192, 149), + "california" : (254, 157, 4), + "calypso" : ( 49, 114, 141), + "camarone" : ( 0, 88, 26), + "camelot" : (137, 52, 86), + "cameo" : (217, 185, 155), + "camouflage" : ( 60, 57, 16), + "camouflage green" : (120, 134, 107), + "can can" : (213, 145, 164), + "canary" : (243, 251, 98), + "candlelight" : (252, 217, 23), + "candy corn" : (251, 236, 93), + "cannon black" : ( 37, 23, 6), + "cannon pink" : (137, 67, 103), + "cape cod" : ( 60, 68, 67), + "cape honey" : (254, 229, 172), + "cape palliser" : (162, 102, 69), + "caper" : (220, 237, 180), + "caramel" : (255, 221, 175), + "cararra" : (238, 238, 232), + "cardin green" : ( 1, 54, 28), + "cardinal" : (196, 30, 58), + "cardinal pink" : (140, 5, 94), + "careys pink" : (210, 158, 170), + "caribbean green" : ( 0, 204, 153), + "carissma" : (234, 136, 168), + "carla" : (243, 255, 216), + "carmine" : (150, 0, 24), + "carnaby tan" : ( 92, 46, 1), + "carnation" : (249, 90, 97), + "carnation pink" : (255, 166, 201), + "carousel pink" : (249, 224, 237), + "carrot orange" : (237, 145, 33), + "casablanca" : (248, 184, 83), + "casal" : ( 47, 97, 104), + "cascade" : (139, 169, 165), + "cashmere" : (230, 190, 165), + "casper" : (173, 190, 209), + "castro" : ( 82, 0, 31), + "catalina blue" : ( 6, 42, 120), + "catskill white" : (238, 246, 247), + "cavern pink" : (227, 190, 190), + "cedar" : ( 62, 28, 20), + "cedar wood finish" : (113, 26, 0), + "celadon" : (172, 225, 175), + "celery" : (184, 194, 93), + "celeste" : (209, 210, 202), + "cello" : ( 30, 56, 91), + "celtic" : ( 22, 50, 34), + "cement" : (141, 118, 98), + "ceramic" : (252, 255, 249), + "cerise" : (218, 50, 135), + "cerise red" : (222, 49, 99), + "cerulean" : ( 2, 164, 211), + "cerulean blue" : ( 42, 82, 190), + "chablis" : (255, 244, 243), + "chalet green" : ( 81, 110, 61), + "chalky" : (238, 215, 148), + "chambray" : ( 53, 78, 140), + "chamois" : (237, 220, 177), + "champagne" : (250, 236, 204), + "chantilly" : (248, 195, 223), + "charade" : ( 41, 41, 55), + "chardon" : (255, 243, 241), + "chardonnay" : (255, 205, 140), + "charlotte" : (186, 238, 249), + "charm" : (212, 116, 148), + "chartreuse" : (127, 255, 0), + "chartreuse yellow" : (223, 255, 0), + "chateau green" : ( 64, 168, 96), + "chatelle" : (189, 179, 199), + "chathams blue" : ( 23, 85, 121), + "chelsea cucumber" : (131, 170, 93), + "chelsea gem" : (158, 83, 2), + "chenin" : (223, 205, 111), + "cherokee" : (252, 218, 152), + "cherry pie" : ( 42, 3, 89), + "cherrywood" : (101, 26, 20), + "cherub" : (248, 217, 233), + "chestnut" : (185, 78, 72), + "chestnut rose" : (205, 92, 92), + "chetwode blue" : (133, 129, 217), + "chicago" : ( 93, 92, 88), + "chiffon" : (241, 255, 200), + "chilean fire" : (247, 119, 3), + "chilean heath" : (255, 253, 230), + "china ivory" : (252, 255, 231), + "chino" : (206, 199, 167), + "chinook" : (168, 227, 189), + "chocolate" : ( 55, 2, 2), + "christalle" : ( 51, 3, 107), + "christi" : (103, 167, 18), + "christine" : (231, 115, 10), + "chrome white" : (232, 241, 212), + "cinder" : ( 14, 14, 24), + "cinderella" : (253, 225, 220), + "cinnabar" : (227, 66, 52), + "cinnamon" : (123, 63, 0), + "cioccolato" : ( 85, 40, 12), + "citrine white" : (250, 247, 214), + "citron" : (158, 169, 31), + "citrus" : (161, 197, 10), + "clairvoyant" : ( 72, 6, 86), + "clam shell" : (212, 182, 175), + "claret" : (127, 23, 52), + "classic rose" : (251, 204, 231), + "clay ash" : (189, 200, 179), + "clay creek" : (138, 131, 96), + "clear day" : (233, 255, 253), + "clementine" : (233, 110, 0), + "clinker" : ( 55, 29, 9), + "cloud" : (199, 196, 191), + "cloud burst" : ( 32, 46, 84), + "cloudy" : (172, 165, 159), + "clover" : ( 56, 73, 16), + "cobalt" : ( 0, 71, 171), + "cocoa bean" : ( 72, 28, 28), + "cocoa brown" : ( 48, 31, 30), + "coconut cream" : (248, 247, 220), + "cod gray" : ( 11, 11, 11), + "coffee" : (112, 101, 85), + "coffee bean" : ( 42, 20, 14), + "cognac" : (159, 56, 29), + "cola" : ( 63, 37, 0), + "cold purple" : (171, 160, 217), + "cold turkey" : (206, 186, 186), + "colonial white" : (255, 237, 188), + "comet" : ( 92, 93, 117), + "como" : ( 81, 124, 102), + "conch" : (201, 217, 210), + "concord" : (124, 123, 122), + "concrete" : (242, 242, 242), + "confetti" : (233, 215, 90), + "congo brown" : ( 89, 55, 55), + "congress blue" : ( 2, 71, 142), + "conifer" : (172, 221, 77), + "contessa" : (198, 114, 107), + "copper" : (184, 115, 51), + "copper canyon" : (126, 58, 21), + "copper rose" : (153, 102, 102), + "copper rust" : (148, 71, 71), + "copperfield" : (218, 138, 103), + "coral" : (255, 127, 80), + "coral red" : (255, 64, 64), + "coral reef" : (199, 188, 162), + "coral tree" : (168, 107, 107), + "corduroy" : ( 96, 110, 104), + "coriander" : (196, 208, 176), + "cork" : ( 64, 41, 29), + "corn" : (231, 191, 5), + "corn field" : (248, 250, 205), + "corn harvest" : (139, 107, 11), + "cornflower" : (147, 204, 234), + "cornflower blue" : (100, 149, 237), + "cornflower lilac" : (255, 176, 172), + "corvette" : (250, 211, 162), + "cosmic" : (118, 57, 93), + "cosmos" : (255, 216, 217), + "costa del sol" : ( 97, 93, 48), + "cotton candy" : (255, 183, 213), + "cotton seed" : (194, 189, 182), + "county green" : ( 1, 55, 26), + "cowboy" : ( 77, 40, 45), + "crail" : (185, 81, 64), + "cranberry" : (219, 80, 121), + "crater brown" : ( 70, 36, 37), + "cream" : (255, 253, 208), + "cream brulee" : (255, 229, 160), + "cream can" : (245, 200, 92), + "creole" : ( 30, 15, 4), + "crete" : (115, 120, 41), + "crimson" : (220, 20, 60), + "crocodile" : (115, 109, 88), + "crown of thorns" : (119, 31, 31), + "crowshead" : ( 28, 18, 8), + "cruise" : (181, 236, 223), + "crusoe" : ( 0, 72, 22), + "crusta" : (253, 123, 51), + "cumin" : (146, 67, 33), + "cumulus" : (253, 255, 213), + "cupid" : (251, 190, 218), + "curious blue" : ( 37, 150, 209), + "cutty sark" : ( 80, 118, 114), + "cyan / aqua" : ( 0, 255, 255), + "cyprus" : ( 0, 62, 64), + "daintree" : ( 1, 39, 49), + "dairy cream" : (249, 228, 188), + "daisy bush" : ( 79, 35, 152), + "dallas" : (110, 75, 38), + "dandelion" : (254, 216, 93), + "danube" : ( 96, 147, 209), + "dark blue" : ( 0, 0, 200), + "dark burgundy" : (119, 15, 5), + "dark ebony" : ( 60, 32, 5), + "dark fern" : ( 10, 72, 13), + "dark tan" : (102, 16, 16), + "dawn" : (166, 162, 154), + "dawn pink" : (243, 233, 229), + "de york" : (122, 196, 136), + "deco" : (210, 218, 151), + "deep blue" : ( 34, 8, 120), + "deep blush" : (228, 118, 152), + "deep bronze" : ( 74, 48, 4), + "deep cerulean" : ( 0, 123, 167), + "deep cove" : ( 5, 16, 64), + "deep fir" : ( 0, 41, 0), + "deep forest green" : ( 24, 45, 9), + "deep koamaru" : ( 27, 18, 123), + "deep oak" : ( 65, 32, 16), + "deep sapphire" : ( 8, 37, 103), + "deep sea" : ( 1, 130, 107), + "deep sea green" : ( 9, 88, 89), + "deep teal" : ( 0, 53, 50), + "del rio" : (176, 154, 149), + "dell" : ( 57, 100, 19), + "delta" : (164, 164, 157), + "deluge" : (117, 99, 168), + "denim" : ( 21, 96, 189), + "derby" : (255, 238, 216), + "desert" : (174, 96, 32), + "desert sand" : (237, 201, 175), + "desert storm" : (248, 248, 247), + "dew" : (234, 255, 254), + "di serria" : (219, 153, 94), + "diesel" : ( 19, 0, 0), + "dingley" : ( 93, 119, 71), + "disco" : (135, 21, 80), + "dixie" : (226, 148, 24), + "dodger blue" : ( 30, 144, 255), + "dolly" : (249, 255, 139), + "dolphin" : (100, 96, 119), + "domino" : (142, 119, 94), + "don juan" : ( 93, 76, 81), + "donkey brown" : (166, 146, 121), + "dorado" : (107, 87, 85), + "double colonial white" : (238, 227, 173), + "double pearl lusta" : (252, 244, 208), + "double spanish white" : (230, 215, 185), + "dove gray" : (109, 108, 108), + "downriver" : ( 9, 34, 86), + "downy" : (111, 208, 197), + "driftwood" : (175, 135, 81), + "drover" : (253, 247, 173), + "dull lavender" : (168, 153, 230), + "dune" : ( 56, 53, 51), + "dust storm" : (229, 204, 201), + "dusty gray" : (168, 152, 155), + "eagle" : (182, 186, 164), + "earls green" : (201, 185, 59), + "early dawn" : (255, 249, 230), + "east bay" : ( 65, 76, 125), + "east side" : (172, 145, 206), + "eastern blue" : ( 30, 154, 176), + "ebb" : (233, 227, 227), + "ebony" : ( 12, 11, 29), + "ebony clay" : ( 38, 40, 59), + "eclipse" : ( 49, 28, 23), + "ecru white" : (245, 243, 229), + "ecstasy" : (250, 120, 20), + "eden" : ( 16, 88, 82), + "edgewater" : (200, 227, 215), + "edward" : (162, 174, 171), + "egg sour" : (255, 244, 221), + "egg white" : (255, 239, 193), + "eggplant" : ( 97, 64, 81), + "el paso" : ( 30, 23, 8), + "el salva" : (143, 62, 51), + "electric lime" : (204, 255, 0), + "electric violet" : (139, 0, 255), + "elephant" : ( 18, 52, 71), + "elf green" : ( 8, 131, 112), + "elm" : ( 28, 124, 125), + "emerald" : ( 80, 200, 120), + "eminence" : (108, 48, 130), + "emperor" : ( 81, 70, 73), + "empress" : (129, 115, 119), + "endeavour" : ( 0, 86, 167), + "energy yellow" : (248, 221, 92), + "english holly" : ( 2, 45, 21), + "english walnut" : ( 62, 43, 35), + "envy" : (139, 166, 144), + "equator" : (225, 188, 100), + "espresso" : ( 97, 39, 24), + "eternity" : ( 33, 26, 14), + "eucalyptus" : ( 39, 138, 91), + "eunry" : (207, 163, 157), + "evening sea" : ( 2, 78, 70), + "everglade" : ( 28, 64, 46), + "faded jade" : ( 66, 121, 119), + "fair pink" : (255, 239, 236), + "falcon" : (127, 98, 109), + "fall green" : (236, 235, 189), + "falu red" : (128, 24, 24), + "fantasy" : (250, 243, 240), + "fedora" : (121, 106, 120), + "feijoa" : (159, 221, 140), + "fern" : ( 99, 183, 108), + "fern frond" : (101, 114, 32), + "fern green" : ( 79, 121, 66), + "ferra" : (112, 79, 80), + "festival" : (251, 233, 108), + "feta" : (240, 252, 234), + "fiery orange" : (179, 82, 19), + "finch" : ( 98, 102, 73), + "finlandia" : ( 85, 109, 86), + "finn" : (105, 45, 84), + "fiord" : ( 64, 81, 105), + "fire" : (170, 66, 3), + "fire bush" : (232, 153, 40), + "firefly" : ( 14, 42, 48), + "flame pea" : (218, 91, 56), + "flamenco" : (255, 125, 7), + "flamingo" : (242, 85, 42), + "flax" : (238, 220, 130), + "flax smoke" : (123, 130, 101), + "flesh" : (255, 203, 164), + "flint" : (111, 106, 97), + "flirt" : (162, 0, 109), + "flush mahogany" : (202, 52, 53), + "flush orange" : (255, 127, 0), + "foam" : (216, 252, 250), + "fog" : (215, 208, 255), + "foggy gray" : (203, 202, 182), + "forest green" : ( 34, 139, 34), + "forget me not" : (255, 241, 238), + "fountain blue" : ( 86, 180, 190), + "frangipani" : (255, 222, 179), + "french gray" : (189, 189, 198), + "french lilac" : (236, 199, 238), + "french pass" : (189, 237, 253), + "french rose" : (246, 74, 138), + "fresh eggplant" : (153, 0, 102), + "friar gray" : (128, 126, 121), + "fringy flower" : (177, 226, 193), + "froly" : (245, 117, 132), + "frost" : (237, 245, 221), + "frosted mint" : (219, 255, 248), + "frostee" : (228, 246, 231), + "fruit salad" : ( 79, 157, 93), + "fuchsia blue" : (122, 88, 193), + "fuchsia pink" : (193, 84, 193), + "fuego" : (190, 222, 13), + "fuel yellow" : (236, 169, 39), + "fun blue" : ( 25, 89, 168), + "fun green" : ( 1, 109, 57), + "fuscous gray" : ( 84, 83, 77), + "fuzzy wuzzy brown" : (196, 86, 85), + "gable green" : ( 22, 53, 49), + "gallery" : (239, 239, 239), + "galliano" : (220, 178, 12), + "gamboge" : (228, 155, 15), + "geebung" : (209, 143, 27), + "genoa" : ( 21, 115, 107), + "geraldine" : (251, 137, 137), + "geyser" : (212, 223, 226), + "ghost" : (199, 201, 213), + "gigas" : ( 82, 60, 148), + "gimblet" : (184, 181, 106), + "gin" : (232, 242, 235), + "gin fizz" : (255, 249, 226), + "givry" : (248, 228, 191), + "glacier" : (128, 179, 196), + "glade green" : ( 97, 132, 95), + "go ben" : (114, 109, 78), + "goblin" : ( 61, 125, 82), + "gold" : (255, 215, 0), + "gold drop" : (241, 130, 0), + "gold sand" : (230, 190, 138), + "gold tips" : (222, 186, 19), + "golden bell" : (226, 137, 19), + "golden dream" : (240, 213, 45), + "golden fizz" : (245, 251, 61), + "golden glow" : (253, 226, 149), + "golden grass" : (218, 165, 32), + "golden sand" : (240, 219, 125), + "golden tainoi" : (255, 204, 92), + "goldenrod" : (252, 214, 103), + "gondola" : ( 38, 20, 20), + "gordons green" : ( 11, 17, 7), + "gorse" : (255, 241, 79), + "gossamer" : ( 6, 155, 129), + "gossip" : (210, 248, 176), + "gothic" : (109, 146, 161), + "governor bay" : ( 47, 60, 179), + "grain brown" : (228, 213, 183), + "grandis" : (255, 211, 140), + "granite green" : (141, 137, 116), + "granny apple" : (213, 246, 227), + "granny smith" : (132, 160, 160), + "granny smith apple" : (157, 224, 147), + "grape" : ( 56, 26, 81), + "graphite" : ( 37, 22, 7), + "gravel" : ( 74, 68, 75), + "gray" : (128, 128, 128), + "gray asparagus" : ( 70, 89, 69), + "gray chateau" : (162, 170, 179), + "gray nickel" : (195, 195, 189), + "gray nurse" : (231, 236, 230), + "gray olive" : (169, 164, 145), + "gray suit" : (193, 190, 205), + "green" : ( 0, 255, 0), + "green haze" : ( 1, 163, 104), + "green house" : ( 36, 80, 15), + "green kelp" : ( 37, 49, 28), + "green leaf" : ( 67, 106, 13), + "green mist" : (203, 211, 176), + "green pea" : ( 29, 97, 66), + "green smoke" : (164, 175, 110), + "green spring" : (184, 193, 177), + "green vogue" : ( 3, 43, 82), + "green waterloo" : ( 16, 20, 5), + "green white" : (232, 235, 224), + "green yellow" : (173, 255, 47), + "grenadier" : (213, 70, 0), + "guardsman red" : (186, 1, 1), + "gulf blue" : ( 5, 22, 87), + "gulf stream" : (128, 179, 174), + "gull gray" : (157, 172, 183), + "gum leaf" : (182, 211, 191), + "gumbo" : (124, 161, 166), + "gun powder" : ( 65, 66, 87), + "gunsmoke" : (130, 134, 133), + "gurkha" : (154, 149, 119), + "hacienda" : (152, 129, 27), + "hairy heath" : (107, 42, 20), + "haiti" : ( 27, 16, 53), + "half baked" : (133, 196, 204), + "half colonial white" : (253, 246, 211), + "half dutch white" : (254, 247, 222), + "half spanish white" : (254, 244, 219), + "half and half" : (255, 254, 225), + "hampton" : (229, 216, 175), + "harlequin" : ( 63, 255, 0), + "harp" : (230, 242, 234), + "harvest gold" : (224, 185, 116), + "havelock blue" : ( 85, 144, 217), + "hawaiian tan" : (157, 86, 22), + "hawkes blue" : (212, 226, 252), + "heath" : ( 84, 16, 18), + "heather" : (183, 195, 208), + "heathered gray" : (182, 176, 149), + "heavy metal" : ( 43, 50, 40), + "heliotrope" : (223, 115, 255), + "hemlock" : ( 94, 93, 59), + "hemp" : (144, 120, 116), + "hibiscus" : (182, 49, 108), + "highland" : (111, 142, 99), + "hillary" : (172, 165, 134), + "himalaya" : (106, 93, 27), + "hint of green" : (230, 255, 233), + "hint of red" : (251, 249, 249), + "hint of yellow" : (250, 253, 228), + "hippie blue" : ( 88, 154, 175), + "hippie green" : ( 83, 130, 75), + "hippie pink" : (174, 69, 96), + "hit gray" : (161, 173, 181), + "hit pink" : (255, 171, 129), + "hokey pokey" : (200, 165, 40), + "hoki" : (101, 134, 159), + "holly" : ( 1, 29, 19), + "hollywood cerise" : (244, 0, 161), + "honey flower" : ( 79, 28, 112), + "honeysuckle" : (237, 252, 132), + "hopbush" : (208, 109, 161), + "horizon" : ( 90, 135, 160), + "horses neck" : ( 96, 73, 19), + "hot cinnamon" : (210, 105, 30), + "hot pink" : (255, 105, 180), + "hot toddy" : (179, 128, 7), + "humming bird" : (207, 249, 243), + "hunter green" : ( 22, 29, 16), + "hurricane" : (135, 124, 123), + "husk" : (183, 164, 88), + "ice cold" : (177, 244, 231), + "iceberg" : (218, 244, 240), + "illusion" : (246, 164, 201), + "inch worm" : (176, 227, 19), + "indian khaki" : (195, 176, 145), + "indian tan" : ( 77, 30, 1), + "indigo" : ( 79, 105, 198), + "indochine" : (194, 107, 3), + "international klein blue" : ( 0, 47, 167), + "international orange" : (255, 79, 0), + "irish coffee" : ( 95, 61, 38), + "iroko" : ( 67, 49, 32), + "iron" : (212, 215, 217), + "ironside gray" : (103, 102, 98), + "ironstone" : (134, 72, 60), + "island spice" : (255, 252, 238), + "ivory" : (255, 255, 240), + "jacaranda" : ( 46, 3, 41), + "jacarta" : ( 58, 42, 106), + "jacko bean" : ( 46, 25, 5), + "jacksons purple" : ( 32, 32, 141), + "jade" : ( 0, 168, 107), + "jaffa" : (239, 134, 63), + "jagged ice" : (194, 232, 229), + "jagger" : ( 53, 14, 87), + "jaguar" : ( 8, 1, 16), + "jambalaya" : ( 91, 48, 19), + "janna" : (244, 235, 211), + "japanese laurel" : ( 10, 105, 6), + "japanese maple" : (120, 1, 9), + "japonica" : (216, 124, 99), + "java" : ( 31, 194, 194), + "jazzberry jam" : (165, 11, 94), + "jelly bean" : ( 41, 123, 154), + "jet stream" : (181, 210, 206), + "jewel" : ( 18, 107, 64), + "jon" : ( 59, 31, 31), + "jonquil" : (238, 255, 154), + "jordy blue" : (138, 185, 241), + "judge gray" : ( 84, 67, 51), + "jumbo" : (124, 123, 130), + "jungle green" : ( 41, 171, 135), + "jungle mist" : (180, 207, 211), + "juniper" : (109, 146, 146), + "just right" : (236, 205, 185), + "kabul" : ( 94, 72, 62), + "kaitoke green" : ( 0, 70, 32), + "kangaroo" : (198, 200, 189), + "karaka" : ( 30, 22, 9), + "karry" : (255, 234, 212), + "kashmir blue" : ( 80, 112, 150), + "kelp" : ( 69, 73, 54), + "kenyan copper" : (124, 28, 5), + "keppel" : ( 58, 176, 158), + "key lime pie" : (191, 201, 33), + "khaki" : (240, 230, 140), + "kidnapper" : (225, 234, 212), + "kilamanjaro" : ( 36, 12, 2), + "killarney" : ( 58, 106, 71), + "kimberly" : (115, 108, 159), + "kingfisher daisy" : ( 62, 4, 128), + "kobi" : (231, 159, 196), + "kokoda" : (110, 109, 87), + "korma" : (143, 75, 14), + "koromiko" : (255, 189, 95), + "kournikova" : (255, 231, 114), + "kumera" : (136, 98, 33), + "la palma" : ( 54, 135, 22), + "la rioja" : (179, 193, 16), + "las palmas" : (198, 230, 16), + "laser" : (200, 181, 104), + "laser lemon" : (255, 255, 102), + "laurel" : (116, 147, 120), + "lavender" : (181, 126, 220), + "lavender gray" : (189, 187, 215), + "lavender magenta" : (238, 130, 238), + "lavender pink" : (251, 174, 210), + "lavender purple" : (150, 123, 182), + "lavender rose" : (251, 160, 227), + "lavender blush" : (255, 240, 245), + "leather" : (150, 112, 89), + "lemon" : (253, 233, 16), + "lemon chiffon" : (255, 250, 205), + "lemon ginger" : (172, 158, 34), + "lemon grass" : (155, 158, 143), + "light apricot" : (253, 213, 177), + "light orchid" : (226, 156, 210), + "light wisteria" : (201, 160, 220), + "lightning yellow" : (252, 192, 30), + "lilac" : (200, 162, 200), + "lilac bush" : (152, 116, 211), + "lily" : (200, 170, 191), + "lily white" : (231, 248, 255), + "lima" : (118, 189, 23), + "lime" : (191, 255, 0), + "limeade" : (111, 157, 2), + "limed ash" : (116, 125, 99), + "limed oak" : (172, 138, 86), + "limed spruce" : ( 57, 72, 81), + "linen" : (250, 240, 230), + "link water" : (217, 228, 245), + "lipstick" : (171, 5, 99), + "lisbon brown" : ( 66, 57, 33), + "livid brown" : ( 77, 40, 46), + "loafer" : (238, 244, 222), + "loblolly" : (189, 201, 206), + "lochinvar" : ( 44, 140, 132), + "lochmara" : ( 0, 126, 199), + "locust" : (168, 175, 142), + "log cabin" : ( 36, 42, 29), + "logan" : (170, 169, 205), + "lola" : (223, 207, 219), + "london hue" : (190, 166, 195), + "lonestar" : (109, 1, 1), + "lotus" : (134, 60, 60), + "loulou" : ( 70, 11, 65), + "lucky" : (175, 159, 28), + "lucky point" : ( 26, 26, 104), + "lunar green" : ( 60, 73, 58), + "luxor gold" : (167, 136, 44), + "lynch" : (105, 126, 154), + "mabel" : (217, 247, 255), + "macaroni and cheese" : (255, 185, 123), + "madang" : (183, 240, 190), + "madison" : ( 9, 37, 93), + "madras" : ( 63, 48, 2), + "magenta / fuchsia" : (255, 0, 255), + "magic mint" : (170, 240, 209), + "magnolia" : (248, 244, 255), + "mahogany" : ( 78, 6, 6), + "mai tai" : (176, 102, 8), + "maize" : (245, 213, 160), + "makara" : (137, 125, 109), + "mako" : ( 68, 73, 84), + "malachite" : ( 11, 218, 81), + "malibu" : (125, 200, 247), + "mallard" : ( 35, 52, 24), + "malta" : (189, 178, 161), + "mamba" : (142, 129, 144), + "manatee" : (141, 144, 161), + "mandalay" : (173, 120, 27), + "mandy" : (226, 84, 101), + "mandys pink" : (242, 195, 178), + "mango tango" : (231, 114, 0), + "manhattan" : (245, 201, 153), + "mantis" : (116, 195, 101), + "mantle" : (139, 156, 144), + "manz" : (238, 239, 120), + "mardi gras" : ( 53, 0, 54), + "marigold" : (185, 141, 40), + "marigold yellow" : (251, 232, 112), + "mariner" : ( 40, 106, 205), + "maroon" : (128, 0, 0), + "maroon flush" : (195, 33, 72), + "maroon oak" : ( 82, 12, 23), + "marshland" : ( 11, 15, 8), + "martini" : (175, 160, 158), + "martinique" : ( 54, 48, 80), + "marzipan" : (248, 219, 157), + "masala" : ( 64, 59, 56), + "matisse" : ( 27, 101, 157), + "matrix" : (176, 93, 84), + "matterhorn" : ( 78, 59, 65), + "mauve" : (224, 176, 255), + "mauvelous" : (240, 145, 169), + "maverick" : (216, 194, 213), + "medium carmine" : (175, 64, 53), + "medium purple" : (147, 112, 219), + "medium red violet" : (187, 51, 133), + "melanie" : (228, 194, 213), + "melanzane" : ( 48, 5, 41), + "melon" : (254, 186, 173), + "melrose" : (199, 193, 255), + "mercury" : (229, 229, 229), + "merino" : (246, 240, 230), + "merlin" : ( 65, 60, 55), + "merlot" : (131, 25, 35), + "metallic bronze" : ( 73, 55, 27), + "metallic copper" : (113, 41, 29), + "meteor" : (208, 125, 18), + "meteorite" : ( 60, 31, 118), + "mexican red" : (167, 37, 37), + "mid gray" : ( 95, 95, 110), + "midnight" : ( 1, 22, 53), + "midnight blue" : ( 0, 51, 102), + "midnight moss" : ( 4, 16, 4), + "mikado" : ( 45, 37, 16), + "milan" : (250, 255, 164), + "milano red" : (184, 17, 4), + "milk punch" : (255, 246, 212), + "millbrook" : ( 89, 68, 51), + "mimosa" : (248, 253, 211), + "mindaro" : (227, 249, 136), + "mine shaft" : ( 50, 50, 50), + "mineral green" : ( 63, 93, 83), + "ming" : ( 54, 116, 125), + "minsk" : ( 63, 48, 127), + "mint green" : (152, 255, 152), + "mint julep" : (241, 238, 193), + "mint tulip" : (196, 244, 235), + "mirage" : ( 22, 25, 40), + "mischka" : (209, 210, 221), + "mist gray" : (196, 196, 188), + "mobster" : (127, 117, 137), + "moccaccino" : (110, 29, 20), + "mocha" : (120, 45, 25), + "mojo" : (192, 71, 55), + "mona lisa" : (255, 161, 148), + "monarch" : (139, 7, 35), + "mondo" : ( 74, 60, 48), + "mongoose" : (181, 162, 127), + "monsoon" : (138, 131, 137), + "monte carlo" : (131, 208, 198), + "monza" : (199, 3, 30), + "moody blue" : (127, 118, 211), + "moon glow" : (252, 254, 218), + "moon mist" : (220, 221, 204), + "moon raker" : (214, 206, 246), + "morning glory" : (158, 222, 224), + "morocco brown" : ( 68, 29, 0), + "mortar" : ( 80, 67, 81), + "mosque" : ( 3, 106, 110), + "moss green" : (173, 223, 173), + "mountain meadow" : ( 26, 179, 133), + "mountain mist" : (149, 147, 150), + "mountbatten pink" : (153, 122, 141), + "muddy waters" : (183, 142, 92), + "muesli" : (170, 139, 91), + "mulberry" : (197, 75, 140), + "mulberry wood" : ( 92, 5, 54), + "mule fawn" : (140, 71, 47), + "mulled wine" : ( 78, 69, 98), + "mustard" : (255, 219, 88), + "my pink" : (214, 145, 136), + "my sin" : (255, 179, 31), + "mystic" : (226, 235, 237), + "nandor" : ( 75, 93, 82), + "napa" : (172, 164, 148), + "narvik" : (237, 249, 241), + "natural gray" : (139, 134, 128), + "navajo white" : (255, 222, 173), + "navy blue" : ( 0, 0, 128), + "nebula" : (203, 219, 214), + "negroni" : (255, 226, 197), + "neon carrot" : (255, 153, 51), + "nepal" : (142, 171, 193), + "neptune" : (124, 183, 187), + "nero" : ( 20, 6, 0), + "nevada" : (100, 110, 117), + "new orleans" : (243, 214, 157), + "new york pink" : (215, 131, 127), + "niagara" : ( 6, 161, 137), + "night rider" : ( 31, 18, 15), + "night shadz" : (170, 55, 90), + "nile blue" : ( 25, 55, 81), + "nobel" : (183, 177, 177), + "nomad" : (186, 177, 162), + "norway" : (168, 189, 159), + "nugget" : (197, 153, 34), + "nutmeg" : (129, 66, 44), + "nutmeg wood finish" : (104, 54, 0), + "oasis" : (254, 239, 206), + "observatory" : ( 2, 134, 111), + "ocean green" : ( 65, 170, 120), + "ochre" : (204, 119, 34), + "off green" : (230, 248, 243), + "off yellow" : (254, 249, 227), + "oil" : ( 40, 30, 21), + "old brick" : (144, 30, 30), + "old copper" : (114, 74, 47), + "old gold" : (207, 181, 59), + "old lace" : (253, 245, 230), + "old lavender" : (121, 104, 120), + "old rose" : (192, 128, 129), + "olive" : (128, 128, 0), + "olive drab" : (107, 142, 35), + "olive green" : (181, 179, 92), + "olive haze" : (139, 132, 112), + "olivetone" : (113, 110, 16), + "olivine" : (154, 185, 115), + "onahau" : (205, 244, 255), + "onion" : ( 47, 39, 14), + "opal" : (169, 198, 194), + "opium" : (142, 111, 112), + "oracle" : ( 55, 116, 117), + "orange" : (255, 104, 31), + "orange peel" : (255, 160, 0), + "orange roughy" : (196, 87, 25), + "orange white" : (254, 252, 237), + "orchid" : (218, 112, 214), + "orchid white" : (255, 253, 243), + "oregon" : (155, 71, 3), + "orient" : ( 1, 94, 133), + "oriental pink" : (198, 145, 145), + "orinoco" : (243, 251, 212), + "oslo gray" : (135, 141, 145), + "ottoman" : (233, 248, 237), + "outer space" : ( 45, 56, 58), + "outrageous orange" : (255, 96, 55), + "oxford blue" : ( 56, 69, 85), + "oxley" : (119, 158, 134), + "oyster bay" : (218, 250, 255), + "oyster pink" : (233, 206, 205), + "paarl" : (166, 85, 41), + "pablo" : (119, 111, 97), + "pacific blue" : ( 0, 157, 196), + "pacifika" : (119, 129, 32), + "paco" : ( 65, 31, 16), + "padua" : (173, 230, 196), + "pale canary" : (255, 255, 153), + "pale leaf" : (192, 211, 185), + "pale oyster" : (152, 141, 119), + "pale prim" : (253, 254, 184), + "pale rose" : (255, 225, 242), + "pale sky" : (110, 119, 131), + "pale slate" : (195, 191, 193), + "palm green" : ( 9, 35, 15), + "palm leaf" : ( 25, 51, 14), + "pampas" : (244, 242, 238), + "panache" : (234, 246, 238), + "pancho" : (237, 205, 171), + "papaya whip" : (255, 239, 213), + "paprika" : (141, 2, 38), + "paradiso" : ( 49, 125, 130), + "parchment" : (241, 233, 210), + "paris daisy" : (255, 244, 110), + "paris m" : ( 38, 5, 106), + "paris white" : (202, 220, 212), + "parsley" : ( 19, 79, 25), + "pastel green" : (119, 221, 119), + "pastel pink" : (255, 209, 220), + "patina" : ( 99, 154, 143), + "pattens blue" : (222, 245, 255), + "paua" : ( 38, 3, 104), + "pavlova" : (215, 196, 152), + "peach" : (255, 229, 180), + "peach cream" : (255, 240, 219), + "peach orange" : (255, 204, 153), + "peach schnapps" : (255, 220, 214), + "peach yellow" : (250, 223, 173), + "peanut" : (120, 47, 22), + "pear" : (209, 226, 49), + "pearl bush" : (232, 224, 213), + "pearl lusta" : (252, 244, 220), + "peat" : (113, 107, 86), + "pelorous" : ( 62, 171, 191), + "peppermint" : (227, 245, 225), + "perano" : (169, 190, 242), + "perfume" : (208, 190, 248), + "periglacial blue" : (225, 230, 214), + "periwinkle" : (204, 204, 255), + "periwinkle gray" : (195, 205, 230), + "persian blue" : ( 28, 57, 187), + "persian green" : ( 0, 166, 147), + "persian indigo" : ( 50, 18, 122), + "persian pink" : (247, 127, 190), + "persian plum" : (112, 28, 28), + "persian red" : (204, 51, 51), + "persian rose" : (254, 40, 162), + "persimmon" : (255, 107, 83), + "peru tan" : (127, 58, 2), + "pesto" : (124, 118, 49), + "petite orchid" : (219, 150, 144), + "pewter" : (150, 168, 161), + "pharlap" : (163, 128, 123), + "picasso" : (255, 243, 157), + "pickled bean" : (110, 72, 38), + "pickled bluewood" : ( 49, 68, 89), + "picton blue" : ( 69, 177, 232), + "pig pink" : (253, 215, 228), + "pigeon post" : (175, 189, 217), + "pigment indigo" : ( 75, 0, 130), + "pine cone" : (109, 94, 84), + "pine glade" : (199, 205, 144), + "pine green" : ( 1, 121, 111), + "pine tree" : ( 23, 31, 4), + "pink" : (255, 192, 203), + "pink flamingo" : (255, 102, 255), + "pink flare" : (225, 192, 200), + "pink lace" : (255, 221, 244), + "pink lady" : (255, 241, 216), + "pink salmon" : (255, 145, 164), + "pink swan" : (190, 181, 183), + "piper" : (201, 99, 35), + "pipi" : (254, 244, 204), + "pippin" : (255, 225, 223), + "pirate gold" : (186, 127, 3), + "pistachio" : (157, 194, 9), + "pixie green" : (192, 216, 182), + "pizazz" : (255, 144, 0), + "pizza" : (201, 148, 21), + "plantation" : ( 39, 80, 75), + "plum" : (132, 49, 121), + "pohutukawa" : (143, 2, 28), + "polar" : (229, 249, 246), + "polo blue" : (141, 168, 204), + "pomegranate" : (243, 71, 35), + "pompadour" : (102, 0, 69), + "porcelain" : (239, 242, 243), + "porsche" : (234, 174, 105), + "port gore" : ( 37, 31, 79), + "portafino" : (255, 255, 180), + "portage" : (139, 159, 238), + "portica" : (249, 230, 99), + "pot pourri" : (245, 231, 226), + "potters clay" : (140, 87, 56), + "powder ash" : (188, 201, 194), + "powder blue" : (176, 224, 230), + "prairie sand" : (154, 56, 32), + "prelude" : (208, 192, 229), + "prim" : (240, 226, 236), + "primrose" : (237, 234, 153), + "provincial pink" : (254, 245, 241), + "prussian blue" : ( 0, 49, 83), + "puce" : (204, 136, 153), + "pueblo" : (125, 44, 20), + "puerto rico" : ( 63, 193, 170), + "pumice" : (194, 202, 196), + "pumpkin" : (255, 117, 24), + "pumpkin skin" : (177, 97, 11), + "punch" : (220, 67, 51), + "punga" : ( 77, 61, 20), + "purple" : (102, 0, 153), + "purple heart" : (101, 45, 193), + "purple mountain's majesty" : (150, 120, 182), + "purple pizzazz" : (255, 0, 204), + "putty" : (231, 205, 140), + "quarter pearl lusta" : (255, 253, 244), + "quarter spanish white" : (247, 242, 225), + "quicksand" : (189, 151, 142), + "quill gray" : (214, 214, 209), + "quincy" : ( 98, 63, 45), + "racing green" : ( 12, 25, 17), + "radical red" : (255, 53, 94), + "raffia" : (234, 218, 184), + "rainee" : (185, 200, 172), + "rajah" : (247, 182, 104), + "rangitoto" : ( 46, 50, 34), + "rangoon green" : ( 28, 30, 19), + "raven" : (114, 123, 137), + "raw sienna" : (210, 125, 70), + "raw umber" : (115, 74, 18), + "razzle dazzle rose" : (255, 51, 204), + "razzmatazz" : (227, 11, 92), + "rebel" : ( 60, 18, 6), + "red" : (255, 0, 0), + "red beech" : (123, 56, 1), + "red berry" : (142, 0, 0), + "red damask" : (218, 106, 65), + "red devil" : (134, 1, 17), + "red orange" : (255, 63, 52), + "red oxide" : (110, 9, 2), + "red ribbon" : (237, 10, 63), + "red robin" : (128, 52, 31), + "red stage" : (208, 95, 4), + "red violet" : (199, 21, 133), + "redwood" : ( 93, 30, 15), + "reef" : (201, 255, 162), + "reef gold" : (159, 130, 28), + "regal blue" : ( 1, 63, 106), + "regent gray" : (134, 148, 159), + "regent st blue" : (170, 214, 230), + "remy" : (254, 235, 243), + "reno sand" : (168, 101, 21), + "resolution blue" : ( 0, 35, 135), + "revolver" : ( 44, 22, 50), + "rhino" : ( 46, 63, 98), + "rice cake" : (255, 254, 240), + "rice flower" : (238, 255, 226), + "rich gold" : (168, 83, 7), + "rio grande" : (187, 208, 9), + "ripe lemon" : (244, 216, 28), + "ripe plum" : ( 65, 0, 86), + "riptide" : (139, 230, 216), + "river bed" : ( 67, 76, 89), + "rob roy" : (234, 198, 116), + "robin's egg blue" : ( 0, 204, 204), + "rock" : ( 77, 56, 51), + "rock blue" : (158, 177, 205), + "rock spray" : (186, 69, 12), + "rodeo dust" : (201, 178, 155), + "rolling stone" : (116, 125, 131), + "roman" : (222, 99, 96), + "roman coffee" : (121, 93, 76), + "romance" : (255, 254, 253), + "romantic" : (255, 210, 183), + "ronchi" : (236, 197, 78), + "roof terracotta" : (166, 47, 32), + "rope" : (142, 77, 30), + "rose" : (255, 0, 127), + "rose bud" : (251, 178, 163), + "rose bud cherry" : (128, 11, 71), + "rose fog" : (231, 188, 180), + "rose white" : (255, 246, 245), + "rose of sharon" : (191, 85, 0), + "rosewood" : (101, 0, 11), + "roti" : (198, 168, 75), + "rouge" : (162, 59, 108), + "royal blue" : ( 65, 105, 225), + "royal heath" : (171, 52, 114), + "royal purple" : (107, 63, 160), + "rum" : (121, 105, 137), + "rum swizzle" : (249, 248, 228), + "russet" : (128, 70, 27), + "russett" : (117, 90, 87), + "rust" : (183, 65, 14), + "rustic red" : ( 72, 4, 4), + "rusty nail" : (134, 86, 10), + "saddle" : ( 76, 48, 36), + "saddle brown" : ( 88, 52, 1), + "saffron" : (244, 196, 48), + "saffron mango" : (249, 191, 88), + "sage" : (158, 165, 135), + "sahara" : (183, 162, 20), + "sahara sand" : (241, 231, 136), + "sail" : (184, 224, 249), + "salem" : ( 9, 127, 75), + "salmon" : (255, 140, 105), + "salomie" : (254, 219, 141), + "salt box" : (104, 94, 110), + "saltpan" : (241, 247, 242), + "sambuca" : ( 58, 32, 16), + "san felix" : ( 11, 98, 7), + "san juan" : ( 48, 75, 106), + "san marino" : ( 69, 108, 172), + "sand dune" : (130, 111, 101), + "sandal" : (170, 141, 111), + "sandrift" : (171, 145, 122), + "sandstone" : (121, 109, 98), + "sandwisp" : (245, 231, 162), + "sandy beach" : (255, 234, 200), + "sandy brown" : (244, 164, 96), + "sangria" : (146, 0, 10), + "sanguine brown" : (141, 61, 56), + "santa fe" : (177, 109, 82), + "santas gray" : (159, 160, 177), + "sapling" : (222, 212, 164), + "sapphire" : ( 47, 81, 158), + "saratoga" : ( 85, 91, 16), + "satin linen" : (230, 228, 212), + "sauvignon" : (255, 245, 243), + "sazerac" : (255, 244, 224), + "scampi" : (103, 95, 166), + "scandal" : (207, 250, 244), + "scarlet" : (255, 36, 0), + "scarlet gum" : ( 67, 21, 96), + "scarlett" : (149, 0, 21), + "scarpa flow" : ( 88, 85, 98), + "schist" : (169, 180, 151), + "school bus yellow" : (255, 216, 0), + "schooner" : (139, 132, 126), + "science blue" : ( 0, 102, 204), + "scooter" : ( 46, 191, 212), + "scorpion" : (105, 95, 98), + "scotch mist" : (255, 251, 220), + "screamin' green" : (102, 255, 102), + "sea buckthorn" : (251, 161, 41), + "sea green" : ( 46, 139, 87), + "sea mist" : (197, 219, 202), + "sea nymph" : (120, 163, 156), + "sea pink" : (237, 152, 158), + "seagull" : (128, 204, 234), + "seance" : (115, 30, 143), + "seashell" : (241, 241, 241), + "seashell peach" : (255, 245, 238), + "seaweed" : ( 27, 47, 17), + "selago" : (240, 238, 253), + "selective yellow" : (255, 186, 0), + "sepia" : (112, 66, 20), + "sepia black" : ( 43, 2, 2), + "sepia skin" : (158, 91, 64), + "serenade" : (255, 244, 232), + "shadow" : (131, 112, 80), + "shadow green" : (154, 194, 184), + "shady lady" : (170, 165, 169), + "shakespeare" : ( 78, 171, 209), + "shalimar" : (251, 255, 186), + "shamrock" : ( 51, 204, 153), + "shark" : ( 37, 39, 44), + "sherpa blue" : ( 0, 73, 80), + "sherwood green" : ( 2, 64, 44), + "shilo" : (232, 185, 179), + "shingle fawn" : (107, 78, 49), + "ship cove" : (120, 139, 186), + "ship gray" : ( 62, 58, 68), + "shiraz" : (178, 9, 49), + "shocking" : (226, 146, 192), + "shocking pink" : (252, 15, 192), + "shuttle gray" : ( 95, 102, 114), + "siam" : (100, 106, 84), + "sidecar" : (243, 231, 187), + "silk" : (189, 177, 168), + "silver" : (192, 192, 192), + "silver chalice" : (172, 172, 172), + "silver rust" : (201, 192, 187), + "silver sand" : (191, 193, 194), + "silver tree" : (102, 181, 143), + "sinbad" : (159, 215, 211), + "siren" : (122, 1, 58), + "sirocco" : (113, 128, 128), + "sisal" : (211, 203, 186), + "skeptic" : (202, 230, 218), + "sky blue" : (118, 215, 234), + "slate gray" : (112, 128, 144), + "smalt" : ( 0, 51, 153), + "smalt blue" : ( 81, 128, 143), + "smoky" : ( 96, 91, 115), + "snow drift" : (247, 250, 247), + "snow flurry" : (228, 255, 209), + "snowy mint" : (214, 255, 219), + "snuff" : (226, 216, 237), + "soapstone" : (255, 251, 249), + "soft amber" : (209, 198, 180), + "soft peach" : (245, 237, 239), + "solid pink" : (137, 56, 67), + "solitaire" : (254, 248, 226), + "solitude" : (234, 246, 255), + "sorbus" : (253, 124, 7), + "sorrell brown" : (206, 185, 143), + "soya bean" : (106, 96, 81), + "spanish green" : (129, 152, 133), + "spectra" : ( 47, 90, 87), + "spice" : (106, 68, 46), + "spicy mix" : (136, 83, 66), + "spicy mustard" : (116, 100, 13), + "spicy pink" : (129, 110, 113), + "spindle" : (182, 209, 234), + "spray" : (121, 222, 236), + "spring green" : ( 0, 255, 127), + "spring leaves" : ( 87, 131, 99), + "spring rain" : (172, 203, 177), + "spring sun" : (246, 255, 220), + "spring wood" : (248, 246, 241), + "sprout" : (193, 215, 176), + "spun pearl" : (170, 171, 183), + "squirrel" : (143, 129, 118), + "st tropaz" : ( 45, 86, 155), + "stack" : (138, 143, 138), + "star dust" : (159, 159, 156), + "stark white" : (229, 215, 189), + "starship" : (236, 242, 69), + "steel blue" : ( 70, 130, 180), + "steel gray" : ( 38, 35, 53), + "stiletto" : (156, 51, 54), + "stonewall" : (146, 133, 115), + "storm dust" : (100, 100, 99), + "storm gray" : (113, 116, 134), + "stratos" : ( 0, 7, 65), + "straw" : (212, 191, 141), + "strikemaster" : (149, 99, 135), + "stromboli" : ( 50, 93, 82), + "studio" : (113, 74, 178), + "submarine" : (186, 199, 201), + "sugar cane" : (249, 255, 246), + "sulu" : (193, 240, 124), + "summer green" : (150, 187, 171), + "sun" : (251, 172, 19), + "sundance" : (201, 179, 91), + "sundown" : (255, 177, 179), + "sunflower" : (228, 212, 34), + "sunglo" : (225, 104, 101), + "sunglow" : (255, 204, 51), + "sunset orange" : (254, 76, 64), + "sunshade" : (255, 158, 44), + "supernova" : (255, 201, 1), + "surf" : (187, 215, 193), + "surf crest" : (207, 229, 210), + "surfie green" : ( 12, 122, 121), + "sushi" : (135, 171, 57), + "suva gray" : (136, 131, 135), + "swamp" : ( 0, 27, 28), + "swamp green" : (172, 183, 142), + "swans down" : (220, 240, 234), + "sweet corn" : (251, 234, 140), + "sweet pink" : (253, 159, 162), + "swirl" : (211, 205, 197), + "swiss coffee" : (221, 214, 213), + "sycamore" : (144, 141, 57), + "tabasco" : (160, 39, 18), + "tacao" : (237, 179, 129), + "tacha" : (214, 197, 98), + "tahiti gold" : (233, 124, 7), + "tahuna sands" : (238, 240, 200), + "tall poppy" : (179, 45, 41), + "tallow" : (168, 165, 137), + "tamarillo" : (153, 22, 19), + "tamarind" : ( 52, 21, 21), + "tan" : (210, 180, 140), + "tan hide" : (250, 157, 90), + "tana" : (217, 220, 193), + "tangaroa" : ( 3, 22, 60), + "tangerine" : (242, 133, 0), + "tango" : (237, 122, 28), + "tapa" : (123, 120, 116), + "tapestry" : (176, 94, 129), + "tara" : (225, 246, 232), + "tarawera" : ( 7, 58, 80), + "tasman" : (207, 220, 207), + "taupe" : ( 72, 60, 50), + "taupe gray" : (179, 175, 149), + "tawny port" : (105, 37, 69), + "te papa green" : ( 30, 67, 60), + "tea" : (193, 186, 176), + "tea green" : (208, 240, 192), + "teak" : (177, 148, 97), + "teal" : ( 0, 128, 128), + "teal blue" : ( 4, 66, 89), + "temptress" : ( 59, 0, 11), + "tenn" : (205, 87, 0), + "tequila" : (255, 230, 199), + "terracotta" : (226, 114, 91), + "texas" : (248, 249, 156), + "texas rose" : (255, 181, 85), + "thatch" : (182, 157, 152), + "thatch green" : ( 64, 61, 25), + "thistle" : (216, 191, 216), + "thistle green" : (204, 202, 168), + "thunder" : ( 51, 41, 47), + "thunderbird" : (192, 43, 24), + "tia maria" : (193, 68, 14), + "tiara" : (195, 209, 209), + "tiber" : ( 6, 53, 55), + "tickle me pink" : (252, 128, 165), + "tidal" : (241, 255, 173), + "tide" : (191, 184, 176), + "timber green" : ( 22, 50, 44), + "timberwolf" : (217, 214, 207), + "titan white" : (240, 238, 255), + "toast" : (154, 110, 97), + "tobacco brown" : (113, 93, 71), + "toledo" : ( 58, 0, 32), + "tolopea" : ( 27, 2, 69), + "tom thumb" : ( 63, 88, 59), + "tonys pink" : (231, 159, 140), + "topaz" : (124, 119, 138), + "torch red" : (253, 14, 53), + "torea bay" : ( 15, 45, 158), + "tory blue" : ( 20, 80, 170), + "tosca" : (141, 63, 63), + "totem pole" : (153, 27, 7), + "tower gray" : (169, 189, 191), + "tradewind" : ( 95, 179, 172), + "tranquil" : (230, 255, 255), + "travertine" : (255, 253, 232), + "tree poppy" : (252, 156, 29), + "treehouse" : ( 59, 40, 32), + "trendy green" : (124, 136, 26), + "trendy pink" : (140, 100, 149), + "trinidad" : (230, 78, 3), + "tropical blue" : (195, 221, 249), + "tropical rain forest" : ( 0, 117, 94), + "trout" : ( 74, 78, 90), + "true v" : (138, 115, 214), + "tuatara" : ( 54, 53, 52), + "tuft bush" : (255, 221, 205), + "tulip tree" : (234, 179, 59), + "tumbleweed" : (222, 166, 129), + "tuna" : ( 53, 53, 66), + "tundora" : ( 74, 66, 68), + "turbo" : (250, 230, 0), + "turkish rose" : (181, 114, 129), + "turmeric" : (202, 187, 72), + "turquoise" : ( 48, 213, 200), + "turquoise blue" : (108, 218, 231), + "turtle green" : ( 42, 56, 11), + "tuscany" : (189, 94, 46), + "tusk" : (238, 243, 195), + "tussock" : (197, 153, 75), + "tutu" : (255, 241, 249), + "twilight" : (228, 207, 222), + "twilight blue" : (238, 253, 255), + "twine" : (194, 149, 93), + "tyrian purple" : (102, 2, 60), + "ultramarine" : ( 18, 10, 143), + "valencia" : (216, 68, 55), + "valentino" : ( 53, 14, 66), + "valhalla" : ( 43, 25, 79), + "van cleef" : ( 73, 23, 12), + "vanilla" : (209, 190, 168), + "vanilla ice" : (243, 217, 223), + "varden" : (255, 246, 223), + "venetian red" : (114, 1, 15), + "venice blue" : ( 5, 89, 137), + "venus" : (146, 133, 144), + "verdigris" : ( 93, 94, 55), + "verdun green" : ( 73, 84, 0), + "vermilion" : (255, 77, 0), + "vesuvius" : (177, 74, 11), + "victoria" : ( 83, 68, 145), + "vida loca" : ( 84, 144, 25), + "viking" : (100, 204, 219), + "vin rouge" : (152, 61, 97), + "viola" : (203, 143, 169), + "violent violet" : ( 41, 12, 94), + "violet" : ( 36, 10, 64), + "violet eggplant" : (153, 17, 153), + "violet red" : (247, 70, 138), + "viridian" : ( 64, 130, 109), + "viridian green" : (103, 137, 117), + "vis vis" : (255, 239, 161), + "vista blue" : (143, 214, 180), + "vista white" : (252, 248, 247), + "vivid tangerine" : (255, 153, 128), + "vivid violet" : (128, 55, 144), + "voodoo" : ( 83, 52, 85), + "vulcan" : ( 16, 18, 29), + "wafer" : (222, 203, 198), + "waikawa gray" : ( 90, 110, 156), + "waiouru" : ( 54, 60, 13), + "walnut" : (119, 63, 26), + "wasabi" : (120, 138, 37), + "water leaf" : (161, 233, 222), + "watercourse" : ( 5, 111, 87), + "waterloo " : (123, 124, 148), + "wattle" : (220, 215, 71), + "watusi" : (255, 221, 207), + "wax flower" : (255, 192, 168), + "we peep" : (247, 219, 230), + "web orange" : (255, 165, 0), + "wedgewood" : ( 78, 127, 158), + "well read" : (180, 51, 50), + "west coast" : ( 98, 81, 25), + "west side" : (255, 145, 15), + "westar" : (220, 217, 210), + "wewak" : (241, 155, 171), + "wheat" : (245, 222, 179), + "wheatfield" : (243, 237, 207), + "whiskey" : (213, 154, 111), + "whisper" : (247, 245, 250), + "white" : (255, 255, 255), + "white ice" : (221, 249, 241), + "white lilac" : (248, 247, 252), + "white linen" : (248, 240, 232), + "white pointer" : (254, 248, 255), + "white rock" : (234, 232, 212), + "wild blue yonder" : (122, 137, 184), + "wild rice" : (236, 224, 144), + "wild sand" : (244, 244, 244), + "wild strawberry" : (255, 51, 153), + "wild watermelon" : (253, 91, 120), + "wild willow" : (185, 196, 106), + "william" : ( 58, 104, 108), + "willow brook" : (223, 236, 218), + "willow grove" : (101, 116, 93), + "windsor" : ( 60, 8, 120), + "wine berry" : ( 89, 29, 53), + "winter hazel" : (213, 209, 149), + "wisp pink" : (254, 244, 248), + "wisteria" : (151, 113, 181), + "wistful" : (164, 166, 211), + "witch haze" : (255, 252, 153), + "wood bark" : ( 38, 17, 5), + "woodland" : ( 77, 83, 40), + "woodrush" : ( 48, 42, 15), + "woodsmoke" : ( 12, 13, 15), + "woody brown" : ( 72, 49, 49), + "xanadu" : (115, 134, 120), + "yellow" : (255, 255, 0), + "yellow green" : (197, 225, 122), + "yellow metal" : (113, 99, 56), + "yellow orange" : (255, 174, 66), + "yellow sea" : (254, 169, 4), + "your pink" : (255, 195, 192), + "yukon gold" : (123, 102, 8), + "yuma" : (206, 194, 145), + "zambezi" : (104, 85, 88), + "zanah" : (218, 236, 214), + "zest" : (229, 132, 27), + "zeus" : ( 41, 35, 25), + "ziggurat" : (191, 219, 226), + "zinnwaldite" : (235, 194, 175), + "zircon" : (244, 248, 255), + "zombie" : (228, 214, 155), + "zorba" : (165, 155, 145), + "zuccini" : ( 4, 64, 34), + "zumthor" : (237, 246, 255)} + +def build_reverse_dict(): + global reverse + global colorhex + global colors + for color in colors: + rgb = colors[color] + hex = '#%02X%02X%02X' % (rgb) + reverse[hex] = color + colorhex[color] = hex + return + + +def get_complementary_hex(color): + # strip the # from the beginning + color = color[1:] + # convert the string into hex + color = int(color, 16) + # invert the three bytes + # as good as substracting each of RGB component by 255(FF) + comp_color = 0xFFFFFF ^ color + # convert the color back to hex by prefixing a # + comp_color = "#%06X" % comp_color + # return the result + return comp_color + +def get_complementary_rgb(red, green, blue): + color_string = '#%02X%02X%02X' % (red, green, blue) + # strip the # from the beginning + color = color_string[1:] + # convert the string into hex + color = int(color, 16) + # invert the three bytes + # as good as substracting each of RGB component by 255(FF) + comp_color = 0xFFFFFF ^ color + # convert the color back to hex by prefixing a # + comp_color = "#%06X" % comp_color + # return the result + return comp_color + +def get_name_from_hex(hex): + global reverse + global colorhex + global colors + + hex = hex.upper() + try: + name = reverse[hex] + except: + name = 'No Hex For Name' + return name + +def get_hex_from_name(name): + global reverse + global colorhex + global colors + + name = name.lower() + try: + hex = colorhex[name] + except: + hex = '#000000' + return hex + +def show_all_colors_on_buttons(): + global reverse + global colorhex + global colors + window = sg.Window('Colors on Buttons Demo', default_element_size=(3, 1), location=(0, 0), icon=MY_WINDOW_ICON, font=("Helvetica", 7)) + row = [] + row_len = 20 + for i, c in enumerate(colors): + hex = get_hex_from_name(c) + button1 = sg.Button(button_text=c, button_color=(get_complementary_hex(hex), hex), size=(8, 1)) + button2 = sg.Button(button_text=c, button_color=(hex, get_complementary_hex(hex)), size=(8, 1)) + row.append(button1) + row.append(button2) + if (i+1) % row_len == 0: + window.AddRow(*row) + row = [] + if row != []: + window.AddRow(*row) + window.Show() + + +GoodColors = [('#0e6251', sg.RGB(255, 246, 122)), + ('white', sg.RGB(0, 74, 60)), + (sg.RGB(0, 210, 124), sg.RGB(0, 74, 60)), + (sg.RGB(0, 210, 87), sg.RGB(0, 74, 60)), + (sg.RGB(0, 164, 73), sg.RGB(0, 74, 60)), + (sg.RGB(0, 74, 60), sg.RGB(0, 74, 60)), + ] + + +def main(): + global colors + global reverse + + build_reverse_dict() + list_of_colors = [c for c in colors] + printable = '\n'.join(map(str, list_of_colors)) + # show_all_colors_on_buttons() + sg.SetOptions(element_padding=(0,0)) + while True: + # ------- Form show ------- # + layout = [[sg.Text('Find color')], + [sg.Text('Demonstration of colors')], + [sg.Text('Enter a color name in text or hex #RRGGBB format')], + [sg.InputText(key='hex')], + [sg.Listbox(list_of_colors, size=(20, 30), bind_return_key=True, key='listbox'), sg.T('Or choose from list')], + [sg.Submit(), sg.Button('Many buttons', button_color=('white', '#0e6251'), key='Many buttons'), sg.ColorChooserButton( 'Chooser', target=(3,0), key='Chooser'), sg.Quit(),], + ] + # [g.Multiline(DefaultText=str(printable), Size=(30,20))]] + button, values = sg.Window('Color Demo', auto_size_buttons=False).Layout(layout).Read() + + # ------- OUTPUT results portion ------- # + if button == 'Quit' or button is None: + exit(0) + elif button == 'Many buttons': + show_all_colors_on_buttons() + + drop_down_value = values['listbox'] + hex_input = values['hex'] + if hex_input == '' and len(drop_down_value) == 0: + continue + + if len(hex_input) != 0: + if hex_input[0] == '#': + color_hex = hex_input.upper() + color_name = get_name_from_hex(hex_input) + else: + color_name = hex_input + color_hex = get_hex_from_name(color_name) + elif drop_down_value is not None and len(drop_down_value) != 0: + color_name = drop_down_value[0] + color_hex = get_hex_from_name(color_name) + + complementary_hex = get_complementary_hex(color_hex) + complementary_color = get_name_from_hex(complementary_hex) + + layout = [[sg.Text('That color and it\'s compliment are shown on these buttons. This form auto-closes')], + [sg.Button(button_text=color_name, button_color=(color_hex, complementary_hex))], + [sg.Button(button_text=complementary_hex + ' ' + complementary_color, button_color=(complementary_hex , color_hex), size=(30, 1))], + ] + sg.Window('Color demo', default_element_size=(100, 1), auto_size_text=True, auto_close=True, auto_close_duration=5, icon=MY_WINDOW_ICON).Layout(layout).Read() + + + +if __name__ == '__main__': + main() diff --git a/Demo_Color_Names.py b/Demo_Color_Names.py new file mode 100644 index 000000000..aeba15d0d --- /dev/null +++ b/Demo_Color_Names.py @@ -0,0 +1,693 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + + +""" + + Shows a big chart of colors... give it a few seconds to create it + Once large window is shown, you can click on any color and another window will popup + showing both white and black text on that color + You will find the list of tkinter colors here: + http://www.tcl.tk/man/tcl8.5/TkCmd/colors.htm + +""" + +color_map = { + 'alice blue': '#F0F8FF', + 'AliceBlue': '#F0F8FF', + 'antique white': '#FAEBD7', + 'AntiqueWhite': '#FAEBD7', + 'AntiqueWhite1': '#FFEFDB', + 'AntiqueWhite2': '#EEDFCC', + 'AntiqueWhite3': '#CDC0B0', + 'AntiqueWhite4': '#8B8378', + 'aquamarine': '#7FFFD4', + 'aquamarine1': '#7FFFD4', + 'aquamarine2': '#76EEC6', + 'aquamarine3': '#66CDAA', + 'aquamarine4': '#458B74', + 'azure': '#F0FFFF', + 'azure1': '#F0FFFF', + 'azure2': '#E0EEEE', + 'azure3': '#C1CDCD', + 'azure4': '#838B8B', + 'beige': '#F5F5DC', + 'bisque': '#FFE4C4', + 'bisque1': '#FFE4C4', + 'bisque2': '#EED5B7', + 'bisque3': '#CDB79E', + 'bisque4': '#8B7D6B', + 'black': '#000000', + 'blanched almond': '#FFEBCD', + 'BlanchedAlmond': '#FFEBCD', + 'blue': '#0000FF', + 'blue violet': '#8A2BE2', + 'blue1': '#0000FF', + 'blue2': '#0000EE', + 'blue3': '#0000CD', + 'blue4': '#00008B', + 'BlueViolet': '#8A2BE2', + 'brown': '#A52A2A', + 'brown1': '#FF4040', + 'brown2': '#EE3B3B', + 'brown3': '#CD3333', + 'brown4': '#8B2323', + 'burlywood': '#DEB887', + 'burlywood1': '#FFD39B', + 'burlywood2': '#EEC591', + 'burlywood3': '#CDAA7D', + 'burlywood4': '#8B7355', + 'cadet blue': '#5F9EA0', + 'CadetBlue': '#5F9EA0', + 'CadetBlue1': '#98F5FF', + 'CadetBlue2': '#8EE5EE', + 'CadetBlue3': '#7AC5CD', + 'CadetBlue4': '#53868B', + 'chartreuse': '#7FFF00', + 'chartreuse1': '#7FFF00', + 'chartreuse2': '#76EE00', + 'chartreuse3': '#66CD00', + 'chartreuse4': '#458B00', + 'chocolate': '#D2691E', + 'chocolate1': '#FF7F24', + 'chocolate2': '#EE7621', + 'chocolate3': '#CD661D', + 'chocolate4': '#8B4513', + 'coral': '#FF7F50', + 'coral1': '#FF7256', + 'coral2': '#EE6A50', + 'coral3': '#CD5B45', + 'coral4': '#8B3E2F', + 'cornflower blue': '#6495ED', + 'CornflowerBlue': '#6495ED', + 'cornsilk': '#FFF8DC', + 'cornsilk1': '#FFF8DC', + 'cornsilk2': '#EEE8CD', + 'cornsilk3': '#CDC8B1', + 'cornsilk4': '#8B8878', + 'cyan': '#00FFFF', + 'cyan1': '#00FFFF', + 'cyan2': '#00EEEE', + 'cyan3': '#00CDCD', + 'cyan4': '#008B8B', + 'dark blue': '#00008B', + 'dark cyan': '#008B8B', + 'dark goldenrod': '#B8860B', + 'dark gray': '#A9A9A9', + 'dark green': '#006400', + 'dark grey': '#A9A9A9', + 'dark khaki': '#BDB76B', + 'dark magenta': '#8B008B', + 'dark olive green': '#556B2F', + 'dark orange': '#FF8C00', + 'dark orchid': '#9932CC', + 'dark red': '#8B0000', + 'dark salmon': '#E9967A', + 'dark sea green': '#8FBC8F', + 'dark slate blue': '#483D8B', + 'dark slate gray': '#2F4F4F', + 'dark slate grey': '#2F4F4F', + 'dark turquoise': '#00CED1', + 'dark violet': '#9400D3', + 'DarkBlue': '#00008B', + 'DarkCyan': '#008B8B', + 'DarkGoldenrod': '#B8860B', + 'DarkGoldenrod1': '#FFB90F', + 'DarkGoldenrod2': '#EEAD0E', + 'DarkGoldenrod3': '#CD950C', + 'DarkGoldenrod4': '#8B6508', + 'DarkGray': '#A9A9A9', + 'DarkGreen': '#006400', + 'DarkGrey': '#A9A9A9', + 'DarkKhaki': '#BDB76B', + 'DarkMagenta': '#8B008B', + 'DarkOliveGreen': '#556B2F', + 'DarkOliveGreen1': '#CAFF70', + 'DarkOliveGreen2': '#BCEE68', + 'DarkOliveGreen3': '#A2CD5A', + 'DarkOliveGreen4': '#6E8B3D', + 'DarkOrange': '#FF8C00', + 'DarkOrange1': '#FF7F00', + 'DarkOrange2': '#EE7600', + 'DarkOrange3': '#CD6600', + 'DarkOrange4': '#8B4500', + 'DarkOrchid': '#9932CC', + 'DarkOrchid1': '#BF3EFF', + 'DarkOrchid2': '#B23AEE', + 'DarkOrchid3': '#9A32CD', + 'DarkOrchid4': '#68228B', + 'DarkRed': '#8B0000', + 'DarkSalmon': '#E9967A', + 'DarkSeaGreen': '#8FBC8F', + 'DarkSeaGreen1': '#C1FFC1', + 'DarkSeaGreen2': '#B4EEB4', + 'DarkSeaGreen3': '#9BCD9B', + 'DarkSeaGreen4': '#698B69', + 'DarkSlateBlue': '#483D8B', + 'DarkSlateGray': '#2F4F4F', + 'DarkSlateGray1': '#97FFFF', + 'DarkSlateGray2': '#8DEEEE', + 'DarkSlateGray3': '#79CDCD', + 'DarkSlateGray4': '#528B8B', + 'DarkSlateGrey': '#2F4F4F', + 'DarkTurquoise': '#00CED1', + 'DarkViolet': '#9400D3', + 'deep pink': '#FF1493', + 'deep sky blue': '#00BFFF', + 'DeepPink': '#FF1493', + 'DeepPink1': '#FF1493', + 'DeepPink2': '#EE1289', + 'DeepPink3': '#CD1076', + 'DeepPink4': '#8B0A50', + 'DeepSkyBlue': '#00BFFF', + 'DeepSkyBlue1': '#00BFFF', + 'DeepSkyBlue2': '#00B2EE', + 'DeepSkyBlue3': '#009ACD', + 'DeepSkyBlue4': '#00688B', + 'dim gray': '#696969', + 'dim grey': '#696969', + 'DimGray': '#696969', + 'DimGrey': '#696969', + 'dodger blue': '#1E90FF', + 'DodgerBlue': '#1E90FF', + 'DodgerBlue1': '#1E90FF', + 'DodgerBlue2': '#1C86EE', + 'DodgerBlue3': '#1874CD', + 'DodgerBlue4': '#104E8B', + 'firebrick': '#B22222', + 'firebrick1': '#FF3030', + 'firebrick2': '#EE2C2C', + 'firebrick3': '#CD2626', + 'firebrick4': '#8B1A1A', + 'floral white': '#FFFAF0', + 'FloralWhite': '#FFFAF0', + 'forest green': '#228B22', + 'ForestGreen': '#228B22', + 'gainsboro': '#DCDCDC', + 'ghost white': '#F8F8FF', + 'GhostWhite': '#F8F8FF', + 'gold': '#FFD700', + 'gold1': '#FFD700', + 'gold2': '#EEC900', + 'gold3': '#CDAD00', + 'gold4': '#8B7500', + 'goldenrod': '#DAA520', + 'goldenrod1': '#FFC125', + 'goldenrod2': '#EEB422', + 'goldenrod3': '#CD9B1D', + 'goldenrod4': '#8B6914', + 'green': '#00FF00', + 'green yellow': '#ADFF2F', + 'green1': '#00FF00', + 'green2': '#00EE00', + 'green3': '#00CD00', + 'green4': '#008B00', + 'GreenYellow': '#ADFF2F', + 'grey': '#BEBEBE', + 'grey0': '#000000', + 'grey1': '#030303', + 'grey2': '#050505', + 'grey3': '#080808', + 'grey4': '#0A0A0A', + 'grey5': '#0D0D0D', + 'grey6': '#0F0F0F', + 'grey7': '#121212', + 'grey8': '#141414', + 'grey9': '#171717', + 'grey10': '#1A1A1A', + 'grey11': '#1C1C1C', + 'grey12': '#1F1F1F', + 'grey13': '#212121', + 'grey14': '#242424', + 'grey15': '#262626', + 'grey16': '#292929', + 'grey17': '#2B2B2B', + 'grey18': '#2E2E2E', + 'grey19': '#303030', + 'grey20': '#333333', + 'grey21': '#363636', + 'grey22': '#383838', + 'grey23': '#3B3B3B', + 'grey24': '#3D3D3D', + 'grey25': '#404040', + 'grey26': '#424242', + 'grey27': '#454545', + 'grey28': '#474747', + 'grey29': '#4A4A4A', + 'grey30': '#4D4D4D', + 'grey31': '#4F4F4F', + 'grey32': '#525252', + 'grey33': '#545454', + 'grey34': '#575757', + 'grey35': '#595959', + 'grey36': '#5C5C5C', + 'grey37': '#5E5E5E', + 'grey38': '#616161', + 'grey39': '#636363', + 'grey40': '#666666', + 'grey41': '#696969', + 'grey42': '#6B6B6B', + 'grey43': '#6E6E6E', + 'grey44': '#707070', + 'grey45': '#737373', + 'grey46': '#757575', + 'grey47': '#787878', + 'grey48': '#7A7A7A', + 'grey49': '#7D7D7D', + 'grey50': '#7F7F7F', + 'grey51': '#828282', + 'grey52': '#858585', + 'grey53': '#878787', + 'grey54': '#8A8A8A', + 'grey55': '#8C8C8C', + 'grey56': '#8F8F8F', + 'grey57': '#919191', + 'grey58': '#949494', + 'grey59': '#969696', + 'grey60': '#999999', + 'grey61': '#9C9C9C', + 'grey62': '#9E9E9E', + 'grey63': '#A1A1A1', + 'grey64': '#A3A3A3', + 'grey65': '#A6A6A6', + 'grey66': '#A8A8A8', + 'grey67': '#ABABAB', + 'grey68': '#ADADAD', + 'grey69': '#B0B0B0', + 'grey70': '#B3B3B3', + 'grey71': '#B5B5B5', + 'grey72': '#B8B8B8', + 'grey73': '#BABABA', + 'grey74': '#BDBDBD', + 'grey75': '#BFBFBF', + 'grey76': '#C2C2C2', + 'grey77': '#C4C4C4', + 'grey78': '#C7C7C7', + 'grey79': '#C9C9C9', + 'grey80': '#CCCCCC', + 'grey81': '#CFCFCF', + 'grey82': '#D1D1D1', + 'grey83': '#D4D4D4', + 'grey84': '#D6D6D6', + 'grey85': '#D9D9D9', + 'grey86': '#DBDBDB', + 'grey87': '#DEDEDE', + 'grey88': '#E0E0E0', + 'grey89': '#E3E3E3', + 'grey90': '#E5E5E5', + 'grey91': '#E8E8E8', + 'grey92': '#EBEBEB', + 'grey93': '#EDEDED', + 'grey94': '#F0F0F0', + 'grey95': '#F2F2F2', + 'grey96': '#F5F5F5', + 'grey97': '#F7F7F7', + 'grey98': '#FAFAFA', + 'grey99': '#FCFCFC', + 'grey100': '#FFFFFF', + 'honeydew': '#F0FFF0', + 'honeydew1': '#F0FFF0', + 'honeydew2': '#E0EEE0', + 'honeydew3': '#C1CDC1', + 'honeydew4': '#838B83', + 'hot pink': '#FF69B4', + 'HotPink': '#FF69B4', + 'HotPink1': '#FF6EB4', + 'HotPink2': '#EE6AA7', + 'HotPink3': '#CD6090', + 'HotPink4': '#8B3A62', + 'indian red': '#CD5C5C', + 'IndianRed': '#CD5C5C', + 'IndianRed1': '#FF6A6A', + 'IndianRed2': '#EE6363', + 'IndianRed3': '#CD5555', + 'IndianRed4': '#8B3A3A', + 'ivory': '#FFFFF0', + 'ivory1': '#FFFFF0', + 'ivory2': '#EEEEE0', + 'ivory3': '#CDCDC1', + 'ivory4': '#8B8B83', + 'khaki': '#F0E68C', + 'khaki1': '#FFF68F', + 'khaki2': '#EEE685', + 'khaki3': '#CDC673', + 'khaki4': '#8B864E', + 'lavender': '#E6E6FA', + 'lavender blush': '#FFF0F5', + 'LavenderBlush': '#FFF0F5', + 'LavenderBlush1': '#FFF0F5', + 'LavenderBlush2': '#EEE0E5', + 'LavenderBlush3': '#CDC1C5', + 'LavenderBlush4': '#8B8386', + 'lawn green': '#7CFC00', + 'LawnGreen': '#7CFC00', + 'lemon chiffon': '#FFFACD', + 'LemonChiffon': '#FFFACD', + 'LemonChiffon1': '#FFFACD', + 'LemonChiffon2': '#EEE9BF', + 'LemonChiffon3': '#CDC9A5', + 'LemonChiffon4': '#8B8970', + 'light blue': '#ADD8E6', + 'light coral': '#F08080', + 'light cyan': '#E0FFFF', + 'light goldenrod': '#EEDD82', + 'light goldenrod yellow': '#FAFAD2', + 'light gray': '#D3D3D3', + 'light green': '#90EE90', + 'light grey': '#D3D3D3', + 'light pink': '#FFB6C1', + 'light salmon': '#FFA07A', + 'light sea green': '#20B2AA', + 'light sky blue': '#87CEFA', + 'light slate blue': '#8470FF', + 'light slate gray': '#778899', + 'light slate grey': '#778899', + 'light steel blue': '#B0C4DE', + 'light yellow': '#FFFFE0', + 'LightBlue': '#ADD8E6', + 'LightBlue1': '#BFEFFF', + 'LightBlue2': '#B2DFEE', + 'LightBlue3': '#9AC0CD', + 'LightBlue4': '#68838B', + 'LightCoral': '#F08080', + 'LightCyan': '#E0FFFF', + 'LightCyan1': '#E0FFFF', + 'LightCyan2': '#D1EEEE', + 'LightCyan3': '#B4CDCD', + 'LightCyan4': '#7A8B8B', + 'LightGoldenrod': '#EEDD82', + 'LightGoldenrod1': '#FFEC8B', + 'LightGoldenrod2': '#EEDC82', + 'LightGoldenrod3': '#CDBE70', + 'LightGoldenrod4': '#8B814C', + 'LightGoldenrodYellow': '#FAFAD2', + 'LightGray': '#D3D3D3', + 'LightGreen': '#90EE90', + 'LightGrey': '#D3D3D3', + 'LightPink': '#FFB6C1', + 'LightPink1': '#FFAEB9', + 'LightPink2': '#EEA2AD', + 'LightPink3': '#CD8C95', + 'LightPink4': '#8B5F65', + 'LightSalmon': '#FFA07A', + 'LightSalmon1': '#FFA07A', + 'LightSalmon2': '#EE9572', + 'LightSalmon3': '#CD8162', + 'LightSalmon4': '#8B5742', + 'LightSeaGreen': '#20B2AA', + 'LightSkyBlue': '#87CEFA', + 'LightSkyBlue1': '#B0E2FF', + 'LightSkyBlue2': '#A4D3EE', + 'LightSkyBlue3': '#8DB6CD', + 'LightSkyBlue4': '#607B8B', + 'LightSlateBlue': '#8470FF', + 'LightSlateGray': '#778899', + 'LightSlateGrey': '#778899', + 'LightSteelBlue': '#B0C4DE', + 'LightSteelBlue1': '#CAE1FF', + 'LightSteelBlue2': '#BCD2EE', + 'LightSteelBlue3': '#A2B5CD', + 'LightSteelBlue4': '#6E7B8B', + 'LightYellow': '#FFFFE0', + 'LightYellow1': '#FFFFE0', + 'LightYellow2': '#EEEED1', + 'LightYellow3': '#CDCDB4', + 'LightYellow4': '#8B8B7A', + 'lime green': '#32CD32', + 'LimeGreen': '#32CD32', + 'linen': '#FAF0E6', + 'magenta': '#FF00FF', + 'magenta1': '#FF00FF', + 'magenta2': '#EE00EE', + 'magenta3': '#CD00CD', + 'magenta4': '#8B008B', + 'maroon': '#B03060', + 'maroon1': '#FF34B3', + 'maroon2': '#EE30A7', + 'maroon3': '#CD2990', + 'maroon4': '#8B1C62', + 'medium aquamarine': '#66CDAA', + 'medium blue': '#0000CD', + 'medium orchid': '#BA55D3', + 'medium purple': '#9370DB', + 'medium sea green': '#3CB371', + 'medium slate blue': '#7B68EE', + 'medium spring green': '#00FA9A', + 'medium turquoise': '#48D1CC', + 'medium violet red': '#C71585', + 'MediumAquamarine': '#66CDAA', + 'MediumBlue': '#0000CD', + 'MediumOrchid': '#BA55D3', + 'MediumOrchid1': '#E066FF', + 'MediumOrchid2': '#D15FEE', + 'MediumOrchid3': '#B452CD', + 'MediumOrchid4': '#7A378B', + 'MediumPurple': '#9370DB', + 'MediumPurple1': '#AB82FF', + 'MediumPurple2': '#9F79EE', + 'MediumPurple3': '#8968CD', + 'MediumPurple4': '#5D478B', + 'MediumSeaGreen': '#3CB371', + 'MediumSlateBlue': '#7B68EE', + 'MediumSpringGreen': '#00FA9A', + 'MediumTurquoise': '#48D1CC', + 'MediumVioletRed': '#C71585', + 'midnight blue': '#191970', + 'MidnightBlue': '#191970', + 'mint cream': '#F5FFFA', + 'MintCream': '#F5FFFA', + 'misty rose': '#FFE4E1', + 'MistyRose': '#FFE4E1', + 'MistyRose1': '#FFE4E1', + 'MistyRose2': '#EED5D2', + 'MistyRose3': '#CDB7B5', + 'MistyRose4': '#8B7D7B', + 'moccasin': '#FFE4B5', + 'navajo white': '#FFDEAD', + 'NavajoWhite': '#FFDEAD', + 'NavajoWhite1': '#FFDEAD', + 'NavajoWhite2': '#EECFA1', + 'NavajoWhite3': '#CDB38B', + 'NavajoWhite4': '#8B795E', + 'navy': '#000080', + 'navy blue': '#000080', + 'NavyBlue': '#000080', + 'old lace': '#FDF5E6', + 'OldLace': '#FDF5E6', + 'olive drab': '#6B8E23', + 'OliveDrab': '#6B8E23', + 'OliveDrab1': '#C0FF3E', + 'OliveDrab2': '#B3EE3A', + 'OliveDrab3': '#9ACD32', + 'OliveDrab4': '#698B22', + 'orange': '#FFA500', + 'orange red': '#FF4500', + 'orange1': '#FFA500', + 'orange2': '#EE9A00', + 'orange3': '#CD8500', + 'orange4': '#8B5A00', + 'OrangeRed': '#FF4500', + 'OrangeRed1': '#FF4500', + 'OrangeRed2': '#EE4000', + 'OrangeRed3': '#CD3700', + 'OrangeRed4': '#8B2500', + 'orchid': '#DA70D6', + 'orchid1': '#FF83FA', + 'orchid2': '#EE7AE9', + 'orchid3': '#CD69C9', + 'orchid4': '#8B4789', + 'pale goldenrod': '#EEE8AA', + 'pale green': '#98FB98', + 'pale turquoise': '#AFEEEE', + 'pale violet red': '#DB7093', + 'PaleGoldenrod': '#EEE8AA', + 'PaleGreen': '#98FB98', + 'PaleGreen1': '#9AFF9A', + 'PaleGreen2': '#90EE90', + 'PaleGreen3': '#7CCD7C', + 'PaleGreen4': '#548B54', + 'PaleTurquoise': '#AFEEEE', + 'PaleTurquoise1': '#BBFFFF', + 'PaleTurquoise2': '#AEEEEE', + 'PaleTurquoise3': '#96CDCD', + 'PaleTurquoise4': '#668B8B', + 'PaleVioletRed': '#DB7093', + 'PaleVioletRed1': '#FF82AB', + 'PaleVioletRed2': '#EE799F', + 'PaleVioletRed3': '#CD687F', + 'PaleVioletRed4': '#8B475D', + 'papaya whip': '#FFEFD5', + 'PapayaWhip': '#FFEFD5', + 'peach puff': '#FFDAB9', + 'PeachPuff': '#FFDAB9', + 'PeachPuff1': '#FFDAB9', + 'PeachPuff2': '#EECBAD', + 'PeachPuff3': '#CDAF95', + 'PeachPuff4': '#8B7765', + 'peru': '#CD853F', + 'pink': '#FFC0CB', + 'pink1': '#FFB5C5', + 'pink2': '#EEA9B8', + 'pink3': '#CD919E', + 'pink4': '#8B636C', + 'plum': '#DDA0DD', + 'plum1': '#FFBBFF', + 'plum2': '#EEAEEE', + 'plum3': '#CD96CD', + 'plum4': '#8B668B', + 'powder blue': '#B0E0E6', + 'PowderBlue': '#B0E0E6', + 'purple': '#A020F0', + 'purple1': '#9B30FF', + 'purple2': '#912CEE', + 'purple3': '#7D26CD', + 'purple4': '#551A8B', + 'red': '#FF0000', + 'red1': '#FF0000', + 'red2': '#EE0000', + 'red3': '#CD0000', + 'red4': '#8B0000', + 'rosy brown': '#BC8F8F', + 'RosyBrown': '#BC8F8F', + 'RosyBrown1': '#FFC1C1', + 'RosyBrown2': '#EEB4B4', + 'RosyBrown3': '#CD9B9B', + 'RosyBrown4': '#8B6969', + 'royal blue': '#4169E1', + 'RoyalBlue': '#4169E1', + 'RoyalBlue1': '#4876FF', + 'RoyalBlue2': '#436EEE', + 'RoyalBlue3': '#3A5FCD', + 'RoyalBlue4': '#27408B', + 'saddle brown': '#8B4513', + 'SaddleBrown': '#8B4513', + 'salmon': '#FA8072', + 'salmon1': '#FF8C69', + 'salmon2': '#EE8262', + 'salmon3': '#CD7054', + 'salmon4': '#8B4C39', + 'sandy brown': '#F4A460', + 'SandyBrown': '#F4A460', + 'sea green': '#2E8B57', + 'SeaGreen': '#2E8B57', + 'SeaGreen1': '#54FF9F', + 'SeaGreen2': '#4EEE94', + 'SeaGreen3': '#43CD80', + 'SeaGreen4': '#2E8B57', + 'seashell': '#FFF5EE', + 'seashell1': '#FFF5EE', + 'seashell2': '#EEE5DE', + 'seashell3': '#CDC5BF', + 'seashell4': '#8B8682', + 'sienna': '#A0522D', + 'sienna1': '#FF8247', + 'sienna2': '#EE7942', + 'sienna3': '#CD6839', + 'sienna4': '#8B4726', + 'sky blue': '#87CEEB', + 'SkyBlue': '#87CEEB', + 'SkyBlue1': '#87CEFF', + 'SkyBlue2': '#7EC0EE', + 'SkyBlue3': '#6CA6CD', + 'SkyBlue4': '#4A708B', + 'slate blue': '#6A5ACD', + 'slate gray': '#708090', + 'slate grey': '#708090', + 'SlateBlue': '#6A5ACD', + 'SlateBlue1': '#836FFF', + 'SlateBlue2': '#7A67EE', + 'SlateBlue3': '#6959CD', + 'SlateBlue4': '#473C8B', + 'SlateGray': '#708090', + 'SlateGray1': '#C6E2FF', + 'SlateGray2': '#B9D3EE', + 'SlateGray3': '#9FB6CD', + 'SlateGray4': '#6C7B8B', + 'SlateGrey': '#708090', + 'snow': '#FFFAFA', + 'snow1': '#FFFAFA', + 'snow2': '#EEE9E9', + 'snow3': '#CDC9C9', + 'snow4': '#8B8989', + 'spring green': '#00FF7F', + 'SpringGreen': '#00FF7F', + 'SpringGreen1': '#00FF7F', + 'SpringGreen2': '#00EE76', + 'SpringGreen3': '#00CD66', + 'SpringGreen4': '#008B45', + 'steel blue': '#4682B4', + 'SteelBlue': '#4682B4', + 'SteelBlue1': '#63B8FF', + 'SteelBlue2': '#5CACEE', + 'SteelBlue3': '#4F94CD', + 'SteelBlue4': '#36648B', + 'tan': '#D2B48C', + 'tan1': '#FFA54F', + 'tan2': '#EE9A49', + 'tan3': '#CD853F', + 'tan4': '#8B5A2B', + 'thistle': '#D8BFD8', + 'thistle1': '#FFE1FF', + 'thistle2': '#EED2EE', + 'thistle3': '#CDB5CD', + 'thistle4': '#8B7B8B', + 'tomato': '#FF6347', + 'tomato1': '#FF6347', + 'tomato2': '#EE5C42', + 'tomato3': '#CD4F39', + 'tomato4': '#8B3626', + 'turquoise': '#40E0D0', + 'turquoise1': '#00F5FF', + 'turquoise2': '#00E5EE', + 'turquoise3': '#00C5CD', + 'turquoise4': '#00868B', + 'violet': '#EE82EE', + 'violet red': '#D02090', + 'VioletRed': '#D02090', + 'VioletRed1': '#FF3E96', + 'VioletRed2': '#EE3A8C', + 'VioletRed3': '#CD3278', + 'VioletRed4': '#8B2252', + 'wheat': '#F5DEB3', + 'wheat1': '#FFE7BA', + 'wheat2': '#EED8AE', + 'wheat3': '#CDBA96', + 'wheat4': '#8B7E66', + 'white': '#FFFFFF', + 'white smoke': '#F5F5F5', + 'WhiteSmoke': '#F5F5F5', + 'yellow': '#FFFF00', + 'yellow green': '#9ACD32', + 'yellow1': '#FFFF00', + 'yellow2': '#EEEE00', + 'yellow3': '#CDCD00', + 'yellow4': '#8B8B00', + 'YellowGreen': '#9ACD32', +} + + +sg.SetOptions(button_element_size=(12,1), element_padding=(0,0), auto_size_buttons=False, border_width=1) + +layout = [[sg.Text('Hover mouse to see RGB value, click for white & black text', text_color='blue', font='Any 15', relief=sg.RELIEF_SUNKEN, justification='center', size=(100,1), background_color='light green', pad=(0,(0,20))),]] +row = [] +# -- Create primary color viewer window -- +for i, color in enumerate(color_map): + row.append(sg.RButton(color, button_color=('black', color), key=color, tooltip=color_map[color])) + if (i+1) % 15 == 0: + layout.append(row) + row = [] + +window = sg.Window('Color Viewer', grab_anywhere=False, font=('any 9')).Layout(layout) + +# -- Event loop -- +while True: + b, v = window.Read() + if b is None: + break + # -- Create a secondary window that shows white and black text on chosen color + layout2 =[[sg.Button(b, button_color=('white', b), tooltip=color_map[b]), sg.Button(b, button_color=('black', b), tooltip=color_map[b])] ] + sg.Window('Buttons with white and black text', keep_on_top=True).Layout(layout2).Read() \ No newline at end of file diff --git a/Demo_Color_Names_Smaller_List.py b/Demo_Color_Names_Smaller_List.py new file mode 100644 index 000000000..fac8fe5c0 --- /dev/null +++ b/Demo_Color_Names_Smaller_List.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +""" + Color names courtesy of Big Daddy's Wiki-Python + http://www.wikipython.com/tkinter-ttk-tix/summary-information/colors/ + + Shows a big chart of colors... give it a few seconds to create it + Once large window is shown, you can click on any color and another window will popup + showing both white and black text on that color +""" +COLORS = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace', + 'linen', 'antique white', 'papaya whip', 'blanched almond', 'bisque', 'peach puff', + 'navajo white', 'lemon chiffon', 'mint cream', 'azure', 'alice blue', 'lavender', + 'lavender blush', 'misty rose', 'dark slate gray', 'dim gray', 'slate gray', + 'light slate gray', 'gray', 'light gray', 'midnight blue', 'navy', 'cornflower blue', 'dark slate blue', + 'slate blue', 'medium slate blue', 'light slate blue', 'medium blue', 'royal blue', 'blue', + 'dodger blue', 'deep sky blue', 'sky blue', 'light sky blue', 'steel blue', 'light steel blue', + 'light blue', 'powder blue', 'pale turquoise', 'dark turquoise', 'medium turquoise', 'turquoise', + 'cyan', 'light cyan', 'cadet blue', 'medium aquamarine', 'aquamarine', 'dark green', 'dark olive green', + 'dark sea green', 'sea green', 'medium sea green', 'light sea green', 'pale green', 'spring green', + 'lawn green', 'medium spring green', 'green yellow', 'lime green', 'yellow green', + 'forest green', 'olive drab', 'dark khaki', 'khaki', 'pale goldenrod', 'light goldenrod yellow', + 'light yellow', 'yellow', 'gold', 'light goldenrod', 'goldenrod', 'dark goldenrod', 'rosy brown', + 'indian red', 'saddle brown', 'sandy brown', + 'dark salmon', 'salmon', 'light salmon', 'orange', 'dark orange', + 'coral', 'light coral', 'tomato', 'orange red', 'red', 'hot pink', 'deep pink', 'pink', 'light pink', + 'pale violet red', 'maroon', 'medium violet red', 'violet red', + 'medium orchid', 'dark orchid', 'dark violet', 'blue violet', 'purple', 'medium purple', + 'thistle', 'snow2', 'snow3', + 'snow4', 'seashell2', 'seashell3', 'seashell4', 'AntiqueWhite1', 'AntiqueWhite2', + 'AntiqueWhite3', 'AntiqueWhite4', 'bisque2', 'bisque3', 'bisque4', 'PeachPuff2', + 'PeachPuff3', 'PeachPuff4', 'NavajoWhite2', 'NavajoWhite3', 'NavajoWhite4', + 'LemonChiffon2', 'LemonChiffon3', 'LemonChiffon4', 'cornsilk2', 'cornsilk3', + 'cornsilk4', 'ivory2', 'ivory3', 'ivory4', 'honeydew2', 'honeydew3', 'honeydew4', + 'LavenderBlush2', 'LavenderBlush3', 'LavenderBlush4', 'MistyRose2', 'MistyRose3', + 'MistyRose4', 'azure2', 'azure3', 'azure4', 'SlateBlue1', 'SlateBlue2', 'SlateBlue3', + 'SlateBlue4', 'RoyalBlue1', 'RoyalBlue2', 'RoyalBlue3', 'RoyalBlue4', 'blue2', 'blue4', + 'DodgerBlue2', 'DodgerBlue3', 'DodgerBlue4', 'SteelBlue1', 'SteelBlue2', + 'SteelBlue3', 'SteelBlue4', 'DeepSkyBlue2', 'DeepSkyBlue3', 'DeepSkyBlue4', + 'SkyBlue1', 'SkyBlue2', 'SkyBlue3', 'SkyBlue4', 'LightSkyBlue1', 'LightSkyBlue2', + 'LightSkyBlue3', 'LightSkyBlue4', 'Slategray1', 'Slategray2', 'Slategray3', + 'Slategray4', 'LightSteelBlue1', 'LightSteelBlue2', 'LightSteelBlue3', + 'LightSteelBlue4', 'LightBlue1', 'LightBlue2', 'LightBlue3', 'LightBlue4', + 'LightCyan2', 'LightCyan3', 'LightCyan4', 'PaleTurquoise1', 'PaleTurquoise2', + 'PaleTurquoise3', 'PaleTurquoise4', 'CadetBlue1', 'CadetBlue2', 'CadetBlue3', + 'CadetBlue4', 'turquoise1', 'turquoise2', 'turquoise3', 'turquoise4', 'cyan2', 'cyan3', + 'cyan4', 'DarkSlategray1', 'DarkSlategray2', 'DarkSlategray3', 'DarkSlategray4', + 'aquamarine2', 'aquamarine4', 'DarkSeaGreen1', 'DarkSeaGreen2', 'DarkSeaGreen3', + 'DarkSeaGreen4', 'SeaGreen1', 'SeaGreen2', 'SeaGreen3', 'PaleGreen1', 'PaleGreen2', + 'PaleGreen3', 'PaleGreen4', 'SpringGreen2', 'SpringGreen3', 'SpringGreen4', + 'green2', 'green3', 'green4', 'chartreuse2', 'chartreuse3', 'chartreuse4', + 'OliveDrab1', 'OliveDrab2', 'OliveDrab4', 'DarkOliveGreen1', 'DarkOliveGreen2', + 'DarkOliveGreen3', 'DarkOliveGreen4', 'khaki1', 'khaki2', 'khaki3', 'khaki4', + 'LightGoldenrod1', 'LightGoldenrod2', 'LightGoldenrod3', 'LightGoldenrod4', + 'LightYellow2', 'LightYellow3', 'LightYellow4', 'yellow2', 'yellow3', 'yellow4', + 'gold2', 'gold3', 'gold4', 'goldenrod1', 'goldenrod2', 'goldenrod3', 'goldenrod4', + 'DarkGoldenrod1', 'DarkGoldenrod2', 'DarkGoldenrod3', 'DarkGoldenrod4', + 'RosyBrown1', 'RosyBrown2', 'RosyBrown3', 'RosyBrown4', 'IndianRed1', 'IndianRed2', + 'IndianRed3', 'IndianRed4', 'sienna1', 'sienna2', 'sienna3', 'sienna4', 'burlywood1', + 'burlywood2', 'burlywood3', 'burlywood4', 'wheat1', 'wheat2', 'wheat3', 'wheat4', 'tan1', + 'tan2', 'tan4', 'chocolate1', 'chocolate2', 'chocolate3', 'firebrick1', 'firebrick2', + 'firebrick3', 'firebrick4', 'brown1', 'brown2', 'brown3', 'brown4', 'salmon1', 'salmon2', + 'salmon3', 'salmon4', 'LightSalmon2', 'LightSalmon3', 'LightSalmon4', 'orange2', + 'orange3', 'orange4', 'DarkOrange1', 'DarkOrange2', 'DarkOrange3', 'DarkOrange4', + 'coral1', 'coral2', 'coral3', 'coral4', 'tomato2', 'tomato3', 'tomato4', 'OrangeRed2', + 'OrangeRed3', 'OrangeRed4', 'red2', 'red3', 'red4', 'DeepPink2', 'DeepPink3', 'DeepPink4', + 'HotPink1', 'HotPink2', 'HotPink3', 'HotPink4', 'pink1', 'pink2', 'pink3', 'pink4', + 'LightPink1', 'LightPink2', 'LightPink3', 'LightPink4', 'PaleVioletRed1', + 'PaleVioletRed2', 'PaleVioletRed3', 'PaleVioletRed4', 'maroon1', 'maroon2', + 'maroon3', 'maroon4', 'VioletRed1', 'VioletRed2', 'VioletRed3', 'VioletRed4', + 'magenta2', 'magenta3', 'magenta4', 'orchid1', 'orchid2', 'orchid3', 'orchid4', 'plum1', + 'plum2', 'plum3', 'plum4', 'MediumOrchid1', 'MediumOrchid2', 'MediumOrchid3', + 'MediumOrchid4', 'DarkOrchid1', 'DarkOrchid2', 'DarkOrchid3', 'DarkOrchid4', + 'purple1', 'purple2', 'purple3', 'purple4', 'MediumPurple1', 'MediumPurple2', + 'MediumPurple3', 'MediumPurple4', 'thistle1', 'thistle2', 'thistle3', 'thistle4', + 'grey1', 'grey2', 'grey3', 'grey4', 'grey5', 'grey6', 'grey7', 'grey8', 'grey9', 'grey10', + 'grey11', 'grey12', 'grey13', 'grey14', 'grey15', 'grey16', 'grey17', 'grey18', 'grey19', + 'grey20', 'grey21', 'grey22', 'grey23', 'grey24', 'grey25', 'grey26', 'grey27', 'grey28', + 'grey29', 'grey30', 'grey31', 'grey32', 'grey33', 'grey34', 'grey35', 'grey36', 'grey37', + 'grey38', 'grey39', 'grey40', 'grey42', 'grey43', 'grey44', 'grey45', 'grey46', 'grey47', + 'grey48', 'grey49', 'grey50', 'grey51', 'grey52', 'grey53', 'grey54', 'grey55', 'grey56', + 'grey57', 'grey58', 'grey59', 'grey60', 'grey61', 'grey62', 'grey63', 'grey64', 'grey65', + 'grey66', 'grey67', 'grey68', 'grey69', 'grey70', 'grey71', 'grey72', 'grey73', 'grey74', + 'grey75', 'grey76', 'grey77', 'grey78', 'grey79', 'grey80', 'grey81', 'grey82', 'grey83', + 'grey84', 'grey85', 'grey86', 'grey87', 'grey88', 'grey89', 'grey90', 'grey91', 'grey92', + 'grey93', 'grey94', 'grey95', 'grey97', 'grey98', 'grey99'] + +sg.SetOptions(button_element_size=(12,1), element_padding=(0,0), auto_size_buttons=False, border_width=0) + +layout = [[sg.Text('Click on a color square to see both white and black text on that color', text_color='blue', font='Any 15')]] +row = [] +# -- Create primary color viewer window -- +for i, color in enumerate(COLORS): + row.append(sg.RButton(color, button_color=('black', color), key=color)) + if (i+1) % 12 == 0: + layout.append(row) + row = [] + +window = sg.Window('Color Viewer', grab_anywhere=False, font=('any 9')).Layout(layout) + +# -- Event loop -- +while True: + b, v = window.Read() + if b is None: + break + # -- Create a secondary window that shows white and black text on chosen color + layout2 =[[sg.Button(b, button_color=('white', b)), sg.Button(b, button_color=('black', b))] ] + sg.Window('Buttons with white and black text', keep_on_top=True).Layout(layout2).Read() \ No newline at end of file diff --git a/Demo_Columns.py b/Demo_Columns.py new file mode 100644 index 000000000..dd68aa865 --- /dev/null +++ b/Demo_Columns.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +sg.ChangeLookAndFeel('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 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'), + select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20, 3)), + sg.Column(col, background_color='blue')], + [sg.Input('Last input')], + [sg.OK()]] + +# Display the window and get values +button, values = sg.Window('Compact 1-line form with column').Layout(layout).Read() + +sg.Popup(button, values, line_width=200) + diff --git a/Demo_Compare_Files.py b/Demo_Compare_Files.py new file mode 100644 index 000000000..a6a8c289d --- /dev/null +++ b/Demo_Compare_Files.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +# sg.SetOptions(button_color=sg.COLOR_SYSTEM_DEFAULT) + +def GetFilesToCompare(): + form_rows = [[sg.Text('Enter 2 files to comare')], + [sg.Text('File 1', size=(15, 1)), sg.InputText(key='file1'), sg.FileBrowse()], + [sg.Text('File 2', size=(15, 1)), sg.InputText(key='file2'), sg.FileBrowse(target='file2')], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('File Compare') + button, values = window.Layout(form_rows).Read() + return button, values + +def main(): + button, values = GetFilesToCompare() + f1 = values['file1'] + f2 = values['file2'] + + if any((button != 'Submit', f1 =='', f2 == '')): + sg.PopupError('Operation cancelled') + sys.exit(69) + + # --- This portion of the code is not GUI related --- + with open(f1, 'rb') as file1: + with open(f2, 'rb') as file2: + a = file1.read() + b = file2.read() + + for i, x in enumerate(a): + if x != b[i]: + sg.Popup('Compare results for files', f1, f2, '**** Mismatch at offset {} ****'.format(i)) + break + else: + if len(a) == len(b): + sg.Popup('**** The files are IDENTICAL ****') + + +if __name__ == '__main__': + main() diff --git a/Demo_Cookbook_Browser.py b/Demo_Cookbook_Browser.py new file mode 100644 index 000000000..b346d5a0d --- /dev/null +++ b/Demo_Cookbook_Browser.py @@ -0,0 +1,793 @@ + + +# import PySimpleGUI as sg +import inspect + +def SimpleDataEntry(): + """Simple Data Entry - Return Values As List + Same GUI screen except the return values are in a list instead of a dictionary and doesn't have initial values. + """ + import PySimpleGUI as sg + # Very basic window. Return values as a list + window = sg.Window('Simple data entry form') # begin with a blank form + + layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText()], + [sg.Text('Address', size=(15, 1)), sg.InputText()], + [sg.Text('Phone', size=(15, 1)), sg.InputText()], + [sg.Submit(), sg.Cancel()] + ] + + button, values = window.LayoutAndRead(layout) + + print(button, values[0], values[1], values[2]) + +def SimpleReturnAsDict(): + """ + Simple data entry - Return Values As Dictionary + A simple form with default values. Results returned in a dictionary. Does not use a context manager + """ + import PySimpleGUI as sg + + # Very basic window. Return values as a dictionary + window = sg.Window('Simple data entry form') # begin with a blank form + + layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText('name', key='name')], + [sg.Text('Address', size=(15, 1)), sg.InputText('address', key='address')], + [sg.Text('Phone', size=(15, 1)), sg.InputText('phone', key='phone')], + [sg.Submit(), sg.Cancel()] + ] + + button, values = window.LayoutAndRead(layout) + + print(button, values['name'], values['address'], values['phone']) + +def FileBrowse(): + """ + Simple File Browse + Browse for a filename that is populated into the input field. + """ + import PySimpleGUI as sg + + with sg.Window('SHA-1 & 256 Hash') as form: + form_rows = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')], + [sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + (button, (source_filename,)) = window.LayoutAndRead(form_rows) + + print(button, source_filename) + +def GUIAddOn(): + """ + Add GUI to Front-End of Script + Quickly add a GUI allowing the user to browse for a filename if a filename is not supplied on the command line using this 1-line GUI. It's the best of both worlds. + """ + import PySimpleGUI as sg + import sys + + if len(sys.argv) == 1: + button, (fname,) = sg.Window('My Script').LayoutAndRead([[sg.T('Document to open')], + [sg.In(), sg.FileBrowse()], + [sg.Open(), sg.Cancel()]]) + else: + fname = sys.argv[1] + + if not fname: + sg.Popup("Cancel", "No filename supplied") + # raise SystemExit("Cancelling: no filename supplied") + +def Compare2Files(): + """ + Compare 2 Files + Browse to get 2 file names that can be then compared. Uses a context manager + """ + import PySimpleGUI as sg + + with sg.Window('File Compare') as form: + form_rows = [[sg.Text('Enter 2 files to comare')], + [sg.Text('File 1', size=(8, 1)), sg.InputText(), sg.FileBrowse()], + [sg.Text('File 2', size=(8, 1)), sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + + button, values = window.LayoutAndRead(form_rows) + + print(button, values) + +def AllWidgetsWithContext(): + """ + Nearly All Widgets with Green Color Theme with Context Manager + Example of nearly all of the widgets in a single window. Uses a customized color scheme. This recipe uses a context manager, the preferred method. + """ + import PySimpleGUI as sg + # Green & tan color scheme + sg.ChangeLookAndFeel('GreenTan') + + + # sg.ChangeLookAndFeel('GreenTan') + + with sg.Window('Everything bagel', default_element_size=(40, 1), grab_anywhere=False) as form: + + column1 = [[sg.Text('Column 1', background_color='#F7F3EC', 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'), initial_value='Spin Box 2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] + + layout = [ + [sg.Text('All graphic widgets in one form!', size=(30, 1), font=("Helvetica", 25))], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text')], + [sg.Checkbox('Checkbox'), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True), sg.Radio('My second Radio!', "RADIO1")], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), + sg.Multiline(default_text='A second multi-line', size=(35, 3))], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], + [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), + sg.Column(column1, background_color='#F7F3EC')], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder'), sg.FolderBrowse()], + [sg.Submit(), sg.Cancel()] + ] + + button, values = window.LayoutAndRead(layout) + +def AllWidgetsNoContext(): + """ + All Widgets No Context Manager + """ + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('GreenTan') + + window = sg.Window('Everything bagel', default_element_size=(40, 1), grab_anywhere=False) + + column1 = [[sg.Text('Column 1', background_color='#F7F3EC', 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'), initial_value='Spin Box 2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] + + layout = [ + [sg.Text('All graphic widgets in one form!', size=(30, 1), font=("Helvetica", 25))], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text')], + [sg.Checkbox('Checkbox'), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True), sg.Radio('My second Radio!', "RADIO1")], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), + sg.Multiline(default_text='A second multi-line', size=(35, 3))], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], + [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), + sg.Column(column1, background_color='#F7F3EC')], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder'), sg.FolderBrowse()], + [sg.Submit(), sg.Cancel()] + ] + + button, values = window.LayoutAndRead(layout) + +def NonBlockingWithUpdates(): + """ + Non-Blocking Form With Periodic Update + An async form that has a button read loop. A Text Element is updated periodically with a running timer. There is no context manager for this recipe because the loop that reads the form is likely to be some distance away from where the form was initialized. + """ + import PySimpleGUI as sg + import time + + window = sg.Window('Running Timer') + # create a text element that will be updated periodically + + form_rows = [[sg.Text('Stopwatch', size=(20,2), justification='center')], + [ sg.Text('', size=(10, 2), font=('Helvetica', 20), justification='center', key='output')], + [sg.T(' ' * 5), sg.ReadButton('Start/Stop', focus=True), sg.Quit()]] + + window.LayoutAndRead(form_rows, non_blocking=True) + + timer_running = True + i = 0 + # loop to process user clicks + while True: + i += 1 * (timer_running is True) + button, values = window.ReadNonBlocking() + if values is None or button == 'Quit': # if user closed the window using X or clicked Quit button + break + elif button == 'Start/Stop': + timer_running = not timer_running + window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100)) + + time.sleep(.01) + # if the loop finished then need to close the form for the user + window.CloseNonBlocking() + +def NonBlockingWithContext(): + """ + Async Form (Non-Blocking) with Context Manager + Like the previous recipe, this form is an async window. The difference is that this form uses a context manager. + """ + import PySimpleGUI as sg + import time + + with sg.Window('Running Timer') as form: + layout = [[sg.Text('Non blocking GUI with updates', justification='center')], + [sg.Text('', size=(10, 2), font=('Helvetica', 20), text_color='red', justification='center', key='output')], + [sg.T(' ' * 15), sg.Quit()]] + window.LayoutAndRead(layout, non_blocking=True) + + for i in range(1, 500): + window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100)) + button, values = window.ReadNonBlocking() + if values is None or button == 'Quit': # if user closed the window using X + break + time.sleep(.01) + else: + # if the loop finished then need to close the form for the user + window.CloseNonBlocking() + +def CallbackSimulation(): + """ + Callback Function Simulation + The architecture of some programs works better with button callbacks instead of handling in-line. While button callbacks are part of the PySimpleGUI implementation, they are not directly exposed to the caller. The way to get the same result as callbacks is to simulate them with a recipe like this one. + """ + import PySimpleGUI as sg + + # This design pattern simulates button callbacks + # Note that callbacks are NOT a part of the package's interface to the + # caller intentionally. The underlying implementation actually does use + # tkinter callbacks. They are simply hidden from the user. + + # The callback functions + def button1(): + print('Button 1 callback') + + def button2(): + print('Button 2 callback') + + # Create a standard form + window = sg.Window('Button callback example') + # Layout the design of the GUI + layout = [[sg.Text('Please click a button')], + [sg.ReadButton('1'), sg.ReadButton('2'), sg.Quit()]] + # Show the form to the user + window.Layout(layout) + + # Event loop. Read buttons, make callbacks + while True: + # Read the form + button, value = window.Read() + # Take appropriate action based on button + if button == '1': + button1() + elif button == '2': + button2() + elif button =='Quit' or button is None: + break + + # All done! + sg.PopupOk('Done') + +def RealtimeButtons(): + """ + Realtime Buttons (Good For Raspberry Pi) + This recipe implements a remote control interface for a robot. There are 4 directions, forward, reverse, left, right. When a button is clicked, PySimpleGUI immediately returns button events for as long as the buttons is held down. When released, the button events stop. This is an async/non-blocking window. + """ + import PySimpleGUI as sg + + # Make a form, but don't use context manager + window = sg.Window('Robotics Remote Control') + + form_rows = [[sg.Text('Robotics Remote Control')], + [sg.T(' ' * 10), sg.RealtimeButton('Forward')], + [sg.RealtimeButton('Left'), sg.T(' ' * 15), sg.RealtimeButton('Right')], + [sg.T(' ' * 10), sg.RealtimeButton('Reverse')], + [sg.T('')], + [sg.Quit(button_color=('black', 'orange'))] + ] + + window.LayoutAndRead(form_rows, non_blocking=True) + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your form every now and then or + # else it won't refresh. + # + # your program's main loop + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + if button is not None: + print(button) + if button is 'Quit' or values is None: + break + + window.CloseNonBlocking() + +def EasyProgressMeter(): + """ + Easy Progress Meter + This recipe shows just how easy it is to add a progress meter to your code. + """ + import PySimpleGUI as sg + + for i in range(1000): + sg.EasyProgressMeter('Easy Meter Example', i+1, 1000) + +def TabbedForm(): + """ + Tabbed Form + Tabbed forms are easy to make and use in PySimpleGUI. You simple may your layouts for each tab and then instead of LayoutAndRead you call ShowTabbedwindow. Results are returned as a list of form results. Each tab acts like a single window. + """ + import PySimpleGUI as sg + + with sg.Window('') as form: + with sg.Window('') as form2: + + layout_tab_1 = [[sg.Text('First tab', size=(20, 1), font=('helvetica', 15))], + [sg.InputText(), sg.Text('Enter some info')], + [sg.Submit(button_color=('red', 'yellow')), sg.Cancel(button_color=('white', 'blue'))]] + + layout_tab_2 = [[sg.Text('Second Tab', size=(20, 1), font=('helvetica', 15))], + [sg.InputText(), sg.Text('Enter some info')], + [sg.Submit(button_color=('red', 'yellow')), sg.Cancel(button_color=('white', 'blue'))]] + + results = sg.ShowTabbedForm('Tabbed form example', (form, layout_tab_1, 'First Tab'), + (form2, layout_tab_2,'Second Tab')) + + sg.Popup(results) + +def MediaPlayer(): + """ + Button Graphics (Media Player) + Buttons can have PNG of GIF images on them. This Media Player recipe requires 4 images in order to function correctly. The background is set to the same color as the button background so that they blend together. + """ + import PySimpleGUI as sg + + background = '#F0F0F0' + # Set the backgrounds the same as the background on the buttons + sg.SetOptions(background_color=background, element_background_color=background) + # Images are located in a subfolder in the Demo Media Player.py folder + image_pause = './ButtonGraphics/Pause.png' + image_restart = './ButtonGraphics/Restart.png' + image_next = './ButtonGraphics/Next.png' + image_exit = './ButtonGraphics/Exit.png' + + # Open a form, note that context manager can't be used generally speaking for async forms + window = sg.Window('Media File Player', default_element_size=(20, 1), + font=("Helvetica", 25)) + # define layout of the rows + layout = [[sg.Text('Media File Player', size=(17, 1), font=("Helvetica", 25))], + [sg.Text('', size=(15, 2), font=("Helvetica", 14), key='out')], + [sg.ReadButton('Restart Song', button_color=(background, background), + image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.ReadButton('Pause', button_color=(background, background), + image_filename=image_pause, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.ReadButton('Next', button_color=(background, background), + image_filename=image_next, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.Text(' ' * 2), sg.Button('Exit', button_color=(background, background), + image_filename=image_exit, image_size=(50, 50), image_subsample=2, + border_width=0)], + [sg.Text('_' * 20)], + [sg.Text(' ' * 30)], + [sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', + font=("Helvetica", 15)), + sg.Text(' ' * 2), + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', + font=("Helvetica", 15)), + sg.Text(' ' * 8), + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', + font=("Helvetica", 15))], + [sg.Text('Bass', font=("Helvetica", 15), size=(6, 1)), + sg.Text('Treble', font=("Helvetica", 15), size=(10, 1)), + sg.Text('Volume', font=("Helvetica", 15), size=(7, 1))] ] + + # Call the same LayoutAndRead but indicate the form is non-blocking + window.LayoutAndRead(layout, non_blocking=True) + # Our event loop + while (True): + # Read the form (this call will not block) + button, values = window.ReadNonBlocking() + if button == 'Exit' or values is None: + break + # If a button was pressed, display it on the GUI by updating the text element + if button: + window.FindElement('out').Update(button) + +def ScriptLauncher(): + """ + Script Launcher - Persistent Form + This form doesn't close after button clicks. To achieve this the buttons are specified as sg.ReadButton instead of sg.Button. The exception to this is the EXIT button. Clicking it will close the window. This program will run commands and display the output in the scrollable window. + """ + import PySimpleGUI as sg + import subprocess + + def Launcher(): + + window = sg.Window('Script launcher') + + layout = [ + [sg.Text('Script output....', size=(40, 1))], + [sg.Output(size=(88, 20))], + [sg.ReadButton('script1'), sg.ReadButton('script2'), sg.Button('EXIT')], + [sg.Text('Manual command', size=(15,1)), sg.InputText(focus=True), sg.ReadButton('Run', bind_return_key=True)] + ] + + window.Layout(layout) + + # ---===--- Loop taking in user input and using it to query HowDoI --- # + while True: + (button, value) = window.Read() + if button == 'EXIT' or button is None: + break # exit button clicked + if button == 'script1': + ExecuteCommandSubprocess('pip','list') + elif button == 'script2': + ExecuteCommandSubprocess('python', '--version') + elif button == 'Run': + ExecuteCommandSubprocess(value[0]) + + + def ExecuteCommandSubprocess(command, *args): + try: + expanded_args = [] + for a in args: + expanded_args += a + sp = subprocess.Popen([command,expanded_args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = sp.communicate() + if out: + print(out.decode("utf-8")) + if err: + print(err.decode("utf-8")) + except: pass + + Launcher() + +def MachineLearning(): + """ + Machine Learning GUI + A standard non-blocking GUI with lots of inputs. + """ + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('LightGreen') + + sg.SetOptions(text_justification='right') + + window = sg.Window('Machine Learning Front End', font=("Helvetica", 12)) # begin with a blank form + + layout = [[sg.Text('Machine Learning Command Line Parameters', font=('Helvetica', 16))], + [sg.Text('Passes', size=(15, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)), + sg.Text('Steps', size=(18, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1))], + [sg.Text('ooa', size=(15, 1)), sg.In(default_text='6', size=(10, 1)), sg.Text('nn', size=(15, 1)), sg.In(default_text='10', size=(10, 1))], + [sg.Text('q', size=(15, 1)), sg.In(default_text='ff', size=(10, 1)), sg.Text('ngram', size=(15, 1)), sg.In(default_text='5', size=(10, 1))], + [sg.Text('l', size=(15, 1)), sg.In(default_text='0.4', size=(10, 1)), sg.Text('Layers', size=(15, 1)), sg.Drop(values=('BatchNorm', 'other'),auto_size_text=True)], + [sg.Text('_' * 100, size=(65, 1))], + [sg.Text('Flags', font=('Helvetica', 15), justification='left')], + [sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1))], + [sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True)], + [sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1))], + [sg.Text('_' * 100, size=(65, 1))], + [sg.Text('Loss Functions', font=('Helvetica', 15), justification='left')], + [sg.Radio('Cross-Entropy', 'loss', size=(12, 1)), sg.Radio('Logistic', 'loss', default=True, size=(12, 1))], + [sg.Radio('Hinge', 'loss', size=(12, 1)), sg.Radio('Huber', 'loss', size=(12, 1))], + [sg.Radio('Kullerback', 'loss', size=(12, 1)), sg.Radio('MAE(L1)', 'loss', size=(12, 1))], + [sg.Radio('MSE(L2)', 'loss', size=(12, 1)), sg.Radio('MB(L0)', 'loss', size=(12, 1))], + [sg.Submit(), sg.Cancel()]] + + button, values = window.LayoutAndRead(layout) + +def CustromProgressMeter(): + """" + Custom Progress Meter / Progress Bar + Perhaps you don't want all the statistics that the EasyProgressMeter provides and want to create your own progress bar. Use this recipe to do just that. + """ + import PySimpleGUI as sg + + def CustomMeter(): + # create the progress bar element + progress_bar = sg.ProgressBar(10000, orientation='h', size=(20,20)) + # layout the form + layout = [[sg.Text('A custom progress meter')], + [progress_bar], + [sg.Cancel()]] + + # create the form + window = sg.Window('Custom Progress Meter') + # display the form as a non-blocking form + window.LayoutAndRead(layout, non_blocking=True) + # loop that would normally do something useful + for i in range(10000): + # check to see if the cancel button was clicked and exit loop if clicked + button, values = window.ReadNonBlocking() + if button == 'Cancel' or values == None: + break + # update bar with loop value +1 so that bar eventually reaches the maximum + progress_bar.UpdateBar(i+1) + # done with loop... need to destroy the window as it's still open + window.CloseNonBlocking() + + CustomMeter() + +def OneLineGUI(): + """ + The One-Line GUI + For those of you into super-compact code, a complete customized GUI can be specified, shown, and received the results using a single line of Python code. The way this is done is to combine the call to Window and the call to LayoutAndRead. Window returns a Window object which has the LayoutAndRead method. + """ + import PySimpleGUI as sg + + layout = [[sg.Text('Filename')], + [sg.Input(), sg.FileBrowse()], + [sg.OK(), sg.Cancel()] ] + + button, (number,) = sg.Window('Get filename example').LayoutAndRead(layout) + + """ + you can write this line of code for the exact same result (OK, two lines with the import): + """ + # import PySimpleGUI as sg + + button, (filename,) = sg.Window('Get filename example'). LayoutAndRead([[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ]) + +def MultipleColumns(): + """ + Multiple Columns + Starting in version 2.9 (not yet released but you can get from current GitHub) you can use the Column Element. A Column is required when you have a tall element to the left of smaller elements. + + This example uses a Column. There is a Listbox on the left that is 3 rows high. To the right of it are 3 single rows of text and input. These 3 rows are in a Column Element. + + To make it easier to see the Column in the window, the Column background has been shaded blue. The code is wordier than normal due to the blue shading. Each element in the column needs to have the color set to match blue background. + """ + import PySimpleGUI as sg + + # Demo of how columns work + # Form has on row 1 a vertical slider followed by a COLUMN with 7 rows + # Prior to the Column element, this layout was not possible + # Columns layouts look identical to form layouts, they are a list of lists of elements. + + # sg.ChangeLookAndFeel('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 3', text_color='white', background_color='blue'), sg.Input('col input 2')]] + + layout = [[sg.Listbox(values=('Listbox Item 1', 'Listbox Item 2', 'Listbox Item 3'), select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20,3)), sg.Column(col, background_color='blue')], + [sg.Input('Last input')], + [sg.OK()]] + + # Display the form and get values + # If you're willing to not use the "context manager" design pattern, then it's possible + # to collapse the form display and read down to a single line of code. + button, values = sg.Window('Compact 1-line form with column').LayoutAndRead(layout) + + sg.Popup(button, values, line_width=200) + +def PersistentForm(): + """ + Persistent Form With Text Element Updates + This simple program keep a form open, taking input values until the user terminates the program using the "X" button. + """ + import PySimpleGUI as sg + + window = sg.Window('Math') + + output = sg.Txt('', size=(8,1)) + + layout = [ [sg.Txt('Enter values to calculate')], + [sg.In(size=(8,1), key='numerator')], + [sg.Txt('_' * 10)], + [sg.In(size=(8,1), key='denominator')], + [output], + [sg.ReadButton('Calculate', bind_return_key=True)]] + + window.Layout(layout) + + while True: + button, values = window.Read() + + if button is not None: + try: + numerator = float(values['numerator']) + denominator = float(values['denominator']) + calc = numerator / denominator + except: + calc = 'Invalid' + + output.Update(calc) + else: + break + +def CanvasWidget(): + """ + tkinter Canvas Widget + The Canvas Element is one of the few tkinter objects that are directly accessible. The tkinter Canvas widget itself can be retrieved from a Canvas Element like this: + """ + + import PySimpleGUI as gui + + canvas = gui.Canvas(size=(100,100), background_color='red') + + layout = [ + [canvas], + [gui.T('Change circle color to:'), gui.ReadButton('Red'), gui.ReadButton('Blue')] + ] + + window = gui.Window('Canvas test', grab_anywhere=True) + window.Layout(layout) + window.ReadNonBlocking() + + cir = canvas.TKCanvas.create_oval(50, 50, 100, 100) + + while True: + button, values = window.Read() + if button is None: + break + if button is 'Blue': + canvas.TKCanvas.itemconfig(cir, fill = "Blue") + elif button is 'Red': + canvas.TKCanvas.itemconfig(cir, fill = "Red") + +def InputElementUpdate(): + """ + Input Element Update + This Recipe implements a Raspberry Pi touchscreen based keypad entry. As the digits are entered using the buttons, the Input Element above it is updated with the input digits. There are a number of features used in this Recipe including: Default Element Size auto_size_buttons ReadButton Dictionary Return values Update of Elements in form (Input, Text) do_not_clear of Input Elements + """ + import PySimpleGUI as g + + # Demonstrates a number of PySimpleGUI features including: + # Default element size + # auto_size_buttons + # ReadButton + # Dictionary return values + # Update of elements in form (Text, Input) + # do_not_clear of Input elements + + layout = [[g.Text('Enter Your Passcode')], + [g.Input(size=(10, 1), do_not_clear=True, key='input')], + [g.ReadButton('1'), g.ReadButton('2'), g.ReadButton('3')], + [g.ReadButton('4'), g.ReadButton('5'), g.ReadButton('6')], + [g.ReadButton('7'), g.ReadButton('8'), g.ReadButton('9')], + [g.ReadButton('Submit'), g.ReadButton('0'), g.ReadButton('Clear')], + [ g.Text('', size=(15, 1), font=('Helvetica', 18), text_color='red', key='output')], + ] + + window = g.Window('Keypad', default_element_size=(5, 2), auto_size_buttons=False) + window.Layout(layout) + + # Loop forever reading the form's values, updating the Input field + keys_entered = '' + while True: + button, values = window.Read() # read the form + if button is None: # if the X button clicked, just exit + break + if button is 'Clear': # clear keys if clear button + keys_entered = '' + elif button in '1234567890': + keys_entered = values['input'] # get what's been entered so far + keys_entered += button # add the new digit + elif button is 'Submit': + keys_entered = values['input'] + window.FindElement('output').Update(keys_entered) # output the final string + + window.FindElement('input').Update(keys_entered) # change the form to reflect current key string + + +def TableSimulation(): + """ + Display data in a table format + """ + import PySimpleGUI as sg + sg.ChangeLookAndFeel('Dark1') + + layout = [[sg.T('Table Test')]] + + for i in range(20): + layout.append([sg.T('{} {}'.format(i,j), size=(4, 1), background_color='black', pad=(1, 1)) for j in range(10)]) + + sg.Window('Table').LayoutAndRead(layout) + + +def TightLayout(): + """ + Turn off padding in order to get a really tight looking layout. + """ + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('Dark') + sg.SetOptions(element_padding=(0, 0)) + layout = [[sg.T('User:', pad=((3, 0), 0)), sg.OptionMenu(values=('User 1', 'User 2'), size=(20, 1)), + sg.T('0', size=(8, 1))], + [sg.T('Customer:', pad=((3, 0), 0)), sg.OptionMenu(values=('Customer 1', 'Customer 2'), size=(20, 1)), + sg.T('1', size=(8, 1))], + [sg.T('Notes:', pad=((3, 0), 0)), sg.In(size=(44, 1), background_color='white', text_color='black')], + [sg.ReadButton('Start', button_color=('white', 'black')), + sg.ReadButton('Stop', button_color=('white', 'black')), + sg.ReadButton('Reset', button_color=('white', '#9B0023')), + sg.ReadButton('Submit', button_color=('white', 'springgreen4')), + sg.Button('Exit', button_color=('white', '#00406B')), + ] + ] + + window = sg.Window("Time Tracker", default_element_size=(12, 1), text_justification='r', auto_size_text=False, + auto_size_buttons=False, no_titlebar=True, + default_button_element_size=(12, 1)) + window.Layout(layout) + while True: + button, values = window.Read() + if button is None or button == 'Exit': + return + +# -------------------------------- GUI Starts Here -------------------------------# +# fig = your figure you want to display. Assumption is that 'fig' holds the # +# information to display. # +# --------------------------------------------------------------------------------# + + +import PySimpleGUI as sg + +fig_dict = {'Simple Data Entry':SimpleDataEntry, 'Simple Entry Return Data as Dict':SimpleReturnAsDict, 'File Browse' : FileBrowse, + 'GUI Add On':GUIAddOn, 'Compare 2 Files':Compare2Files, 'All Widgets With Context Manager':AllWidgetsWithContext, 'All Widgets No Context Manager':AllWidgetsNoContext, + 'Non-Blocking With Updates':NonBlockingWithUpdates, 'Non-Bocking With Context Manager':NonBlockingWithContext, 'Callback Simulation':CallbackSimulation, + 'Realtime Buttons':RealtimeButtons, 'Easy Progress Meter':EasyProgressMeter, 'Tabbed Form':TabbedForm, 'Media Player':MediaPlayer, 'Script Launcher':ScriptLauncher, + 'Machine Learning':MachineLearning, 'Custom Progress Meter':CustromProgressMeter, 'One Line GUI':OneLineGUI, 'Multiple Columns':MultipleColumns, + 'Persistent Form':PersistentForm, 'Canvas Widget':CanvasWidget, 'Input Element Update':InputElementUpdate, + 'Table Simulation':TableSimulation, 'Tight Layout':TightLayout} + + +# define the form layout +listbox_values = [key for key in fig_dict.keys()] + +while True: + sg.ChangeLookAndFeel('Dark') + # sg.SetOptions(element_padding=(0,0)) + + col_listbox = [[sg.Listbox(values=listbox_values, size=(max(len(x) for x in listbox_values),min(len(listbox_values), 20)), change_submits=False, key='func')], + [sg.ReadButton('Run', pad=(0,0)), sg.ReadButton('Show Code', button_color=('white', 'gray25'), pad=(0,0)), sg.Exit(button_color=('white', 'firebrick4'), pad=(0,0))]] + + layout = [[sg.Text('PySimpleGUI Coookbook', font=('current 18'))], + [sg.Column(col_listbox), sg.Multiline(size=(50,min(len(listbox_values), 20)), do_not_clear=True, key='multi')], + ] + +# create the form and show it without the plot +# window.Layout(layout) + + window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', default_button_element_size=(9,1),auto_size_buttons=False, grab_anywhere=False) + window.Layout(layout) + # show it all again and get buttons + while True: + button, values = window.Read() + + if button is None or button == 'Exit': + exit(69) + try: + choice = values['func'][0] + func = fig_dict[choice] + except: + continue + + if button == 'Show Code' and values['multi']: + window.FindElement('multi').Update(inspect.getsource(func)) + elif button is 'Run' and values['func']: + # sg.ChangeLookAndFeel('SystemDefault') + window.CloseNonBlocking() + func() + break + else: + print('ILLEGAL values') + break + diff --git a/Demo_DOC_Viewer_PIL.py b/Demo_DOC_Viewer_PIL.py new file mode 100644 index 000000000..0287cc902 --- /dev/null +++ b/Demo_DOC_Viewer_PIL.py @@ -0,0 +1,242 @@ +""" +@created: 2018-08-19 18:00:00 +@author: (c) 2018 Jorj X. McKie +Display a PyMuPDF Document using Tkinter +------------------------------------------------------------------------------- +Dependencies: +------------- +PyMuPDF, PySimpleGUI (requires Python 3), Tkinter, PIL +License: +-------- +GNU GPL V3+ +Description +------------ +Get filename and start displaying page 1. Please note that all file types +of MuPDF are supported (including EPUB e-books and HTML files for example). +Pages can be directly jumped to, or buttons can be used for paging. + +This version contains enhancements: +* Use of PIL improves response times by a factor 3 or more. +* Zooming is now flexible: only one button serves as a toggle. Arrow keys can + be used for moving the window when zooming. + +We also interpret keyboard events (PageDown / PageUp) and mouse wheel actions +to support paging as if a button was clicked. Similarly, we do not include +a 'Quit' button. Instead, the ESCAPE key can be used, or cancelling the window. +To improve paging performance, we are not directly creating pixmaps from +pages, but instead from the fitz.DisplayList of the page. A display list +will be stored in a list and looked up by page number. This way, zooming +pixmaps and page re-visits will re-use a once-created display list. + +""" +import sys +import fitz +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import tkinter as tk +from PIL import Image, ImageTk +import time + +if len(sys.argv) == 1: + fname = sg.PopupGetFile('Document Browser', 'Document file to open', no_window=True, + file_types = ( + ("PDF Files", "*.pdf"), + ("XPS Files", "*.*xps"), + ("Epub Files", "*.epub"), + ("Fiction Books", "*.fb2"), + ("Comic Books", "*.cbz"), + ("HTML", "*.htm*") + # add more document types here + ) + ) +else: + fname = sys.argv[1] + +if not fname: + sg.Popup("Cancelling:", "No filename supplied") + raise SystemExit("Cancelled: no filename supplied") + +doc = fitz.open(fname) +page_count = len(doc) + +# used for response time statistics only +fitz_img_time = 0.0 +tk_img_time = 0.0 +img_count = 1 + +# allocate storage for page display lists +dlist_tab = [None] * page_count + +title = "PyMuPDF display of '%s', pages: %i" % (fname, page_count) + +def get_page(pno, zoom = False, max_size = None, first = False): + """Return a PNG image for a document page number. + """ + dlist = dlist_tab[pno] # get display list of page number + if not dlist: # create if not yet there + dlist_tab[pno] = doc[pno].getDisplayList() + dlist = dlist_tab[pno] + r = dlist.rect # the page rectangle + clip = r + # ensure image fits screen: + # exploit, but do not exceed width or height + zoom_0 = 1 + if max_size: + zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height) + if zoom_0 == 1: + zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height) + mat_0 = fitz.Matrix(zoom_0, zoom_0) + + if not zoom: # show total page + pix = dlist.getPixmap(matrix = mat_0, alpha=False) + else: + mp = r.tl + (r.br - r.tl) * 0.5 # page rect center + w2 = r.width / 2 + h2 = r.height / 2 + clip = r * 0.5 + tl = zoom[0] # old top-left + tl.x += zoom[1] * (w2 / 2) + tl.x = max(0, tl.x) + tl.x = min(w2, tl.x) + tl.y += zoom[2] * (h2 / 2) + tl.y = max(0, tl.y) + tl.y = min(h2, tl.y) + clip = fitz.Rect(tl, tl.x + w2, tl.y + h2) + + mat = mat_0 * fitz.Matrix(2, 2) # zoom matrix + pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip) + + if first: # first call: tkinter still inactive + img = pix.getPNGData() # so use fitz png output + else: # else take tk photo image + pilimg = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) + img = ImageTk.PhotoImage(pilimg) + + return img, clip.tl # return image, clip position + + +root = tk.Tk() +max_width = root.winfo_screenwidth() - 20 +max_height = root.winfo_screenheight() - 135 +max_size = (max_width, max_height) +root.destroy() +del root + +window = sg.Window(title, return_keyboard_events = True, + location = (0,0), use_default_focus = False, no_titlebar=False) + +cur_page = 0 +data, clip_pos = get_page(cur_page, + zoom = False, + max_size = max_size, + first = True) + +image_elem = sg.Image(data = data) + +goto = sg.InputText(str(cur_page + 1), size=(5, 1), do_not_clear=True, + key = "PageNumber") + +layout = [ + [ + sg.ReadButton('Next'), + sg.ReadButton('Prev'), + sg.Text('Page:'), + goto, + sg.Text('(%i)' % page_count), + sg.ReadButton('Zoom'), + sg.Text('(toggle on/off, use arrows to navigate while zooming)'), + ], + [image_elem], +] + +window.Layout(layout) + +# now define the buttons / events we want to handle +enter_buttons = [chr(13), "Return:13"] +quit_buttons = ["Escape:27", chr(27)] +next_buttons = ["Next", "Next:34", "MouseWheel:Down"] +prev_buttons = ["Prev", "Prior:33", "MouseWheel:Up"] +Up = "Up:38" +Left = "Left:37" +Right = "Right:39" +Down = "Down:40" +zoom_buttons = ["Zoom", Up, Down, Left, Right] + +# all the buttons we will handle +my_keys = enter_buttons + next_buttons + prev_buttons + zoom_buttons + +# old page store and zoom toggle +old_page = 0 +old_zoom = False + +while True: + button, value = window.Read() + if button is None and (value is None or value['PageNumber'] is None): + break + if button in quit_buttons: + break + + zoom_pressed = False + zoom = False + + if button in enter_buttons: + try: + cur_page = int(value['PageNumber']) - 1 # check if valid + while cur_page < 0: + cur_page += page_count + except: + cur_page = 0 # this guy's trying to fool me + + elif button in next_buttons: + cur_page += 1 + elif button in prev_buttons: + cur_page -= 1 + elif button == Up: + zoom = (clip_pos, 0, -1) + elif button == Down: + zoom = (clip_pos, 0, 1) + elif button == Left: + zoom = (clip_pos, -1, 0) + elif button == Right: + zoom = (clip_pos, 1, 0) + elif button == "Zoom": + zoom_pressed = True + zoom = (clip_pos, 0, 0) + + # sanitize page number + if cur_page >= page_count: # wrap around + cur_page = 0 + while cur_page < 0: # pages > 0 look nicer + cur_page += page_count + + if zoom_pressed and old_zoom: + zoom = zoom_pressed = old_zoom = False + + t0 = time.perf_counter() + data, clip_pos = get_page(cur_page, zoom = zoom, max_size = max_size, + first = False) + t1 = time.perf_counter() + image_elem.Update(data = data) + t2 = time.perf_counter() + fitz_img_time += t1 - t0 + tk_img_time += t2 - t1 + img_count += 1 + old_page = cur_page + old_zoom = zoom_pressed or zoom + + # update page number field + if button in my_keys: + goto.Update(str(cur_page + 1)) + + +# print some response time statistics +if img_count > 0: + print("response times for '%s'" % doc.name) + print("%.4f" % (fitz_img_time/img_count), "sec fitz avg. image time") + print("%.4f" % (tk_img_time/img_count), "sec tk avg. image time") + print("%.4f" % ((fitz_img_time + tk_img_time)/img_count), "sec avg. total time") + print(img_count, "images read") + print(page_count, "pages") diff --git a/Demo_Design_Patterns.py b/Demo_Design_Patterns.py new file mode 100644 index 000000000..aa56ddf08 --- /dev/null +++ b/Demo_Design_Patterns.py @@ -0,0 +1,58 @@ +""" +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 window that closes when a "submit" type button is clicked +2. A persistent window that stays open after button clicks (uses an event loop) +3. A persistent window that needs access to the elements' interface variables +""" +# ---------------------------------# +# DESIGN PATTERN 1 - Simple Window # +# ---------------------------------# +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[ sg.Text('My layout') ]] + +window = sg.Window('My window').Layout(layout) +button, value = window.Read() + + +# -------------------------------------# +# DESIGN PATTERN 2 - Persistent Window # +# -------------------------------------# +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[ sg.Text('My layout') ]] + +window = sg.Window('My new window').Layout(layout) + +while True: # Event Loop + button, value = window.Read() + if button is None: + break + +# ------------------------------------------------------------------# +# DESIGN PATTERN 3 - Persistent Window with "early update" required # +# ------------------------------------------------------------------# +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[ sg.Text('My layout') ]] + +window = sg.Window('My new window').Layout(layout).Finalize() + +while True: # Event Loop + button, value = window.Read() + if button is None: + break \ No newline at end of file diff --git a/Demo_Desktop_Floating_Toolbar.py b/Demo_Desktop_Floating_Toolbar.py new file mode 100644 index 000000000..c50d8a901 --- /dev/null +++ b/Demo_Desktop_Floating_Toolbar.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +import subprocess +import os + + +""" + Demo_Toolbar - A floating toolbar with quick launcher + + One cool PySimpleGUI demo. Shows borderless windows, grab_anywhere, tight button layout + You can setup a specific program to launch when a button is clicked, or use the + Combobox to select a .py file found in the root folder, and run that file. + +""" + +ROOT_PATH = './' + +def Launcher(): + + # def print(line): + # window.FindElement('output').Update(line) + + sg.ChangeLookAndFeel('Dark') + + namesonly = [f for f in os.listdir(ROOT_PATH) if f.endswith('.py') ] + + sg.SetOptions(element_padding=(0,0), button_element_size=(12,1), auto_size_buttons=False) + + layout = [[sg.Combo(values=namesonly, size=(35,30), key='demofile'), + sg.ReadButton('Run', button_color=('white', '#00168B')), + sg.ReadButton('Program 1'), + sg.ReadButton('Program 2'), + sg.ReadButton('Program 3', button_color=('white', '#35008B')), + sg.Button('EXIT', button_color=('white','firebrick3'))], + [sg.T('', text_color='white', size=(50,1), key='output')]] + + window = sg.Window('Floating Toolbar', no_titlebar=True, keep_on_top=True).Layout(layout) + + + # ---===--- Loop taking in user input and executing appropriate program --- # + while True: + (button, value) = window.Read() + if button is 'EXIT' or button is None: + break # exit button clicked + if button is 'Program 1': + print('Run your program 1 here!') + elif button is 'Program 2': + print('Run your program 2 here!') + elif button is 'Run': + file = value['demofile'] + print('Launching %s'%file) + ExecuteCommandSubprocess('python', os.path.join(ROOT_PATH, file)) + else: + print(button) + +def ExecuteCommandSubprocess(command, *args, wait=False): + try: + if sys.platform == 'linux': + arg_string = '' + arg_string = ' '.join([str(arg) for arg in args]) + # for arg in args: + # arg_string += ' ' + str(arg) + print('python3 ' + arg_string) + sp = subprocess.Popen(['python3 ', arg_string ], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + else: + arg_string = ' '.join([str(arg) for arg in args]) + sp = subprocess.Popen([command, arg_string], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + # sp = subprocess.Popen([command, list(args)], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + if wait: + out, err = sp.communicate() + if out: + print(out.decode("utf-8")) + if err: + print(err.decode("utf-8")) + except: pass + + + +if __name__ == '__main__': + Launcher() + diff --git a/Demo_Desktop_Widget_CPU_Graph.py b/Demo_Desktop_Widget_CPU_Graph.py new file mode 100644 index 000000000..9f2f8984f --- /dev/null +++ b/Demo_Desktop_Widget_CPU_Graph.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +import sys +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import time +import random +import psutil +from threading import Thread + + +STEP_SIZE=3 +SAMPLES = 300 +SAMPLE_MAX = 500 +CANVAS_SIZE = (300,200) + + +g_interval = .25 +g_cpu_percent = 0 +g_procs = None +g_exit = False + +def CPU_thread(args): + global g_interval, g_cpu_percent, g_procs, g_exit + + while not g_exit: + try: + g_cpu_percent = psutil.cpu_percent(interval=g_interval) + g_procs = psutil.process_iter() + except: + pass + +def main(): + global g_exit, g_response_time + # start ping measurement thread + + sg.ChangeLookAndFeel('Black') + sg.SetOptions(element_padding=(0,0)) + + layout = [ [sg.Quit( button_color=('white','black')), sg.T('', pad=((100,0),0), font='Any 15', key='output')], + [sg.Graph(CANVAS_SIZE, (0,0), (SAMPLES,SAMPLE_MAX),background_color='black', key='graph')],] + + window = sg.Window('CPU Graph', grab_anywhere=True, keep_on_top=True, background_color='black', no_titlebar=True, use_default_focus=False).Layout(layout) + + graph = window.FindElement('graph') + output = window.FindElement('output') + # start cpu measurement thread + thread = Thread(target=CPU_thread,args=(None,)) + thread.start() + + last_cpu = i = 0 + prev_x, prev_y = 0, 0 + while True: # the Event Loop + time.sleep(.5) + button, values = window.ReadNonBlocking() + if button == 'Quit' or values is None: # always give ths user a way out + break + # do CPU measurement and graph it + current_cpu = int(g_cpu_percent*10) + if current_cpu == last_cpu: + continue + output.Update(current_cpu/10) # show current cpu usage at top + if current_cpu > SAMPLE_MAX: + current_cpu = SAMPLE_MAX + new_x, new_y = i, current_cpu + if i >= SAMPLES: + graph.Move(-STEP_SIZE,0) # shift graph over if full of data + prev_x = prev_x - STEP_SIZE + graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white') + prev_x, prev_y = new_x, new_y + i += STEP_SIZE if i < SAMPLES else 0 + last_cpu = current_cpu + +if __name__ == '__main__': + main() diff --git a/Demo_Desktop_Widget_CPU_Utilization.py b/Demo_Desktop_Widget_CPU_Utilization.py new file mode 100644 index 000000000..af970e62b --- /dev/null +++ b/Demo_Desktop_Widget_CPU_Utilization.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +import sys +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import psutil +import time +from threading import Thread +import operator + + +""" + PSUTIL Desktop Widget + Creates a floating CPU utilization window that is always on top of other windows + You move it by grabbing anywhere on the window + Good example of how to do a non-blocking, polling program using PySimpleGUI + Use the spinner to adjust the number of seconds between readings of the CPU utilizaiton + + NOTE - you will get a warning message printed when you exit using exit button. + It will look something like: + invalid command name "1616802625480StopMove" +""" + +# globale used to communicate with thread.. yea yea... it's working fine +g_interval = 1 +g_cpu_percent = 0 +g_procs = None +g_exit = False + +def CPU_thread(args): + global g_interval, g_cpu_percent, g_procs, g_exit + + while not g_exit: + try: + g_cpu_percent = psutil.cpu_percent(interval=g_interval) + g_procs = psutil.process_iter() + except: + pass + + +def main(): + global g_interval, g_procs, g_exit + + # ---------------- Create Form ---------------- + sg.ChangeLookAndFeel('Black') + layout = [[sg.Text('', size=(8,1), font=('Helvetica', 20),text_color=sg.YELLOWS[0], justification='center', key='text')], + [sg.Text('', size=(30, 8), font=('Courier New', 12),text_color='white', justification='left', key='processes')], + [sg.Exit(button_color=('white', 'firebrick4'), pad=((15,0), 0)), sg.Spin([x+1 for x in range(10)], 1, key='spin')],] + + window = sg.Window('CPU Utilization', no_titlebar=True, auto_size_buttons=False, + keep_on_top=True, grab_anywhere=True).Layout(layout) + + # start cpu measurement thread + thread = Thread(target=CPU_thread,args=(None,)) + thread.start() + # ---------------- main loop ---------------- + while (True): + # --------- Read and update window -------- + button, values = window.ReadNonBlocking() + + # --------- Do Button Operations -------- + if values is None or button == 'Exit': + break + try: + g_interval = int(values['spin']) + except: + g_interval = 1 + + # cpu_percent = psutil.cpu_percent(interval=interval) # if don't wan to use a task + cpu_percent = g_cpu_percent + + # let the GUI run ever 700ms regardless of CPU polling time. makes window be more responsive + time.sleep(.7) + + display_string = '' + if g_procs: + # --------- Create list of top % CPU porocesses -------- + try: + top = {proc.name() : proc.cpu_percent() for proc in g_procs} + except: pass + + + top_sorted = sorted(top.items(), key=operator.itemgetter(1), reverse=True) + if top_sorted: + top_sorted.pop(0) + display_string = '' + for proc, cpu in top_sorted: + display_string += '{:2.2f} {}\n'.format(cpu/10, proc) + + + # --------- Display timer in window -------- + window.FindElement('text').Update('CPU {}'.format(cpu_percent)) + window.FindElement('processes').Update(display_string) + + # Broke out of main loop. Close the window. + window.CloseNonBlocking() + g_exit = True + thread.join() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Demo_Desktop_Widget_CPU_Utilization_Simple.py b/Demo_Desktop_Widget_CPU_Utilization_Simple.py new file mode 100644 index 000000000..afb5efd48 --- /dev/null +++ b/Demo_Desktop_Widget_CPU_Utilization_Simple.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +import sys +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +import psutil + +# ---------------- Create Form ---------------- +sg.ChangeLookAndFeel('Black') +layout = [[sg.Text('')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='text')], + [sg.Exit(button_color=('white', 'firebrick4'), pad=((15, 0), 0)), + sg.Spin([x + 1 for x in range(10)], 1, key='spin')]] +# Layout the rows of the form and perform a read. Indicate the form is non-blocking! +window = sg.Window('CPU Meter', no_titlebar=True, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout) + +# ---------------- main loop ---------------- +while (True): + # --------- Read and update window -------- + button, values = window.ReadNonBlocking() + + # --------- Do Button Operations -------- + if values is None or button == 'Exit': + break + try: + interval = int(values['spin']) + except: + interval = 1 + + cpu_percent = psutil.cpu_percent(interval=interval) + + # --------- Display timer in window -------- + + window.FindElement('text').Update(f'CPU {cpu_percent:02.0f}%') + +# Broke out of main loop. Close the window. +window.CloseNonBlocking() \ No newline at end of file diff --git a/Demo_Desktop_Widget_Timer.py b/Demo_Desktop_Widget_Timer.py new file mode 100644 index 000000000..5d15f079f --- /dev/null +++ b/Demo_Desktop_Widget_Timer.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +import sys +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import time + +""" + Timer Desktop Widget Creates a floating timer that is always on top of other windows You move it by grabbing anywhere on the window Good example of how to do a non-blocking, polling program using PySimpleGUI Can be used to poll hardware when running on a Pi NOTE - you will get a warning message printed when you exit using exit button. + It will look something like: invalid command name \"1616802625480StopMove\" +""" + + +# ---------------- Create Form ---------------- +sg.ChangeLookAndFeel('Black') +sg.SetOptions(element_padding=(0, 0)) + +layout = [[sg.Text('')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='text')], + [sg.ReadButton('Pause', key='button', button_color=('white', '#001480')), + sg.ReadButton('Reset', button_color=('white', '#007339'), key='Reset'), + sg.Exit(button_color=('white', 'firebrick4'), key='Exit')]] + +window = sg.Window('Running Timer', no_titlebar=False, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout) + +# ---------------- main loop ---------------- +current_time = 0 +paused = False +start_time = int(round(time.time() * 100)) +while (True): + # --------- Read and update window -------- + if not paused: + button, values = window.ReadNonBlocking() + current_time = int(round(time.time() * 100)) - start_time + else: + button, values = window.Read() + if button == 'button': + button = window.FindElement(button).GetText() + # --------- Do Button Operations -------- + if values is None or button == 'Exit': + break + if button is 'Reset': + start_time = int(round(time.time() * 100)) + current_time = 0 + paused_time = start_time + elif button == 'Pause': + paused = True + paused_time = int(round(time.time() * 100)) + element = window.FindElement('button') + element.Update(text='Run') + elif button == 'Run': + paused = False + start_time = start_time + int(round(time.time() * 100)) - paused_time + element = window.FindElement('button') + element.Update(text='Pause') + + # --------- Display timer in window -------- + window.FindElement('text').Update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60, + (current_time // 100) % 60, + current_time % 100)) + time.sleep(.01) + +# --------- After loop -------- + +# Broke out of main loop. Close the window. +window.CloseNonBlocking() diff --git a/Demo_Disable_Elements.py b/Demo_Disable_Elements.py new file mode 100644 index 000000000..d927d5a1c --- /dev/null +++ b/Demo_Disable_Elements.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +import sys +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +sg.ChangeLookAndFeel('Dark') +sg.SetOptions(element_padding=(0, 0)) + +layout = [ + [sg.T('Notes:', pad=((3, 0), 0)), sg.In(size=(44, 1), background_color='white', text_color='black', key='notes')], + [sg.T('Output:', pad=((3, 0), 0)), sg.T('', size=(44, 1), text_color='white', key='output')], + [sg.CBox('Checkbox:', default=True, pad=((3, 0), 0), key='cbox'), sg.Listbox((1,2,3,4),size=(8,3),key='listbox'), + sg.Radio('Radio 1', default=True, group_id='1', key='radio1'), sg.Radio('Radio 2', default=False, group_id='1', key='radio2')], + [sg.Spin((1,2,3,4),1, key='spin'), sg.OptionMenu((1,2,3,4), key='option'), sg.Combo(values=(1,2,3,4),key='combo')], + [sg.Multiline('Multiline', size=(20,3), key='multi')], + [sg.Slider((1,10), size=(20,20), orientation='h', key='slider')], + [sg.ReadButton('Enable', button_color=('white', 'black')), + sg.ReadButton('Disable', button_color=('white', 'black')), + sg.ReadButton('Reset', button_color=('white', '#9B0023'), key='reset'), + sg.ReadButton('Values', button_color=('white', 'springgreen4')), + sg.Button('Exit', button_color=('white', '#00406B'))]] + +window = sg.Window("Disable Elements Demo", default_element_size=(12, 1), text_justification='r', auto_size_text=False, + auto_size_buttons=False, keep_on_top=True, grab_anywhere=False, + default_button_element_size=(12, 1)).Layout(layout).Finalize() + +key_list = 'cbox', 'listbox', 'radio1', 'radio2', 'spin', 'option', 'combo', 'reset', 'notes', 'multi', 'slider' + +for key in key_list: window.FindElement(key).Update(disabled=True) # don't do this kind of for-loop + +while True: + button, values = window.Read() + if button is None or button == 'Exit': + break + elif button == 'Disable': + for key in key_list: window.FindElement(key).Update(disabled=True) + elif button == 'Enable': + for key in key_list: window.FindElement(key).Update(disabled=False) + elif button == 'Values': + sg.Popup(values, keep_on_top=True) + + + diff --git a/Demo_DuplicateFileFinder.py b/Demo_DuplicateFileFinder.py new file mode 100644 index 000000000..eebe5ee10 --- /dev/null +++ b/Demo_DuplicateFileFinder.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +import sys +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import hashlib +import os + + +# ====____====____==== FUNCTION DeDuplicate_folder(path) ====____====____==== # +# Function to de-duplicate the folder passed in # +# --------------------------------------------------------------------------- # +def FindDuplicatesFilesInFolder(path): + shatab = [] + total = 0 + small_count, dup_count, error_count = 0,0,0 + pngdir = path + if not os.path.exists(path): + sg.Popup('Duplicate Finder', '** Folder doesn\'t exist***', path) + return + pngfiles = os.listdir(pngdir) + total_files = len(pngfiles) + for idx, f in enumerate(pngfiles): + if not sg.OneLineProgressMeter('Counting Duplicates', idx + 1, total_files, 'Counting Duplicate Files'): + break + total += 1 + fname = os.path.join(pngdir, f) + if os.path.isdir(fname): + continue + x = open(fname, "rb").read() + + m = hashlib.sha256() + m.update(x) + f_sha = m.digest() + if f_sha in shatab: + # uncomment next line to remove duplicate files + # os.remove(fname) + dup_count += 1 + # sg.Print(f'Duplicate file - {f}') # cannot current use sg.Print with Progress Meter + continue + shatab.append(f_sha) + + msg = '{} Files processed\n {} Duplicates found'.format(total_files, dup_count) + sg.Popup('Duplicate Finder Ended', msg) + +# ====____====____==== Pseudo-MAIN program ====____====____==== # +# This is our main-alike piece of code # +# + Starts up the GUI # +# + Gets values from GUI # +# + Runs DeDupe_folder based on GUI inputs # +# ------------------------------------------------------------- # +if __name__ == '__main__': + + source_folder = None + rc, source_folder = sg.PopupGetFolder('Duplicate Finder - Count number of duplicate files', 'Enter path to folder you wish to find duplicates in') + if rc is True and source_folder is not None: + FindDuplicatesFilesInFolder(source_folder) + else: + sg.PopupCancel('Cancelling', '*** Cancelling ***') + exit(0) diff --git a/Demo_Fill_Form.py b/Demo_Fill_Form.py new file mode 100644 index 000000000..cbfed70e0 --- /dev/null +++ b/Demo_Fill_Form.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +import sys +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +def Everything(): + sg.ChangeLookAndFeel('TanBlue') + + column1 = [ + [sg.Text('Column 1', background_color=sg.DEFAULT_BACKGROUND_COLOR, justification='center', size=(10, 1))], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 1', key='spin1')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 2', key='spin2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3', key='spin3')]] + + layout = [ + [sg.Text('All graphic widgets in one form!', size=(30, 1), font=("Helvetica", 25))], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text', key='in1', do_not_clear=True)], + [sg.Checkbox('Checkbox', key='cb1'), sg.Checkbox('My second checkbox!', key='cb2', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", key='rad1', default=True), + sg.Radio('My second Radio!', "RADIO1", key='rad2')], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3), + key='multi1', do_not_clear=True), + sg.Multiline(default_text='A second multi-line', size=(35, 3), key='multi2', do_not_clear=True)], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), key='combo', size=(20, 1)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), key='slide1', default_value=85)], + [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'), key='optionmenu')], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3), key='listbox'), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25, key='slide2', ), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75, key='slide3', ), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10, key='slide4'), + sg.Column(column1, background_color='gray34')], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder', key='folder', do_not_clear=True), sg.FolderBrowse()], + [sg.ReadButton('Exit'), + sg.Text(' ' * 40), sg.ReadButton('SaveSettings'), sg.ReadButton('LoadSettings')] + ] + + window = sg.Window('Form Fill Demonstration', default_element_size=(40, 1), grab_anywhere=False) + # button, values = window.LayoutAndRead(layout, non_blocking=True) + window.Layout(layout) + + while True: + button, values = window.Read() + + if button is 'SaveSettings': + filename = sg.PopupGetFile('Save Settings', save_as=True, no_window=True) + window.SaveToDisk(filename) + # save(values) + elif button is 'LoadSettings': + filename = sg.PopupGetFile('Load Settings', no_window=True) + window.LoadFromDisk(filename) + # load(form) + elif button in ['Exit', None]: + break + + # window.CloseNonBlocking() + + +if __name__ == '__main__': + Everything() diff --git a/Demo_Floating_Toolbar.py b/Demo_Floating_Toolbar.py new file mode 100644 index 000000000..5b17d327d --- /dev/null +++ b/Demo_Floating_Toolbar.py @@ -0,0 +1,77 @@ +import PySimpleGUI as sg +import subprocess +import os +import sys + +""" + Demo_Toolbar - A floating toolbar with quick launcher + + One cool PySimpleGUI demo. Shows borderless windows, grab_anywhere, tight button layout + You can setup a specific program to launch when a button is clicked, or use the + Combobox to select a .py file found in the root folder, and run that file. + +""" + +ROOT_PATH = './' + +def Launcher(): + + def print(line): + form.FindElement('output').Update(line) + + sg.ChangeLookAndFeel('Dark') + + namesonly = [f for f in os.listdir(ROOT_PATH) if f.endswith('.py') ] + + sg.SetOptions(element_padding=(0,0), button_element_size=(12,1), auto_size_buttons=False) + layout = [[sg.Combo(values=namesonly, size=(35,30), key='demofile'), + sg.ReadFormButton('Run', button_color=('white', '#00168B')), + sg.ReadFormButton('Program 1'), + sg.ReadFormButton('Program 2'), + sg.ReadFormButton('Program 3', button_color=('white', '#35008B')), + sg.SimpleButton('EXIT', button_color=('white','firebrick3'))], + [sg.T('', text_color='white', size=(50,1), key='output')]] + + form = sg.FlexForm('Floating Toolbar', no_titlebar=True, keep_on_top=True) + + form.Layout(layout) + + # ---===--- Loop taking in user input and using it to query HowDoI --- # + while True: + (button, value) = form.Read() + if button is 'EXIT' or button is None: + break # exit button clicked + if button is 'Program 1': + print('Run your program 1 here!') + elif button is 'Program 2': + print('Run your program 2 here!') + elif button is 'Run': + file = value['demofile'] + print('Launching %s'%file) + ExecuteCommandSubprocess('python', os.path.join(ROOT_PATH, file)) + else: + print(button) + +def ExecuteCommandSubprocess(command, *args, wait=False): + try: + if sys.platform == 'linux': + arg_string = '' + for arg in args: + arg_string += ' ' + str(arg) + sp = subprocess.Popen(['python3' + arg_string, ], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + else: + sp = subprocess.Popen([command, list(args)], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + if wait: + out, err = sp.communicate() + if out: + print(out.decode("utf-8")) + if err: + print(err.decode("utf-8")) + except: pass + + + +if __name__ == '__main__': + Launcher() + diff --git a/Demo_Font_Sizer.py b/Demo_Font_Sizer.py new file mode 100644 index 000000000..56983819c --- /dev/null +++ b/Demo_Font_Sizer.py @@ -0,0 +1,30 @@ + +# Testing async form, see if can have a slider +# that adjusts the size of text displayed +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +fontSize = 12 +layout = [[sg.Spin([sz for sz in range(6, 172)], font=('Helvetica 20'), initial_value=fontSize, change_submits=True, key='spin'), + sg.Slider(range=(6,172), orientation='h', size=(10,20), change_submits=True, key='slider', font=('Helvetica 20')), sg.Text("Aa", size=(2, 1), font="Helvetica " + str(fontSize), key='text')]] +sz = fontSize +window = sg.Window("Font size selector", grab_anywhere=False) +window.Layout(layout) +while True: + button, values= window.Read() + if button is None or button == 'Quit': + break + sz_spin = int(values['spin']) + sz_slider = int(values['slider']) + sz = sz_spin if sz_spin != fontSize else sz_slider + if sz != fontSize: + fontSize = sz + font = "Helvetica " + str(fontSize) + window.FindElement('text').Update(font=font) + window.FindElement('slider').Update(sz) + window.FindElement('spin').Update(sz) + +print("Done.") diff --git a/Demo_Func_Callback_Simulation.py b/Demo_Func_Callback_Simulation.py new file mode 100644 index 000000000..a6bf00959 --- /dev/null +++ b/Demo_Func_Callback_Simulation.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[sg.Text('Filename', )], + [sg.Input(), sg.FileBrowse()], + [sg.OK(), sg.Cancel()]] + +button, (number,) = sg.Window('Get filename example').LayoutAndRead(layout) + + + +import PySimpleGUI as sg + +button, (filename,) = sg.Window('Get filename example').LayoutAndRead( + [[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()]]) \ No newline at end of file diff --git a/Demo_GoodColors.py b/Demo_GoodColors.py new file mode 100644 index 000000000..8ec0fee77 --- /dev/null +++ b/Demo_GoodColors.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +def main(): + # ------- Make a new Window ------- # + window = sg.Window('GoodColors', auto_size_text=True, default_element_size=(30,2)) + window.AddRow(sg.Text('Having trouble picking good colors? Try one of the colors defined by PySimpleGUI')) + window.AddRow(sg.Text('Here come the good colors as defined by PySimpleGUI')) + + #===== Show some nice BLUE colors with yellow text ===== ===== ===== ===== ===== ===== =====# + text_color = sg.YELLOWS[0] + buttons = (sg.Button('BLUES[{}]\n{}'.format(j, c), button_color=(text_color, c), size=(10,2)) for j, c in enumerate(sg.BLUES)) + window.AddRow(sg.T('Button Colors Using PySimpleGUI.BLUES')) + window.AddRow(*buttons) + window.AddRow(sg.Text('_' * 100, size=(65, 1))) + + #===== Show some nice PURPLE colors with yellow text ===== ===== ===== ===== ===== ===== =====# + buttons = (sg.Button('PURPLES[{}]\n{}'.format(j, c), button_color=(text_color, c), size=(10,2)) for j, c in enumerate(sg.PURPLES)) + window.AddRow(sg.T('Button Colors Using PySimpleGUI.PURPLES')) + window.AddRow(*buttons) + window.AddRow(sg.Text('_' * 100, size=(65, 1))) + + #===== Show some nice GREEN colors with yellow text ===== ===== ===== ===== ===== ===== =====# + buttons = (sg.Button('GREENS[{}]\n{}'.format(j, c), button_color=(text_color, c), size=(10,2)) for j, c in enumerate(sg.GREENS)) + window.AddRow(sg.T('Button Colors Using PySimpleGUI.GREENS')) + window.AddRow(*buttons) + window.AddRow(sg.Text('_' * 100, size=(65, 1))) + + #===== Show some nice TAN colors with yellow text ===== ===== ===== ===== ===== ===== =====# + text_color = sg.GREENS[0] # let's use GREEN text on the tan + buttons = (sg.Button('TANS[{}]\n{}'.format(j, c), button_color=(text_color, c), size=(10,2)) for j, c in enumerate(sg.TANS)) + window.AddRow(sg.T('Button Colors Using PySimpleGUI.TANS')) + window.AddRow(*buttons) + window.AddRow(sg.Text('_' * 100, size=(65, 1))) + + #===== Show some nice YELLOWS colors with black text ===== ===== ===== ===== ===== ===== =====# + text_color = 'black' # let's use black text on the tan + buttons = (sg.Button('YELLOWS[{}]\n{}'.format(j, c), button_color=(text_color, c), size=(10,2)) for j, c in enumerate(sg.YELLOWS)) + window.AddRow(sg.T('Button Colors Using PySimpleGUI.YELLOWS')) + window.AddRow(*buttons) + window.AddRow(sg.Text('_' * 100, size=(65, 1))) + + + #===== Add a click me button for fun and SHOW the window ===== ===== ===== ===== ===== ===== =====# + window.AddRow(sg.Button('Click ME!')) + (button, value) = window.Show() # show it! + + +if __name__ == '__main__': + main() diff --git a/Demo_Graph_Drawing.py b/Demo_Graph_Drawing.py new file mode 100644 index 000000000..193da1197 --- /dev/null +++ b/Demo_Graph_Drawing.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[sg.Graph(canvas_size=(400, 400), graph_bottom_left=(0,0), graph_top_right=(400, 400), background_color='red', key='graph')], + [sg.T('Change circle color to:'), sg.ReadButton('Red'), sg.ReadButton('Blue'), sg.ReadButton('Move')]] + +window = sg.Window('Graph test').Layout(layout).Finalize() + +graph = window.FindElement('graph') +circle = graph.DrawCircle((75,75), 25, fill_color='black',line_color='white') +point = graph.DrawPoint((75,75), 10, color='green') +oval = graph.DrawOval((25,300), (100,280), fill_color='purple', line_color='purple' ) +rectangle = graph.DrawRectangle((25,300), (100,280), line_color='purple' ) +line = graph.DrawLine((0,0), (100,100)) + +while True: + button, values = window.Read() + if button is None: + break + if button is 'Blue': + graph.TKCanvas.itemconfig(circle, fill = "Blue") + elif button is 'Red': + graph.TKCanvas.itemconfig(circle, fill = "Red") + elif button is 'Move': + graph.MoveFigure(point, 10,10) + graph.MoveFigure(circle, 10,10) + graph.MoveFigure(oval, 10,10) + graph.MoveFigure(rectangle, 10,10) diff --git a/Demo_Graph_Element.py b/Demo_Graph_Element.py new file mode 100644 index 000000000..e683f2791 --- /dev/null +++ b/Demo_Graph_Element.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +import ping +from threading import Thread +import time + + +STEP_SIZE=1 +SAMPLES = 1000 +CANVAS_SIZE = (1000,500) + +# globale used to communicate with thread.. yea yea... it's working fine +g_exit = False +g_response_time = None +def ping_thread(args): + global g_exit, g_response_time + while not g_exit: + g_response_time = ping.quiet_ping('google.com', timeout=1000) + +def main(): + global g_exit, g_response_time + + # start ping measurement thread + thread = Thread(target=ping_thread, args=(None,)) + thread.start() + + sg.ChangeLookAndFeel('Black') + sg.SetOptions(element_padding=(0,0)) + + layout = [ [sg.T('Ping times to Google.com', font='Any 12'), sg.Quit(pad=((100,0), 0), button_color=('white', 'black'))], + [sg.Graph(CANVAS_SIZE, (0,0), (SAMPLES,500),background_color='black', key='graph')],] + + window = sg.Window('Canvas test', grab_anywhere=True, background_color='black', no_titlebar=False, use_default_focus=False).Layout(layout) + + graph = window.FindElement('graph') + + prev_response_time = None + i=0 + prev_x, prev_y = 0, 0 + while True: + time.sleep(.2) + + button, values = window.ReadNonBlocking() + if button == 'Quit' or values is None: + break + if g_response_time is None or prev_response_time == g_response_time: + continue + new_x, new_y = i, g_response_time[0] + prev_response_time = g_response_time + if i >= SAMPLES: + graph.Move(-STEP_SIZE,0) + prev_x = prev_x - STEP_SIZE + graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white') + # window.FindElement('graph').DrawPoint((new_x, new_y), color='red') + prev_x, prev_y = new_x, new_y + i += STEP_SIZE if i < SAMPLES else 0 + + # tell thread we're done. wait for thread to exit + g_exit = True + thread.join() + + +if __name__ == '__main__': + main() diff --git a/Demo_Graph_Element_Sine_Wave.py b/Demo_Graph_Element_Sine_Wave.py new file mode 100644 index 000000000..997d804b1 --- /dev/null +++ b/Demo_Graph_Element_Sine_Wave.py @@ -0,0 +1,40 @@ +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import math + +layout = [[sg.T('Example of Using Math with a Graph', justification='center', + size=(50,1), relief=sg.RELIEF_SUNKEN)], + [sg.Graph(canvas_size=(400, 400), + graph_bottom_left=(-105,-105), + graph_top_right=(105,105), + background_color='white', + key='graph')],] + +window = sg.Window('Graph of Sine Function', grab_anywhere=True).Layout(layout).Finalize() + +graph = window.FindElement('graph') + +# Draw axis +graph.DrawLine((-100,0), (100,0)) +graph.DrawLine((0,-100), (0,100)) + +for x in range(-100, 101, 20): + graph.DrawLine((x,-3), (x,3)) + if x != 0: + graph.DrawText( x, (x,-10), color='green') + +for y in range(-100, 101, 20): + graph.DrawLine((-3,y), (3,y)) + if y != 0: + graph.DrawText( y, (-10,y), color='blue') + + +# Draw Graph +for x in range(-100,100): + y = math.sin(x/20)*50 + graph.DrawCircle((x,y), 1, line_color='red', fill_color='red') + +button, values = window.Read() diff --git a/Demo_Graph_Noise.py b/Demo_Graph_Noise.py new file mode 100644 index 000000000..8af8cf158 --- /dev/null +++ b/Demo_Graph_Noise.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +import random +import sys + +STEP_SIZE=1 +SAMPLES = 300 +SAMPLE_MAX = 300 +CANVAS_SIZE = (300,300) + + +def main(): + global g_exit, g_response_time + + layout = [[sg.T('Enter width, height of graph')], + [sg.In(size=(6, 1)), sg.In(size=(6, 1))], + [sg.Ok(), sg.Cancel()]] + + window = sg.Window('Enter graph size').Layout(layout) + b,v = window.Read() + if b is None or b == 'Cancel': + sys.exit(69) + w, h = int(v[0]), int(v[1]) + CANVAS_SIZE = (w,h) + + # start ping measurement thread + + sg.ChangeLookAndFeel('Black') + sg.SetOptions(element_padding=(0,0)) + + layout = [ [sg.Quit( button_color=('white','black'))], + [sg.Graph(CANVAS_SIZE, (0,0), (SAMPLES,SAMPLE_MAX),background_color='black', key='graph')],] + + window = sg.Window('Canvas test', grab_anywhere=True, background_color='black', no_titlebar=False, use_default_focus=False).Layout(layout).Finalize() + graph = window.FindElement('graph') + + prev_response_time = None + i=0 + prev_x, prev_y = 0, 0 + graph_value = 250 + while True: + # time.sleep(.2) + button, values = window.ReadNonBlocking() + print(button, values) + if button == 'Quit' or values is None: + break + graph_offset = random.randint(-10, 10) + graph_value = graph_value + graph_offset + if graph_value > SAMPLE_MAX: + graph_value = SAMPLE_MAX + if graph_value < 0: + graph_value = 0 + new_x, new_y = i, graph_value + prev_value = graph_value + if i >= SAMPLES: + graph.Move(-STEP_SIZE,0) + prev_x = prev_x - STEP_SIZE + graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white') + # window.FindElement('graph').DrawPoint((new_x, new_y), color='red') + prev_x, prev_y = new_x, new_y + i += STEP_SIZE if i < SAMPLES else 0 + + + +if __name__ == '__main__': + main() diff --git a/Demo_Graph__Element.py b/Demo_Graph__Element.py new file mode 100644 index 000000000..174ce1fb2 --- /dev/null +++ b/Demo_Graph__Element.py @@ -0,0 +1,66 @@ +import ping +from threading import Thread +import time +import PySimpleGUI as sg + + +STEP_SIZE=1 +SAMPLES = 6000 +CANVAS_SIZE = (6000,500) + +# globale used to communicate with thread.. yea yea... it's working fine +g_exit = False +g_response_time = None +def ping_thread(args): + global g_exit, g_response_time + while not g_exit: + g_response_time = ping.quiet_ping('google.com', timeout=1000) + +def main(): + global g_exit, g_response_time + + # start ping measurement thread + thread = Thread(target=ping_thread, args=(None,)) + thread.start() + + sg.ChangeLookAndFeel('Black') + sg.SetOptions(element_padding=(0,0)) + + layout = [ [sg.T('Ping times to Google.com', font='Any 12'), sg.Quit(pad=((100,0), 0), button_color=('white', 'black'))], + [sg.Graph(CANVAS_SIZE, (0,0), (SAMPLES,500),background_color='black', key='graph')],] + + form = sg.FlexForm('Canvas test', grab_anywhere=True, background_color='black', no_titlebar=False, use_default_focus=False) + form.Layout(layout) + + form.Finalize() + graph = form.FindElement('graph') + + prev_response_time = None + i=0 + prev_x, prev_y = 0, 0 + while True: + time.sleep(.2) + + button, values = form.ReadNonBlocking() + if button == 'Quit' or values is None: + break + if g_response_time is None or prev_response_time == g_response_time: + continue + new_x, new_y = i, g_response_time[0] + prev_response_time = g_response_time + if i >= SAMPLES: + graph.Move(-STEP_SIZE,0) + prev_x = prev_x - STEP_SIZE + graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white') + # form.FindElement('graph').DrawPoint((new_x, new_y), color='red') + prev_x, prev_y = new_x, new_y + i += STEP_SIZE if i < SAMPLES else 0 + + # tell thread we're done. wait for thread to exit + g_exit = True + thread.join() + + +if __name__ == '__main__': + main() + exit(69) \ No newline at end of file diff --git a/Demo_HowDoI.py b/Demo_HowDoI.py new file mode 100644 index 000000000..e05db15bd --- /dev/null +++ b/Demo_HowDoI.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import subprocess + + +# Test this command in a dos window if you are having trouble. +HOW_DO_I_COMMAND = 'python -m howdoi.howdoi' + +# if you want an icon on your taskbar for this gui, then change this line of code to point to the ICO file +DEFAULT_ICON = 'E:\\TheRealMyDocs\\Icons\\QuestionMark.ico' + +def HowDoI(): + ''' + Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle + Excellent example of 2 GUI concepts + 1. Output Element that will show text in a scrolled window + 2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form + :return: never returns + ''' + # ------- Make a new Window ------- # + sg.ChangeLookAndFeel('GreenTan') # give our form a spiffy set of colors + + layout = [ + [sg.Text('Ask and your answer will appear here....', size=(40, 1))], + [sg.Output(size=(127, 30), font=('Helvetica 10'))], + [ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'), + sg.Text('Num Answers',font='Helvetica 15'), sg.Checkbox('Display Full Text', key='full text', font='Helvetica 15'), + sg.T('Command History', font='Helvetica 15'), sg.T('', size=(40,3), text_color=sg.BLUES[0], key='history')], + [sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False), + sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True), + sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))] + ] + + window = sg.Window('How Do I ??', default_element_size=(30, 2), icon=DEFAULT_ICON, font=('Helvetica',' 13'), default_button_element_size=(8,2), return_keyboard_events=True, no_titlebar=True, grab_anywhere=True) + window.Layout(layout) + # ---===--- Loop taking in user input and using it to query HowDoI --- # + command_history = [] + history_offset = 0 + while True: + (button, value) = window.Read() + if button is 'SEND': + query = value['query'].rstrip() + print(query) + QueryHowDoI(query, value['Num Answers'], value['full text']) # send the string to HowDoI + command_history.append(query) + history_offset = len(command_history)-1 + window.FindElement('query').Update('') # manually clear input because keyboard events blocks clear + window.FindElement('history').Update('\n'.join(command_history[-3:])) + elif button is None or button is 'EXIT': # if exit button or closed using X + break + elif 'Up' in button and len(command_history): # scroll back in history + command = command_history[history_offset] + history_offset -= 1 * (history_offset > 0) # decrement is not zero + window.FindElement('query').Update(command) + elif 'Down' in button and len(command_history): # scroll forward in history + history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list + command = command_history[history_offset] + window.FindElement('query').Update(command) + elif 'Escape' in button: # clear currently line + window.FindElement('query').Update('') + + +def QueryHowDoI(Query, num_answers, full_text): + ''' + Kicks off a subprocess to send the 'Query' to HowDoI + Prints the result, which in this program will route to a gooeyGUI window + :param Query: text english question to ask the HowDoI web engine + :return: nothing + ''' + howdoi_command = HOW_DO_I_COMMAND + full_text_option = ' -a' if full_text else '' + t = subprocess.Popen(howdoi_command + ' \"'+ Query + '\" -n ' + str(num_answers)+full_text_option, stdout=subprocess.PIPE) + (output, err) = t.communicate() + print('{:^88}'.format(Query.rstrip())) + print('_'*60) + print(output.decode("utf-8") ) + exit_code = t.wait() + +if __name__ == '__main__': + HowDoI() + diff --git a/Demo_Img_Viewer.py b/Demo_Img_Viewer.py new file mode 100644 index 000000000..0f279ff68 --- /dev/null +++ b/Demo_Img_Viewer.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import os +from PIL import Image, ImageTk +import io +""" +Simple Image Browser based on PySimpleGUI +-------------------------------------------- +There are some improvements compared to the PNG browser of the repository: +1. Paging is cyclic, i.e. automatically wraps around if file index is outside +2. Supports all file types that are valid PIL images +3. Limits the maximum form size to the physical screen +4. When selecting an image from the listbox, subsequent paging uses its index +5. Paging performance improved significantly because of using PIL + +Dependecies +------------ +Python v3 +PIL +""" +# Get the folder containing the images from the user +rc, folder = sg.GetPathBox('Image Browser', 'Image folder to open', default_path='') +if not rc or not folder: + sg.PopupCancel('Cancelling') + raise SystemExit() + +# PIL supported image types +img_types = (".png", ".jpg", "jpeg", ".tiff", ".bmp") + +# get list of files in folder +flist0 = os.listdir(folder) + +# create sub list of image files (no sub folders, no wrong file types) +fnames = [f for f in flist0 if os.path.isfile(os.path.join(folder,f)) and f.lower().endswith(img_types)] + +num_files = len(fnames) # number of iamges found +if num_files == 0: + sg.Popup('No files in folder') + raise SystemExit() + +del flist0 # no longer needed + +#------------------------------------------------------------------------------ +# use PIL to read data of one image +#------------------------------------------------------------------------------ +def get_img_data(f, maxsize = (1200, 850), first = False): + """Generate image data using PIL + """ + img = Image.open(f) + img.thumbnail(maxsize) + if first: # tkinter is inactive the first time + bio = io.BytesIO() + img.save(bio, format = "PNG") + del img + return bio.getvalue() + return ImageTk.PhotoImage(img) +#------------------------------------------------------------------------------ + + +# create the form that also returns keyboard events +window = sg.Window('Image Browser', return_keyboard_events=True, + location=(0, 0), use_default_focus=False) + +# make these 2 elements outside the layout as we want to "update" them later +# initialize to the first file in the list +filename = os.path.join(folder, fnames[0]) # name of first file in list +image_elem = sg.Image(data = get_img_data(filename, first = True)) +filename_display_elem = sg.Text(filename, size=(80, 3)) +file_num_display_elem = sg.Text('File 1 of {}'.format(num_files), size=(15,1)) + +# define layout, show and read the form +col = [[filename_display_elem], + [image_elem]] + +col_files = [[sg.Listbox(values = fnames, change_submits=True, size=(60, 30), key='listbox')], + [sg.ReadButton('Next', size=(8,2)), sg.ReadButton('Prev', + size=(8,2)), file_num_display_elem]] + +layout = [[sg.Column(col_files), sg.Column(col)]] + +window.Layout(layout) # Shows form on screen + +# loop reading the user input and displaying image, filename +i=0 +while True: + # read the form + button, values = window.Read() + + # perform button and keyboard operations + if button is None: + break + elif button in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34'): + i += 1 + if i >= num_files: + i -= num_files + filename = os.path.join(folder, fnames[i]) + elif button in ('Prev', 'MouseWheel:Up', 'Up:38', 'Prior:33'): + i -= 1 + if i < 0: + i = num_files + i + filename = os.path.join(folder, fnames[i]) + elif button in ('Read', ''): # something from the listbox + f = values["listbox"][0] # selected filename + filename = os.path.join(folder, f) # read this file + i = fnames.index(f) # update running index + else: + filename = os.path.join(folder, fnames[i]) + + # update window with new image + image_elem.Update(data=get_img_data(filename)) + # update window with filename + filename_display_elem.Update(filename) + # update page display + file_num_display_elem.Update('File {} of {}'.format(i+1, num_files)) + + diff --git a/Demo_Keyboard.py b/Demo_Keyboard.py new file mode 100644 index 000000000..115106042 --- /dev/null +++ b/Demo_Keyboard.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +# Recipe for getting keys, one at a time as they are released +# If want to use the space bar, then be sure and disable the "default focus" + +layout = [[sg.Text("Press a key or scroll mouse")], + [sg.Text("", size=(18,1), key='text')], + [sg.Button("OK", key='OK')]] + +window = sg.Window("Keyboard Test", return_keyboard_events=True, use_default_focus=False).Layout(layout) + +# ---===--- Loop taking in user input --- # +while True: + button, value = window.Read() + text_elem = window.FindElement('text') + if button in ("OK", None): + print(button, "exiting") + break + if len(button) == 1: + text_elem.Update(value='%s - %s' % (button, ord(button))) + if button is not None: + text_elem.Update(button) + + diff --git a/Demo_Keyboard_Realtime.py b/Demo_Keyboard_Realtime.py new file mode 100644 index 000000000..460d79d18 --- /dev/null +++ b/Demo_Keyboard_Realtime.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[sg.Text("Hold down a key")], + [sg.Button("OK")]] + +window = sg.Window("Realtime Keyboard Test", return_keyboard_events=True, use_default_focus=False).Layout(layout) + +while True: + button, value = window.ReadNonBlocking() + + if button == "OK": + print(button, value, "exiting") + break + if button is not None: + if len(button) == 1: + print('%s - %s'%(button, ord(button))) + else: + print(button) + elif value is None: + break diff --git a/Demo_Keypad.py b/Demo_Keypad.py new file mode 100644 index 000000000..a66685c4e --- /dev/null +++ b/Demo_Keypad.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +# Demonstrates a number of PySimpleGUI features including: +# Default element size +# auto_size_buttons +# ReadButton +# Dictionary return values +# Update of elements in form (Text, Input) +# do_not_clear of Input elements + + + +layout = [[sg.Text('Enter Your Passcode')], + [sg.Input(size=(10, 1), do_not_clear=True, key='input')], + [sg.ReadButton('1'), sg.ReadButton('2'), sg.ReadButton('3')], + [sg.ReadButton('4'), sg.ReadButton('5'), sg.ReadButton('6')], + [sg.ReadButton('7'), sg.ReadButton('8'), sg.ReadButton('9')], + [sg.ReadButton('Submit'), sg.ReadButton('0'), sg.ReadButton('Clear')], + [sg.Text('', size=(15, 1), font=('Helvetica', 18), text_color='red', key='out')], + ] + +window = sg.Window('Keypad', default_button_element_size=(5, 2), auto_size_buttons=False, grab_anywhere=False).Layout(layout) + +# Loop forever reading the form's values, updating the Input field +keys_entered = '' +while True: + button, values = window.Read() # read the form + if button is None: # if the X button clicked, just exit + break + if button == 'Clear': # clear keys if clear button + keys_entered = '' + elif button in '1234567890': + keys_entere=d = values['input'] # get what's been entered so far + keys_entered += button # add the new digit + elif button == 'Submit': + keys_entered = values['input'] + window.FindElement('out').Update(keys_entered) # output the final string + + window.FindElement('input').Update(keys_entered) # change the form to reflect current key string \ No newline at end of file diff --git a/Demo_MIDI_Player.py b/Demo_MIDI_Player.py new file mode 100644 index 000000000..fa4ea87ce --- /dev/null +++ b/Demo_MIDI_Player.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import os +import mido +import time +import sys + +PLAYER_COMMAND_NONE = 0 +PLAYER_COMMAND_EXIT = 1 +PLAYER_COMMAND_PAUSE = 2 +PLAYER_COMMAND_NEXT = 3 +PLAYER_COMMAND_RESTART_SONG = 4 + +# ---------------------------------------------------------------------- # +# PlayerGUI CLASS # +# ---------------------------------------------------------------------- # +class PlayerGUI(): + ''' + Class implementing GUI for both initial screen but the player itself + ''' + + def __init__(self): + self.Window = None + self.TextElem = None + self.PortList = mido.get_output_names() # use to get the list of midi ports + self.PortList = self.PortList[::-1] # reverse the list so the last one is first + + # ---------------------------------------------------------------------- # + # PlayerChooseSongGUI # + # Show a GUI get to the file to playback # + # ---------------------------------------------------------------------- # + def PlayerChooseSongGUI(self): + + # ---------------------- DEFINION OF CHOOSE WHAT TO PLAY GUI ---------------------------- + + layout = [[sg.Text('MIDI File Player', font=("Helvetica", 15), size=(20, 1), text_color='green')], + [sg.Text('File Selection', font=("Helvetica", 15), size=(20, 1))], + [sg.Text('Single File Playback', justification='right'), sg.InputText(size=(65, 1), key='midifile'), sg.FileBrowse(size=(10, 1), file_types=(("MIDI files", "*.mid"),))], + [sg.Text('Or Batch Play From This Folder', auto_size_text=False, justification='right'), sg.InputText(size=(65, 1), key='folder'), sg.FolderBrowse(size=(10, 1))], + [sg.Text('_' * 250, auto_size_text=False, size=(100, 1))], + [sg.Text('Choose MIDI Output Device', size=(22, 1)), + sg.Listbox(values=self.PortList, size=(30, len(self.PortList) + 1), key='device')], + [sg.Text('_' * 250, auto_size_text=False, size=(100, 1))], + [sg.SimpleButton('PLAY', size=(12, 2), button_color=('red', 'white'), font=("Helvetica", 15), bind_return_key=True), sg.Text(' ' * 2, size=(4, 1)), sg.Cancel(size=(8, 2), font=("Helvetica", 15))]] + + window = sg.Window('MIDI File Player', auto_size_text=False, default_element_size=(30, 1), font=("Helvetica", 12)).Layout(layout) + self.Window = window + return window.Read() + + + def PlayerPlaybackGUIStart(self, NumFiles=1): + # ------- Make a new FlexForm ------- # + + image_pause = './ButtonGraphics/Pause.png' + image_restart = './ButtonGraphics/Restart.png' + image_next = './ButtonGraphics/Next.png' + image_exit = './ButtonGraphics/Exit.png' + + self.TextElem = sg.T('Song loading....', size=(70, 5 + NumFiles), font=("Helvetica", 14), auto_size_text=False) + self.SliderElem = sg.Slider(range=(1, 100), size=(50, 8), orientation='h', text_color='#f0f0f0') + layout = [ + [sg.T('MIDI File Player', size=(30, 1), font=("Helvetica", 25))], + [self.TextElem], + [self.SliderElem], + [sg.ReadFormButton('PAUSE', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_pause, image_size=(50,50), image_subsample=2, border_width=0), sg.T(' '), + sg.ReadFormButton('NEXT', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_next, image_size=(50,50), image_subsample=2, border_width=0), sg.T(' '), + sg.ReadFormButton('Restart Song', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_restart, image_size=(50,50), image_subsample=2, border_width=0), sg.T(' '), + sg.SimpleButton('EXIT', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_exit, image_size=(50,50), image_subsample=2, border_width=0, )] + ] + + window = sg.FlexForm('MIDI File Player', default_element_size=(30, 1), font=("Helvetica", 25)).Layout(layout).Finalize() + self.Window = window + + + + # ------------------------------------------------------------------------- # + # PlayerPlaybackGUIUpdate # + # Refresh the GUI for the main playback interface (must call periodically # + # ------------------------------------------------------------------------- # + def PlayerPlaybackGUIUpdate(self, DisplayString): + window = self.Window + if 'window' not in locals() or window is None: # if the form has been destoyed don't mess with it + return PLAYER_COMMAND_EXIT + self.TextElem.Update(DisplayString) + button, (values) = window.ReadNonBlocking() + if values is None: + return PLAYER_COMMAND_EXIT + if button == 'PAUSE': + return PLAYER_COMMAND_PAUSE + elif button == 'EXIT': + return PLAYER_COMMAND_EXIT + elif button == 'NEXT': + return PLAYER_COMMAND_NEXT + elif button == 'Restart Song': + return PLAYER_COMMAND_RESTART_SONG + return PLAYER_COMMAND_NONE + + +# ---------------------------------------------------------------------- # +# MAIN - our main program... this is it # +# Runs the GUI to get the file / path to play # +# Decodes the MIDI-Video into a MID file # +# Plays the decoded MIDI file # +# ---------------------------------------------------------------------- # +def main(): + def GetCurrentTime(): + ''' + Get the current system time in milliseconds + :return: milliseconds + ''' + return int(round(time.time() * 1000)) + + + pback = PlayerGUI() + + button, values = pback.PlayerChooseSongGUI() + if button != 'PLAY': + sg.PopupCancel('Cancelled...\nAutoclose in 2 sec...', auto_close=True, auto_close_duration=2) + sys.exit(69) + if values['device']: + midi_port = values['device'][0] + else: + sg.PopupCancel('No devices found\nAutoclose in 2 sec...', auto_close=True, auto_close_duration=2) + + batch_folder = values['folder'] + midi_filename = values['midifile'] + # ------ Build list of files to play --------------------------------------------------------- # + if batch_folder: + filelist = os.listdir(batch_folder) + filelist = [batch_folder+'/'+f for f in filelist if f.endswith(('.mid', '.MID'))] + filetitles = [os.path.basename(f) for f in filelist] + elif midi_filename: # an individual filename + filelist = [midi_filename,] + filetitles = [os.path.basename(midi_filename),] + else: + sg.PopupError('*** Error - No MIDI files specified ***') + sys.exit(666) + + # ------ LOOP THROUGH MULTIPLE FILES --------------------------------------------------------- # + pback.PlayerPlaybackGUIStart(NumFiles=len(filelist) if len(filelist) <=10 else 10) + port = None + # Loop through the files in the filelist + for now_playing_number, current_midi_filename in enumerate(filelist): + display_string = 'Playing Local File...\n{} of {}\n{}'.format(now_playing_number+1, len(filelist), current_midi_filename) + midi_title = filetitles[now_playing_number] + # --------------------------------- REFRESH THE GUI ----------------------------------------- # + pback.PlayerPlaybackGUIUpdate(display_string) + + # ---===--- Output Filename is .MID --- # + midi_filename = current_midi_filename + + # --------------------------------- MIDI - STARTS HERE ----------------------------------------- # + if not port: # if the midi output port not opened yet, then open it + port = mido.open_output(midi_port if midi_port else None) + + try: + mid = mido.MidiFile(filename=midi_filename) + except: + print('****** Exception trying to play MidiFile filename = {}***************'.format(midi_filename)) + sg.PopupError('Exception trying to play MIDI file:', midi_filename, 'Skipping file') + continue + + # Build list of data contained in MIDI File using only track 0 + midi_length_in_seconds = mid.length + display_file_list = '>> ' + '\n'.join([f for i, f in enumerate(filetitles[now_playing_number:]) if i < 10]) + paused = cancelled = next_file = False + ######################### Loop through MIDI Messages ########################### + while(True): + start_playback_time = GetCurrentTime() + port.reset() + + for midi_msg_number, msg in enumerate(mid.play()): + #################### GUI - read values ################## + if not midi_msg_number % 4: # update the GUI every 4 MIDI messages + t = (GetCurrentTime() - start_playback_time)//1000 + display_midi_len = '{:02d}:{:02d}'.format(*divmod(int(midi_length_in_seconds),60)) + display_string = 'Now Playing {} of {}\n{}\n {:02d}:{:02d} of {}\nPlaylist:'.\ + format(now_playing_number+1, len(filelist), midi_title, *divmod(t, 60), display_midi_len) + # display list of next 10 files to be played. + pback.SliderElem.Update(t, range=(1,midi_length_in_seconds)) + rc = pback.PlayerPlaybackGUIUpdate(display_string + '\n' + display_file_list) + else: # fake rest of code as if GUI did nothing + rc = PLAYER_COMMAND_NONE + if paused: + rc = PLAYER_COMMAND_NONE + while rc == PLAYER_COMMAND_NONE: # TIGHT-ASS loop waiting on a GUI command + rc = pback.PlayerPlaybackGUIUpdate(display_string) + time.sleep(.25) + + ####################################### MIDI send data ################################## + port.send(msg) + + # ------- Execute GUI Commands after sending MIDI data ------- # + if rc == PLAYER_COMMAND_EXIT: + cancelled = True + break + elif rc == PLAYER_COMMAND_PAUSE: + paused = not paused + port.reset() + elif rc == PLAYER_COMMAND_NEXT: + next_file = True + break + elif rc == PLAYER_COMMAND_RESTART_SONG: + break + + if cancelled or next_file: + break + #------- DONE playing the song ------- # + port.reset() # reset the midi port when done with the song + + if cancelled: + break + +# ---------------------------------------------------------------------- # +# LAUNCH POINT -- program starts and ends here # +# ---------------------------------------------------------------------- # +if __name__ == '__main__': + main() + diff --git a/Demo_Machine_Learning.py b/Demo_Machine_Learning.py new file mode 100644 index 000000000..42b1caa62 --- /dev/null +++ b/Demo_Machine_Learning.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +def MachineLearningGUI(): + sg.SetOptions(text_justification='right') + + flags = [[sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1))], + [sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True)], + [sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1))], + [sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1))], + [sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True)], + [sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1))],] + + loss_functions = [[sg.Radio('Cross-Entropy', 'loss', size=(12, 1)), sg.Radio('Logistic', 'loss', default=True, size=(12, 1))], + [sg.Radio('Hinge', 'loss', size=(12, 1)), sg.Radio('Huber', 'loss', size=(12, 1))], + [sg.Radio('Kullerback', 'loss', size=(12, 1)), sg.Radio('MAE(L1)', 'loss', size=(12, 1))], + [sg.Radio('MSE(L2)', 'loss', size=(12, 1)), sg.Radio('MB(L0)', 'loss', size=(12, 1))],] + + command_line_parms = [[sg.Text('Passes', size=(8, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)), + sg.Text('Steps', size=(8, 1), pad=((7,3))), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1))], + [sg.Text('ooa', size=(8, 1)), sg.In(default_text='6', size=(8, 1)), sg.Text('nn', size=(8, 1)), + sg.In(default_text='10', size=(10, 1))], + [sg.Text('q', size=(8, 1)), sg.In(default_text='ff', size=(8, 1)), sg.Text('ngram', size=(8, 1)), + sg.In(default_text='5', size=(10, 1))], + [sg.Text('l', size=(8, 1)), sg.In(default_text='0.4', size=(8, 1)), sg.Text('Layers', size=(8, 1)), + sg.Drop(values=('BatchNorm', 'other'), auto_size_text=True)],] + + layout = [[sg.Frame('Command Line Parameteres', command_line_parms, title_color='green', font='Any 12')], + [sg.Frame('Flags', flags, font='Any 12', title_color='blue')], + [sg.Frame('Loss Functions', loss_functions, font='Any 12', title_color='red')], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('Machine Learning Front End', font=("Helvetica", 12)).Layout(layout) + button, values = window.Read() + sg.SetOptions(text_justification='left') + + print(button, values) + +def CustomMeter(): + # layout the form + layout = [[sg.Text('A custom progress meter')], + [sg.ProgressBar(10000, orientation='h', size=(20,20), key='progress')], + [sg.Cancel()]] + + # create the form` + window = sg.Window('Custom Progress Meter').Layout(layout) + progress_bar = window.FindElement('progress') + # loop that would normally do something useful + for i in range(10000): + # check to see if the cancel button was clicked and exit loop if clicked + button, values = window.ReadNonBlocking() + if button == 'Cancel' or values == None: + break + # update bar with loop value +1 so that bar eventually reaches the maximum + progress_bar.UpdateBar(i+1) + # done with loop... need to destroy the window as it's still open + window.CloseNonBlocking() + +if __name__ == '__main__': + CustomMeter() + MachineLearningGUI() diff --git a/Demo_Matplotlib.py b/Demo_Matplotlib.py new file mode 100644 index 000000000..8cf6eb01c --- /dev/null +++ b/Demo_Matplotlib.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +import matplotlib +matplotlib.use('TkAgg') +from matplotlib.backends.backend_tkagg import FigureCanvasAgg +import matplotlib.backends.tkagg as tkagg +import tkinter as Tk + +""" +Demonstrates one way of embedding Matplotlib figures into a PySimpleGUI window. + +Basic steps are: + * Create a Canvas Element + * Layout form + * Display form (NON BLOCKING) + * Draw plots onto convas + * Display form (BLOCKING) +""" + + +def draw_figure(canvas, figure, loc=(0, 0)): + """ Draw a matplotlib figure onto a Tk canvas + + loc: location of top-left corner of figure on canvas in pixels. + + Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py + """ + figure_canvas_agg = FigureCanvasAgg(figure) + figure_canvas_agg.draw() + figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds + figure_w, figure_h = int(figure_w), int(figure_h) + photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) + canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) + tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) + return photo + +#------------------------------- PASTE YOUR MATPLOTLIB CODE HERE ------------------------------- + +import numpy as np +import matplotlib.pyplot as plt + +from matplotlib.ticker import NullFormatter # useful for `logit` scale + +# 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() # 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 ------------------------------- + +# define the form 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))]] + +# create the form and show it without the plot +window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', force_toplevel=True).Layout(layout).Finalize() + +# add the plot to the window +fig_photo = draw_figure(window.FindElement('canvas').TKCanvas, fig) + +# show it all again and get buttons +button, values = window.Read() diff --git a/Demo_Matplotlib_Animated.py b/Demo_Matplotlib_Animated.py new file mode 100644 index 000000000..7ea716018 --- /dev/null +++ b/Demo_Matplotlib_Animated.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +from random import randint +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureCanvasAgg +from matplotlib.figure import Figure +import matplotlib.backends.tkagg as tkagg +import tkinter as tk + + +def main(): + fig = Figure() + + ax = fig.add_subplot(111) + ax.set_xlabel("X axis") + ax.set_ylabel("Y axis") + ax.grid() + + # define the form layout + layout = [[sg.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')], + [sg.Canvas(size=(640, 480), key='canvas')], + [sg.Slider(range=(0, 10000), size=(60, 10), orientation='h', key='slider')], + [sg.ReadButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]] + + # create the form and show it without the plot + window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize() + + canvas_elem = window.FindElement('canvas') + slider_elem = window.FindElement('slider') + graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas) + canvas = canvas_elem.TKCanvas + + dpts = [randint(0, 10) for x in range(10000)] + for i in range(len(dpts)): + button, values = window.ReadNonBlocking() + if button is 'Exit' or values is None: + exit(69) + + slider_elem.Update(i) + ax.cla() + ax.grid() + DATA_POINTS_PER_SCREEN = 40 + ax.plot(range(DATA_POINTS_PER_SCREEN), dpts[i:i+DATA_POINTS_PER_SCREEN], color='purple') + graph.draw() + figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds + figure_w, figure_h = int(figure_w), int(figure_h) + photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) + + canvas.create_image(640/2, 480/2, image=photo) + + figure_canvas_agg = FigureCanvasAgg(fig) + figure_canvas_agg.draw() + + # Unfortunately, there's no accessor for the pointer to the native renderer + tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) + + # time.sleep(.1) + + +if __name__ == '__main__': + main() diff --git a/Demo_Matplotlib_Animated_Scatter.py b/Demo_Matplotlib_Animated_Scatter.py new file mode 100644 index 000000000..49135aa8f --- /dev/null +++ b/Demo_Matplotlib_Animated_Scatter.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +from random import randint +import PySimpleGUI as sg +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureCanvasAgg +from matplotlib.figure import Figure +import matplotlib.backends.tkagg as tkagg +import tkinter as tk + + +def main(): + # define the form layout + layout = [[sg.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')], + [sg.Canvas(size=(640, 480), key='canvas')], + [sg.ReadButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]] + + # create the form and show it without the plot + window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize() + + canvas_elem = window.FindElement('canvas') + canvas = canvas_elem.TKCanvas + + while True: + button, values = window.ReadNonBlocking() + if button is 'Exit' or values is None: + exit(69) + + def PyplotScatterWithLegend(): + import matplotlib.pyplot as plt + from numpy.random import rand + + fig, ax = plt.subplots() + for color in ['red', 'green', 'blue']: + n = 750 + x, y = rand(2, n) + scale = 200.0 * rand(n) + ax.scatter(x, y, c=color, s=scale, label=color, + alpha=0.3, edgecolors='none') + + ax.legend() + ax.grid(True) + return fig + + fig = PyplotScatterWithLegend() + + figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds + figure_w, figure_h = int(figure_w), int(figure_h) + photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) + + canvas.create_image(640/2, 480/2, image=photo) + + figure_canvas_agg = FigureCanvasAgg(fig) + figure_canvas_agg.draw() + + # Unfortunately, there's no accessor for the pointer to the native renderer + tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) + + # time.sleep(.1) + + +if __name__ == '__main__': + main() diff --git a/Demo_Matplotlib_Browser.py b/Demo_Matplotlib_Browser.py new file mode 100644 index 000000000..f30956786 --- /dev/null +++ b/Demo_Matplotlib_Browser.py @@ -0,0 +1,906 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import matplotlib +matplotlib.use('TkAgg') +from matplotlib.backends.backend_tkagg import FigureCanvasAgg +import matplotlib.backends.tkagg as tkagg +import tkinter as Tk +import inspect + +""" +Demonstrates one way of embedding Matplotlib figures into a PySimpleGUI window. + +Basic steps are: + * Create a Canvas Element + * Layout form + * Display form (NON BLOCKING) + * Draw plots onto convas + * Display form (BLOCKING) +""" + + + +import numpy as np +import matplotlib.pyplot as plt + + +def PyplotSimple(): + import numpy as np + import matplotlib.pyplot as plt + + # evenly sampled time at 200ms intervals + t = np.arange(0., 5., 0.2) + + # red dashes, blue squares and green triangles + plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^') + + fig = plt.gcf() # get the figure to show + return fig + +def PyplotHistogram(): + """ + ============================================================= + Demo of the histogram (hist) function with multiple data sets + ============================================================= + + Plot histogram with multiple sample sets and demonstrate: + + * Use of legend with multiple sample sets + * Stacked bars + * Step curve with no fill + * Data sets of different sample sizes + + Selecting different bin counts and sizes can significantly affect the + shape of a histogram. The Astropy docs have a great section on how to + select these parameters: + http://docs.astropy.org/en/stable/visualization/histogram.html + """ + + import numpy as np + import matplotlib.pyplot as plt + + np.random.seed(0) + + n_bins = 10 + x = np.random.randn(1000, 3) + + fig, axes = plt.subplots(nrows=2, ncols=2) + ax0, ax1, ax2, ax3 = axes.flatten() + + colors = ['red', 'tan', 'lime'] + ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors) + ax0.legend(prop={'size': 10}) + ax0.set_title('bars with legend') + + ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True) + ax1.set_title('stacked bar') + + ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False) + ax2.set_title('stack step (unfilled)') + + # Make a multiple-histogram of data-sets with different length. + x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]] + ax3.hist(x_multi, n_bins, histtype='bar') + ax3.set_title('different sample sizes') + + fig.tight_layout() + return fig + +def PyplotArtistBoxPlots(): + """ + ========================================= + Demo of artist customization in box plots + ========================================= + + This example demonstrates how to use the various kwargs + to fully customize box plots. The first figure demonstrates + how to remove and add individual components (note that the + mean is the only value not shown by default). The second + figure demonstrates how the styles of the artists can + be customized. It also demonstrates how to set the limit + of the whiskers to specific percentiles (lower right axes) + + A good general reference on boxplots and their history can be found + here: http://vita.had.co.nz/papers/boxplots.pdf + + """ + + import numpy as np + import matplotlib.pyplot as plt + + # fake data + np.random.seed(937) + data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75) + labels = list('ABCD') + fs = 10 # fontsize + + # demonstrate how to toggle the display of different elements: + fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True) + axes[0, 0].boxplot(data, labels=labels) + axes[0, 0].set_title('Default', fontsize=fs) + + axes[0, 1].boxplot(data, labels=labels, showmeans=True) + axes[0, 1].set_title('showmeans=True', fontsize=fs) + + axes[0, 2].boxplot(data, labels=labels, showmeans=True, meanline=True) + axes[0, 2].set_title('showmeans=True,\nmeanline=True', fontsize=fs) + + axes[1, 0].boxplot(data, labels=labels, showbox=False, showcaps=False) + tufte_title = 'Tufte Style \n(showbox=False,\nshowcaps=False)' + axes[1, 0].set_title(tufte_title, fontsize=fs) + + axes[1, 1].boxplot(data, labels=labels, notch=True, bootstrap=10000) + axes[1, 1].set_title('notch=True,\nbootstrap=10000', fontsize=fs) + + axes[1, 2].boxplot(data, labels=labels, showfliers=False) + axes[1, 2].set_title('showfliers=False', fontsize=fs) + + for ax in axes.flatten(): + ax.set_yscale('log') + ax.set_yticklabels([]) + + fig.subplots_adjust(hspace=0.4) + return fig + +def ArtistBoxplot2(): + + # fake data + np.random.seed(937) + data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75) + labels = list('ABCD') + fs = 10 # fontsize + + # demonstrate how to customize the display different elements: + boxprops = dict(linestyle='--', linewidth=3, color='darkgoldenrod') + flierprops = dict(marker='o', markerfacecolor='green', markersize=12, + linestyle='none') + medianprops = dict(linestyle='-.', linewidth=2.5, color='firebrick') + meanpointprops = dict(marker='D', markeredgecolor='black', + markerfacecolor='firebrick') + meanlineprops = dict(linestyle='--', linewidth=2.5, color='purple') + + fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True) + axes[0, 0].boxplot(data, boxprops=boxprops) + axes[0, 0].set_title('Custom boxprops', fontsize=fs) + + axes[0, 1].boxplot(data, flierprops=flierprops, medianprops=medianprops) + axes[0, 1].set_title('Custom medianprops\nand flierprops', fontsize=fs) + + axes[0, 2].boxplot(data, whis='range') + axes[0, 2].set_title('whis="range"', fontsize=fs) + + axes[1, 0].boxplot(data, meanprops=meanpointprops, meanline=False, + showmeans=True) + axes[1, 0].set_title('Custom mean\nas point', fontsize=fs) + + axes[1, 1].boxplot(data, meanprops=meanlineprops, meanline=True, + showmeans=True) + axes[1, 1].set_title('Custom mean\nas line', fontsize=fs) + + axes[1, 2].boxplot(data, whis=[15, 85]) + axes[1, 2].set_title('whis=[15, 85]\n#percentiles', fontsize=fs) + + for ax in axes.flatten(): + ax.set_yscale('log') + ax.set_yticklabels([]) + + fig.suptitle("I never said they'd be pretty") + fig.subplots_adjust(hspace=0.4) + return fig + +def PyplotScatterWithLegend(): + import matplotlib.pyplot as plt + from numpy.random import rand + + fig, ax = plt.subplots() + for color in ['red', 'green', 'blue']: + n = 750 + x, y = rand(2, n) + scale = 200.0 * rand(n) + ax.scatter(x, y, c=color, s=scale, label=color, + alpha=0.3, edgecolors='none') + + ax.legend() + ax.grid(True) + return fig + +def PyplotLineStyles(): + """ + ========== + Linestyles + ========== + + This examples showcases different linestyles copying those of Tikz/PGF. + """ + import numpy as np + import matplotlib.pyplot as plt + from collections import OrderedDict + from matplotlib.transforms import blended_transform_factory + + linestyles = OrderedDict( + [('solid', (0, ())), + ('loosely dotted', (0, (1, 10))), + ('dotted', (0, (1, 5))), + ('densely dotted', (0, (1, 1))), + + ('loosely dashed', (0, (5, 10))), + ('dashed', (0, (5, 5))), + ('densely dashed', (0, (5, 1))), + + ('loosely dashdotted', (0, (3, 10, 1, 10))), + ('dashdotted', (0, (3, 5, 1, 5))), + ('densely dashdotted', (0, (3, 1, 1, 1))), + + ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))), + ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))), + ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]) + + plt.figure(figsize=(10, 6)) + ax = plt.subplot(1, 1, 1) + + X, Y = np.linspace(0, 100, 10), np.zeros(10) + for i, (name, linestyle) in enumerate(linestyles.items()): + ax.plot(X, Y + i, linestyle=linestyle, linewidth=1.5, color='black') + + ax.set_ylim(-0.5, len(linestyles) - 0.5) + plt.yticks(np.arange(len(linestyles)), linestyles.keys()) + plt.xticks([]) + + # For each line style, add a text annotation with a small offset from + # the reference point (0 in Axes coords, y tick value in Data coords). + reference_transform = blended_transform_factory(ax.transAxes, ax.transData) + for i, (name, linestyle) in enumerate(linestyles.items()): + ax.annotate(str(linestyle), xy=(0.0, i), xycoords=reference_transform, + xytext=(-6, -12), textcoords='offset points', color="blue", + fontsize=8, ha="right", family="monospace") + + plt.tight_layout() + return plt.gcf() + +def PyplotLinePolyCollection(): + import matplotlib.pyplot as plt + from matplotlib import collections, colors, transforms + import numpy as np + + nverts = 50 + npts = 100 + + # Make some spirals + r = np.arange(nverts) + theta = np.linspace(0, 2 * np.pi, nverts) + xx = r * np.sin(theta) + yy = r * np.cos(theta) + spiral = np.column_stack([xx, yy]) + + # Fixing random state for reproducibility + rs = np.random.RandomState(19680801) + + # Make some offsets + xyo = rs.randn(npts, 2) + + # Make a list of colors cycling through the default series. + colors = [colors.to_rgba(c) + for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] + + fig, axes = plt.subplots(2, 2) + fig.subplots_adjust(top=0.92, left=0.07, right=0.97, + hspace=0.3, wspace=0.3) + ((ax1, ax2), (ax3, ax4)) = axes # unpack the axes + + col = collections.LineCollection([spiral], offsets=xyo, + transOffset=ax1.transData) + trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0 / 72.0) + col.set_transform(trans) # the points to pixels transform + # Note: the first argument to the collection initializer + # must be a list of sequences of x,y tuples; we have only + # one sequence, but we still have to put it in a list. + ax1.add_collection(col, autolim=True) + # autolim=True enables autoscaling. For collections with + # offsets like this, it is neither efficient nor accurate, + # but it is good enough to generate a plot that you can use + # as a starting point. If you know beforehand the range of + # x and y that you want to show, it is better to set them + # explicitly, leave out the autolim kwarg (or set it to False), + # and omit the 'ax1.autoscale_view()' call below. + + # Make a transform for the line segments such that their size is + # given in points: + col.set_color(colors) + + ax1.autoscale_view() # See comment above, after ax1.add_collection. + ax1.set_title('LineCollection using offsets') + + # The same data as above, but fill the curves. + col = collections.PolyCollection([spiral], offsets=xyo, + transOffset=ax2.transData) + trans = transforms.Affine2D().scale(fig.dpi / 72.0) + col.set_transform(trans) # the points to pixels transform + ax2.add_collection(col, autolim=True) + col.set_color(colors) + + ax2.autoscale_view() + ax2.set_title('PolyCollection using offsets') + + # 7-sided regular polygons + + col = collections.RegularPolyCollection( + 7, sizes=np.abs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData) + trans = transforms.Affine2D().scale(fig.dpi / 72.0) + col.set_transform(trans) # the points to pixels transform + ax3.add_collection(col, autolim=True) + col.set_color(colors) + ax3.autoscale_view() + ax3.set_title('RegularPolyCollection using offsets') + + # Simulate a series of ocean current profiles, successively + # offset by 0.1 m/s so that they form what is sometimes called + # a "waterfall" plot or a "stagger" plot. + + nverts = 60 + ncurves = 20 + offs = (0.1, 0.0) + + yy = np.linspace(0, 2 * np.pi, nverts) + ym = np.max(yy) + xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5 + segs = [] + for i in range(ncurves): + xxx = xx + 0.02 * rs.randn(nverts) + curve = np.column_stack([xxx, yy * 100]) + segs.append(curve) + + col = collections.LineCollection(segs, offsets=offs) + ax4.add_collection(col, autolim=True) + col.set_color(colors) + ax4.autoscale_view() + ax4.set_title('Successive data offsets') + ax4.set_xlabel('Zonal velocity component (m/s)') + ax4.set_ylabel('Depth (m)') + # Reverse the y-axis so depth increases downward + ax4.set_ylim(ax4.get_ylim()[::-1]) + return fig + +def PyplotGGPlotSytleSheet(): + import numpy as np + import matplotlib.pyplot as plt + + plt.style.use('ggplot') + + # Fixing random state for reproducibility + np.random.seed(19680801) + + fig, axes = plt.subplots(ncols=2, nrows=2) + ax1, ax2, ax3, ax4 = axes.ravel() + + # scatter plot (Note: `plt.scatter` doesn't use default colors) + x, y = np.random.normal(size=(2, 200)) + ax1.plot(x, y, 'o') + + # sinusoidal lines with colors from default color cycle + L = 2 * np.pi + x = np.linspace(0, L) + ncolors = len(plt.rcParams['axes.prop_cycle']) + shift = np.linspace(0, L, ncolors, endpoint=False) + for s in shift: + ax2.plot(x, np.sin(x + s), '-') + ax2.margins(0) + + # bar graphs + x = np.arange(5) + y1, y2 = np.random.randint(1, 25, size=(2, 5)) + width = 0.25 + ax3.bar(x, y1, width) + ax3.bar(x + width, y2, width, + color=list(plt.rcParams['axes.prop_cycle'])[2]['color']) + ax3.set_xticks(x + width) + ax3.set_xticklabels(['a', 'b', 'c', 'd', 'e']) + + # circles with colors from default color cycle + for i, color in enumerate(plt.rcParams['axes.prop_cycle']): + xy = np.random.normal(size=2) + ax4.add_patch(plt.Circle(xy, radius=0.3, color=color['color'])) + ax4.axis('equal') + ax4.margins(0) + fig = plt.gcf() # get the figure to show + return fig + +def PyplotBoxPlot(): + import numpy as np + import matplotlib.pyplot as plt + + # Fixing random state for reproducibility + np.random.seed(19680801) + + # fake up some data + spread = np.random.rand(50) * 100 + center = np.ones(25) * 50 + flier_high = np.random.rand(10) * 100 + 100 + flier_low = np.random.rand(10) * -100 + data = np.concatenate((spread, center, flier_high, flier_low), 0) + fig1, ax1 = plt.subplots() + ax1.set_title('Basic Plot') + ax1.boxplot(data) + return fig1 + +def PyplotRadarChart(): + import numpy as np + + import matplotlib.pyplot as plt + from matplotlib.path import Path + from matplotlib.spines import Spine + from matplotlib.projections.polar import PolarAxes + from matplotlib.projections import register_projection + + def radar_factory(num_vars, frame='circle'): + """Create a radar chart with `num_vars` axes. + + This function creates a RadarAxes projection and registers it. + + Parameters + ---------- + num_vars : int + Number of variables for radar chart. + frame : {'circle' | 'polygon'} + Shape of frame surrounding axes. + + """ + # calculate evenly-spaced axis angles + theta = np.linspace(0, 2 * np.pi, num_vars, endpoint=False) + + def draw_poly_patch(self): + # rotate theta such that the first axis is at the top + verts = unit_poly_verts(theta + np.pi / 2) + return plt.Polygon(verts, closed=True, edgecolor='k') + + def draw_circle_patch(self): + # unit circle centered on (0.5, 0.5) + return plt.Circle((0.5, 0.5), 0.5) + + patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch} + if frame not in patch_dict: + raise ValueError('unknown value for `frame`: %s' % frame) + + class RadarAxes(PolarAxes): + + name = 'radar' + # use 1 line segment to connect specified points + RESOLUTION = 1 + # define draw_frame method + draw_patch = patch_dict[frame] + + def __init__(self, *args, **kwargs): + super(RadarAxes, self).__init__(*args, **kwargs) + # rotate plot such that the first axis is at the top + self.set_theta_zero_location('N') + + def fill(self, *args, **kwargs): + """Override fill so that line is closed by default""" + closed = kwargs.pop('closed', True) + return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) + + def plot(self, *args, **kwargs): + """Override plot so that line is closed by default""" + lines = super(RadarAxes, self).plot(*args, **kwargs) + for line in lines: + self._close_line(line) + + def _close_line(self, line): + x, y = line.get_data() + # FIXME: markers at x[0], y[0] get doubled-up + if x[0] != x[-1]: + x = np.concatenate((x, [x[0]])) + y = np.concatenate((y, [y[0]])) + line.set_data(x, y) + + def set_varlabels(self, labels): + self.set_thetagrids(np.degrees(theta), labels) + + def _gen_axes_patch(self): + return self.draw_patch() + + def _gen_axes_spines(self): + if frame == 'circle': + return PolarAxes._gen_axes_spines(self) + # The following is a hack to get the spines (i.e. the axes frame) + # to draw correctly for a polygon frame. + + # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`. + spine_type = 'circle' + verts = unit_poly_verts(theta + np.pi / 2) + # close off polygon by repeating first vertex + verts.append(verts[0]) + path = Path(verts) + + spine = Spine(self, spine_type, path) + spine.set_transform(self.transAxes) + return {'polar': spine} + + register_projection(RadarAxes) + return theta + + def unit_poly_verts(theta): + """Return vertices of polygon for subplot axes. + + This polygon is circumscribed by a unit circle centered at (0.5, 0.5) + """ + x0, y0, r = [0.5] * 3 + verts = [(r * np.cos(t) + x0, r * np.sin(t) + y0) for t in theta] + return verts + + def example_data(): + # The following data is from the Denver Aerosol Sources and Health study. + # See doi:10.1016/j.atmosenv.2008.12.017 + # + # The data are pollution source profile estimates for five modeled + # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical + # species. The radar charts are experimented with here to see if we can + # nicely visualize how the modeled source profiles change across four + # scenarios: + # 1) No gas-phase species present, just seven particulate counts on + # Sulfate + # Nitrate + # Elemental Carbon (EC) + # Organic Carbon fraction 1 (OC) + # Organic Carbon fraction 2 (OC2) + # Organic Carbon fraction 3 (OC3) + # Pyrolized Organic Carbon (OP) + # 2)Inclusion of gas-phase specie carbon monoxide (CO) + # 3)Inclusion of gas-phase specie ozone (O3). + # 4)Inclusion of both gas-phase species is present... + data = [ + ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'], + ('Basecase', [ + [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00], + [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00], + [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00], + [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00], + [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]), + ('With CO', [ + [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00], + [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00], + [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00], + [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00], + [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]), + ('With O3', [ + [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03], + [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00], + [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00], + [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95], + [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]), + ('CO & O3', [ + [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01], + [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00], + [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00], + [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88], + [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]]) + ] + return data + + N = 9 + theta = radar_factory(N, frame='polygon') + + data = example_data() + spoke_labels = data.pop(0) + + fig, axes = plt.subplots(figsize=(9, 9), nrows=2, ncols=2, + subplot_kw=dict(projection='radar')) + fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) + + colors = ['b', 'r', 'g', 'm', 'y'] + # Plot the four cases from the example data on separate axes + for ax, (title, case_data) in zip(axes.flatten(), data): + ax.set_rgrids([0.2, 0.4, 0.6, 0.8]) + ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), + horizontalalignment='center', verticalalignment='center') + for d, color in zip(case_data, colors): + ax.plot(theta, d, color=color) + ax.fill(theta, d, facecolor=color, alpha=0.25) + ax.set_varlabels(spoke_labels) + + # add legend relative to top-left plot + ax = axes[0, 0] + labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5') + legend = ax.legend(labels, loc=(0.9, .95), + labelspacing=0.1, fontsize='small') + + fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios', + horizontalalignment='center', color='black', weight='bold', + size='large') + return fig + +def DifferentScales(): + import numpy as np + import matplotlib.pyplot as plt + + # Create some mock data + t = np.arange(0.01, 10.0, 0.01) + data1 = np.exp(t) + data2 = np.sin(2 * np.pi * t) + + fig, ax1 = plt.subplots() + + color = 'tab:red' + ax1.set_xlabel('time (s)') + ax1.set_ylabel('exp', color=color) + ax1.plot(t, data1, color=color) + ax1.tick_params(axis='y', labelcolor=color) + + ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis + + color = 'tab:blue' + ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1 + ax2.plot(t, data2, color=color) + ax2.tick_params(axis='y', labelcolor=color) + + fig.tight_layout() # otherwise the right y-label is slightly clipped + return fig + +def ExploringNormalizations(): + import matplotlib.pyplot as plt + import matplotlib.colors as mcolors + import numpy as np + from numpy.random import multivariate_normal + + data = np.vstack([ + multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000), + multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000) + ]) + + gammas = [0.8, 0.5, 0.3] + + fig, axes = plt.subplots(nrows=2, ncols=2) + + axes[0, 0].set_title('Linear normalization') + axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100) + + for ax, gamma in zip(axes.flat[1:], gammas): + ax.set_title(r'Power law $(\gamma=%1.1f)$' % gamma) + ax.hist2d(data[:, 0], data[:, 1], + bins=100, norm=mcolors.PowerNorm(gamma)) + + fig.tight_layout() + return fig + +def PyplotFormatstr(): + + def f(t): + return np.exp(-t) * np.cos(2*np.pi*t) + + t1 = np.arange(0.0, 5.0, 0.1) + t2 = np.arange(0.0, 5.0, 0.02) + + plt.figure(1) + plt.subplot(211) + plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') + + plt.subplot(212) + plt.plot(t2, np.cos(2*np.pi*t2), 'r--') + fig = plt.gcf() # get the figure to show + return fig + +def UnicodeMinus(): + import numpy as np + import matplotlib + import matplotlib.pyplot as plt + + # Fixing random state for reproducibility + np.random.seed(19680801) + + matplotlib.rcParams['axes.unicode_minus'] = False + fig, ax = plt.subplots() + ax.plot(10 * np.random.randn(100), 10 * np.random.randn(100), 'o') + ax.set_title('Using hyphen instead of Unicode minus') + return fig + +def Subplot3d(): + from mpl_toolkits.mplot3d.axes3d import Axes3D + from matplotlib import cm + # from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter + import matplotlib.pyplot as plt + import numpy as np + + fig = plt.figure() + + ax = fig.add_subplot(1, 2, 1, projection='3d') + X = np.arange(-5, 5, 0.25) + Y = np.arange(-5, 5, 0.25) + X, Y = np.meshgrid(X, Y) + R = np.sqrt(X ** 2 + Y ** 2) + Z = np.sin(R) + surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, + linewidth=0, antialiased=False) + ax.set_zlim3d(-1.01, 1.01) + + # ax.w_zaxis.set_major_locator(LinearLocator(10)) + # ax.w_zaxis.set_major_formatter(FormatStrFormatter('%.03f')) + + fig.colorbar(surf, shrink=0.5, aspect=5) + + from mpl_toolkits.mplot3d.axes3d import get_test_data + ax = fig.add_subplot(1, 2, 2, projection='3d') + X, Y, Z = get_test_data(0.05) + ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) + return fig + +def PyplotScales(): + import numpy as np + import matplotlib.pyplot as plt + + from matplotlib.ticker import NullFormatter # useful for `logit` scale + + # 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) + # Format the minor tick labels of the y-axis into empty strings with + # `NullFormatter`, to avoid cumbering the axis with too many labels. + plt.gca().yaxis.set_minor_formatter(NullFormatter()) + # Adjust the subplot layout, because the logit one may take more space + # than usual, due to y-tick labels like "1 - 10^{-3}" + plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, + wspace=0.35) + return plt.gcf() + + +def AxesGrid(): + import numpy as np + import matplotlib.pyplot as plt + from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes + + def get_demo_image(): + # prepare image + delta = 0.5 + + extent = (-3, 4, -4, 3) + x = np.arange(-3.0, 4.001, delta) + y = np.arange(-4.0, 3.001, delta) + X, Y = np.meshgrid(x, y) + Z1 = np.exp(-X ** 2 - Y ** 2) + Z2 = np.exp(-(X - 1) ** 2 - (Y - 1) ** 2) + Z = (Z1 - Z2) * 2 + + return Z, extent + + def get_rgb(): + Z, extent = get_demo_image() + + Z[Z < 0] = 0. + Z = Z / Z.max() + + R = Z[:13, :13] + G = Z[2:, 2:] + B = Z[:13, 2:] + + return R, G, B + + fig = plt.figure(1) + ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8]) + + r, g, b = get_rgb() + kwargs = dict(origin="lower", interpolation="nearest") + ax.imshow_rgb(r, g, b, **kwargs) + + ax.RGB.set_xlim(0., 9.5) + ax.RGB.set_ylim(0.9, 10.6) + + plt.draw() + return plt.gcf() + +# The magic function that makes it possible.... glues together tkinter and pyplot using Canvas Widget +def draw_figure(canvas, figure, loc=(0, 0)): + """ Draw a matplotlib figure onto a Tk canvas + + loc: location of top-left corner of figure on canvas in pixels. + + Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py + """ + figure_canvas_agg = FigureCanvasAgg(figure) + figure_canvas_agg.draw() + figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds + figure_w, figure_h = int(figure_w), int(figure_h) + photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) + + # Position: convert from top-left anchor to center anchor + canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) + + # Unfortunately, there's no accessor for the pointer to the native renderer + tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) + + # Return a handle which contains a reference to the photo object + # which must be kept live or else the picture disappears + return photo + + +# -------------------------------- GUI Starts Here -------------------------------# +# fig = your figure you want to display. Assumption is that 'fig' holds the # +# information to display. # +# --------------------------------------------------------------------------------# + +# print(inspect.getsource(PyplotSimple)) + + +fig_dict = {'Pyplot Simple':PyplotSimple, 'Pyplot Formatstr':PyplotFormatstr,'PyPlot Three':Subplot3d, + 'Unicode Minus': UnicodeMinus, 'Pyplot Scales' : PyplotScales, 'Axes Grid' : AxesGrid, + 'Exploring Normalizations' : ExploringNormalizations, 'Different Scales' : DifferentScales, + 'Pyplot Box Plot' : PyplotBoxPlot, 'Pyplot ggplot Style Sheet' : PyplotGGPlotSytleSheet, + 'Pyplot Line Poly Collection' : PyplotLinePolyCollection, 'Pyplot Line Styles' : PyplotLineStyles, + 'Pyplot Scatter With Legend' :PyplotScatterWithLegend, 'Artist Customized Box Plots' : PyplotArtistBoxPlots, + 'Artist Customized Box Plots 2' : ArtistBoxplot2, 'Pyplot Histogram' : PyplotHistogram} + + +sg.ChangeLookAndFeel('LightGreen') +figure_w, figure_h = 650, 650 +# define the form layout +listbox_values = [key for key in fig_dict.keys()] +col_listbox = [[sg.Listbox(values=listbox_values, change_submits=True, size=(28, len(listbox_values)), key='func')], + [sg.T(' ' * 12), sg.Exit(size=(5, 2))]] + +layout = [[sg.Text('Matplotlib Plot Test', font=('current 18'))], + [sg.Column(col_listbox, pad=(5, (3, 330))), sg.Canvas(size=(figure_w, figure_h), key='canvas') , + sg.Multiline(size=(70, 35), pad=(5, (3, 90)), key='multiline')],] + +# create the form and show it without the plot +window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', grab_anywhere=False).Layout(layout) +window.Finalize() + +canvas_elem = window.FindElement('canvas') +multiline_elem= window.FindElement('multiline') + +while True: + button, values = window.Read() + print(button) + # show it all again and get buttons + if button is None or button is 'Exit': + break + + try: + choice = values['func'][0] + func = fig_dict[choice] + except: + pass + + multiline_elem.Update(inspect.getsource(func)) + plt.clf() + fig = func() + fig_photo = draw_figure(canvas_elem.TKCanvas, fig) + + diff --git a/Demo_Matplotlib_Ping_Graph.py b/Demo_Matplotlib_Ping_Graph.py new file mode 100644 index 000000000..318297502 --- /dev/null +++ b/Demo_Matplotlib_Ping_Graph.py @@ -0,0 +1,674 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import matplotlib.pyplot as plt +from matplotlib.backends.backend_tkagg import FigureCanvasAgg +import matplotlib.backends.tkagg as tkagg +import tkinter as tk + + +""" +A graph of time to ping Google.com +Demonstrates Matploylib used in an animated way. + +Note this file contains a copy of ping.py. It is contained in the first part of this file + +""" + + +""" + A pure python ping implementation using raw sockets. + + (This is Python 3 port of https://github.com/jedie/python-ping) + (Tested and working with python 2.7, should work with 2.6+) + + Note that ICMP messages can only be sent from processes running as root + (in Windows, you must run this script as 'Administrator'). + + Derived from ping.c distributed in Linux's netkit. That code is + copyright (c) 1989 by The Regents of the University of California. + That code is in turn derived from code written by Mike Muuss of the + US Army Ballistic Research Laboratory in December, 1983 and + placed in the public domain. They have my thanks. + + Bugs are naturally mine. I'd be glad to hear about them. There are + certainly word - size dependencies here. + + Copyright (c) Matthew Dixon Cowles, . + Distributable under the terms of the GNU General Public License + version 2. Provided with no warranties of any sort. + + Original Version from Matthew Dixon Cowles: + -> ftp://ftp.visi.com/users/mdc/ping.py + + Rewrite by Jens Diemer: + -> http://www.python-forum.de/post-69122.html#69122 + + Rewrite by George Notaras: + -> http://www.g-loaded.eu/2009/10/30/python-ping/ + + Enhancements by Martin Falatic: + -> http://www.falatic.com/index.php/39/pinging-with-python + + Enhancements and fixes by Georgi Kolev: + -> http://github.com/jedie/python-ping/ + + Bug fix by Andrejs Rozitis: + -> http://github.com/rozitis/python-ping/ + + Revision history + ~~~~~~~~~~~~~~~~ + May 1, 2014 + ----------- + Little modifications by Mohammad Emami + - Added Python 3 support. For now this project will just support + python 3.x + - Tested with python 3.3 + - version was upped to 0.6 + + March 19, 2013 + -------------- + * Fixing bug to prevent divide by 0 during run-time. + + January 26, 2012 + ---------------- + * Fixing BUG #4 - competability with python 2.x [tested with 2.7] + - Packet data building is different for 2.x and 3.x. + 'cose of the string/bytes difference. + * Fixing BUG #10 - the multiple resolv issue. + - When pinging domain names insted of hosts (for exmaple google.com) + you can get different IP every time you try to resolv it, we should + resolv the host only once and stick to that IP. + * Fixing BUGs #3 #10 - Doing hostname resolv only once. + * Fixing BUG #14 - Removing all 'global' stuff. + - You should not use globul! Its bad for you...and its not thread safe! + * Fix - forcing the use of different times on linux/windows for + more accurate mesurments. (time.time - linux/ time.clock - windows) + * Adding quiet_ping function - This way we'll be able to use this script + as external lib. + * Changing default timeout to 3s. (1second is not enought) + * Switching data syze to packet size. It's easyer for the user to ignore the + fact that the packet headr is 8b and the datasize 64 will make packet with + size 72. + + October 12, 2011 + -------------- + Merged updates from the main project + -> https://github.com/jedie/python-ping + + September 12, 2011 + -------------- + Bugfixes + cleanup by Jens Diemer + Tested with Ubuntu + Windows 7 + + September 6, 2011 + -------------- + Cleanup by Martin Falatic. Restored lost comments and docs. Improved + functionality: constant time between pings, internal times consistently + use milliseconds. Clarified annotations (e.g., in the checksum routine). + Using unsigned data in IP & ICMP header pack/unpack unless otherwise + necessary. Signal handling. Ping-style output formatting and stats. + + August 3, 2011 + -------------- + Ported to py3k by Zach Ware. Mostly done by 2to3; also minor changes to + deal with bytes vs. string changes (no more ord() in checksum() because + >source_string< is actually bytes, added .encode() to data in + send_one_ping()). That's about it. + + March 11, 2010 + -------------- + changes by Samuel Stauffer: + - replaced time.clock with default_timer which is set to + time.clock on windows and time.time on other systems. + + November 8, 2009 + ---------------- + Improved compatibility with GNU/Linux systems. + + Fixes by: + * George Notaras -- http://www.g-loaded.eu + Reported by: + * Chris Hallman -- http://cdhallman.blogspot.com + + Changes in this release: + - Re-use time.time() instead of time.clock(). The 2007 implementation + worked only under Microsoft Windows. Failed on GNU/Linux. + time.clock() behaves differently under the two OSes[1]. + + [1] http://docs.python.org/library/time.html#time.clock + + May 30, 2007 + ------------ + little rewrite by Jens Diemer: + - change socket asterisk import to a normal import + - replace time.time() with time.clock() + - delete "return None" (or change to "return" only) + - in checksum() rename "str" to "source_string" + + December 4, 2000 + ---------------- + Changed the struct.pack() calls to pack the checksum and ID as + unsigned. My thanks to Jerome Poincheval for the fix. + + November 22, 1997 + ----------------- + Initial hack. Doesn't do much, but rather than try to guess + what features I (or others) will want in the future, I've only + put in what I need now. + + December 16, 1997 + ----------------- + For some reason, the checksum bytes are in the wrong order when + this is run under Solaris 2.X for SPARC but it works right under + Linux x86. Since I don't know just what's wrong, I'll swap the + bytes always and then do an htons(). + + =========================================================================== + IP header info from RFC791 + -> http://tools.ietf.org/html/rfc791) + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |Version| IHL |Type of Service| Total Length | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Identification |Flags| Fragment Offset | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Time to Live | Protocol | Header Checksum | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Source Address | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Destination Address | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Options | Padding | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + =========================================================================== + ICMP Echo / Echo Reply Message header info from RFC792 + -> http://tools.ietf.org/html/rfc792 + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Type | Code | Checksum | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Identifier | Sequence Number | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Data ... + +-+-+-+-+- + + =========================================================================== + ICMP parameter info: + -> http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml + + =========================================================================== + An example of ping's typical output: + + PING heise.de (193.99.144.80): 56 data bytes + 64 bytes from 193.99.144.80: icmp_seq=0 ttl=240 time=127 ms + 64 bytes from 193.99.144.80: icmp_seq=1 ttl=240 time=127 ms + 64 bytes from 193.99.144.80: icmp_seq=2 ttl=240 time=126 ms + 64 bytes from 193.99.144.80: icmp_seq=3 ttl=240 time=126 ms + 64 bytes from 193.99.144.80: icmp_seq=4 ttl=240 time=127 ms + + ----heise.de PING Statistics---- + 5 packets transmitted, 5 packets received, 0.0% packet loss + round-trip (ms) min/avg/max/med = 126/127/127/127 + + =========================================================================== +""" + +# =============================================================================# +import argparse +import os, sys, socket, struct, select, time, signal + +__description__ = 'A pure python ICMP ping implementation using raw sockets.' + +if sys.platform == "win32": + # On Windows, the best timer is time.clock() + default_timer = time.clock +else: + # On most other platforms the best timer is time.time() + default_timer = time.time + +NUM_PACKETS = 3 +PACKET_SIZE = 64 +WAIT_TIMEOUT = 3.0 + +# =============================================================================# +# ICMP parameters + +ICMP_ECHOREPLY = 0 # Echo reply (per RFC792) +ICMP_ECHO = 8 # Echo request (per RFC792) +ICMP_MAX_RECV = 2048 # Max size of incoming buffer + +MAX_SLEEP = 1000 + + +class MyStats: + thisIP = "0.0.0.0" + pktsSent = 0 + pktsRcvd = 0 + minTime = 999999999 + maxTime = 0 + totTime = 0 + avrgTime = 0 + fracLoss = 1.0 + + +myStats = MyStats # NOT Used globally anymore. + + +# =============================================================================# +def checksum(source_string): + """ + A port of the functionality of in_cksum() from ping.c + Ideally this would act on the string as a series of 16-bit ints (host + packed), but this works. + Network data is big-endian, hosts are typically little-endian + """ + countTo = (int(len(source_string) / 2)) * 2 + sum = 0 + count = 0 + + # Handle bytes in pairs (decoding as short ints) + loByte = 0 + hiByte = 0 + while count < countTo: + if (sys.byteorder == "little"): + loByte = source_string[count] + hiByte = source_string[count + 1] + else: + loByte = source_string[count + 1] + hiByte = source_string[count] + try: # For Python3 + sum = sum + (hiByte * 256 + loByte) + except: # For Python2 + sum = sum + (ord(hiByte) * 256 + ord(loByte)) + count += 2 + + # Handle last byte if applicable (odd-number of bytes) + # Endianness should be irrelevant in this case + if countTo < len(source_string): # Check for odd length + loByte = source_string[len(source_string) - 1] + try: # For Python3 + sum += loByte + except: # For Python2 + sum += ord(loByte) + + sum &= 0xffffffff # Truncate sum to 32 bits (a variance from ping.c, which + # uses signed ints, but overflow is unlikely in ping) + + sum = (sum >> 16) + (sum & 0xffff) # Add high 16 bits to low 16 bits + sum += (sum >> 16) # Add carry from above (if any) + answer = ~sum & 0xffff # Invert and truncate to 16 bits + answer = socket.htons(answer) + + return answer + + +# =============================================================================# +def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False): + """ + Returns either the delay (in ms) or None on timeout. + """ + delay = None + + try: # One could use UDP here, but it's obscure + mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) + except socket.error as e: + print("failed. (socket error: '%s')" % e.args[1]) + raise # raise the original error + + my_ID = os.getpid() & 0xFFFF + + sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, packet_size) + if sentTime == None: + mySocket.close() + return delay + + myStats.pktsSent += 1 + + recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout) + + mySocket.close() + + if recvTime: + delay = (recvTime - sentTime) * 1000 + if not quiet: + print("%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms" % ( + dataSize, socket.inet_ntoa(struct.pack("!I", iphSrcIP)), icmpSeqNumber, iphTTL, delay) + ) + myStats.pktsRcvd += 1 + myStats.totTime += delay + if myStats.minTime > delay: + myStats.minTime = delay + if myStats.maxTime < delay: + myStats.maxTime = delay + else: + delay = None + print("Request timed out.") + + return delay + + +# =============================================================================# +def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size): + """ + Send one ping to the given >destIP<. + """ + # destIP = socket.gethostbyname(destIP) + + # Header is type (8), code (8), checksum (16), id (16), sequence (16) + # (packet_size - 8) - Remove header size from packet size + myChecksum = 0 + + # Make a dummy heder with a 0 checksum. + header = struct.pack( + "!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber + ) + + padBytes = [] + startVal = 0x42 + # 'cose of the string/byte changes in python 2/3 we have + # to build the data differnely for different version + # or it will make packets with unexpected size. + if sys.version[:1] == '2': + bytes = struct.calcsize("d") + data = ((packet_size - 8) - bytes) * "Q" + data = struct.pack("d", default_timer()) + data + else: + for i in range(startVal, startVal + (packet_size - 8)): + padBytes += [(i & 0xff)] # Keep chars in the 0-255 range + # data = bytes(padBytes) + data = bytearray(padBytes) + + # Calculate the checksum on the data and the dummy header. + myChecksum = checksum(header + data) # Checksum is in network order + + # Now that we have the right checksum, we put that in. It's just easier + # to make up a new header than to stuff it into the dummy. + header = struct.pack( + "!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber + ) + + packet = header + data + + sendTime = default_timer() + + try: + mySocket.sendto(packet, (destIP, 1)) # Port number is irrelevant for ICMP + except socket.error as e: + print("General failure (%s)" % (e.args[1])) + return + + return sendTime + + +# =============================================================================# +def receive_one_ping(mySocket, myID, timeout): + """ + Receive the ping from the socket. Timeout = in ms + """ + timeLeft = timeout / 1000 + + while True: # Loop while waiting for packet or timeout + startedSelect = default_timer() + whatReady = select.select([mySocket], [], [], timeLeft) + howLongInSelect = (default_timer() - startedSelect) + if whatReady[0] == []: # Timeout + return None, 0, 0, 0, 0 + + timeReceived = default_timer() + + recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV) + + ipHeader = recPacket[:20] + iphVersion, iphTypeOfSvc, iphLength, \ + iphID, iphFlags, iphTTL, iphProtocol, \ + iphChecksum, iphSrcIP, iphDestIP = struct.unpack( + "!BBHHHBBHII", ipHeader + ) + + icmpHeader = recPacket[20:28] + icmpType, icmpCode, icmpChecksum, \ + icmpPacketID, icmpSeqNumber = struct.unpack( + "!BBHHH", icmpHeader + ) + + if icmpPacketID == myID: # Our packet + dataSize = len(recPacket) - 28 + # print (len(recPacket.encode())) + return timeReceived, (dataSize + 8), iphSrcIP, icmpSeqNumber, iphTTL + + timeLeft = timeLeft - howLongInSelect + if timeLeft <= 0: + return None, 0, 0, 0, 0 + + +# =============================================================================# +def dump_stats(myStats): + """ + Show stats when pings are done + """ + print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP)) + + if myStats.pktsSent > 0: + myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) / myStats.pktsSent + + print("%d packets transmitted, %d packets received, %0.1f%% packet loss" % ( + myStats.pktsSent, myStats.pktsRcvd, 100.0 * myStats.fracLoss + )) + + if myStats.pktsRcvd > 0: + print("round-trip (ms) min/avg/max = %d/%0.1f/%d" % ( + myStats.minTime, myStats.totTime / myStats.pktsRcvd, myStats.maxTime + )) + + print("") + return + + +# =============================================================================# +def signal_handler(signum, frame): + """ + Handle exit via signals + """ + dump_stats() + print("\n(Terminated with signal %d)\n" % (signum)) + sys.exit(0) + + +# =============================================================================# +def verbose_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, + packet_size=PACKET_SIZE, path_finder=False): + """ + Send >count< ping to >destIP< with the given >timeout< and display + the result. + """ + signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl-C + if hasattr(signal, "SIGBREAK"): + # Handle Ctrl-Break e.g. under Windows + signal.signal(signal.SIGBREAK, signal_handler) + + myStats = MyStats() # Reset the stats + + mySeqNumber = 0 # Starting value + + try: + destIP = socket.gethostbyname(hostname) + print("\nPYTHON PING %s (%s): %d data bytes" % (hostname, destIP, packet_size)) + except socket.gaierror as e: + print("\nPYTHON PING: Unknown host: %s (%s)" % (hostname, e.args[1])) + print() + return + + myStats.thisIP = destIP + + for i in range(count): + delay = do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size) + + if delay == None: + delay = 0 + + mySeqNumber += 1 + + # Pause for the remainder of the MAX_SLEEP period (if applicable) + if (MAX_SLEEP > delay): + time.sleep((MAX_SLEEP - delay) / 1000) + + dump_stats(myStats) + +#=============================================================================# +def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, + packet_size=PACKET_SIZE, path_finder=False): + """ + Same as verbose_ping, but the results are returned as tuple + """ + myStats = MyStats() # Reset the stats + mySeqNumber = 0 # Starting value + + try: + destIP = socket.gethostbyname(hostname) + except socket.gaierror as e: + return 0,0,0,0 + + myStats.thisIP = destIP + + # This will send packet that we dont care about 0.5 seconds before it starts + # acrutally pinging. This is needed in big MAN/LAN networks where you sometimes + # loose the first packet. (while the switches find the way... :/ ) + if path_finder: + fakeStats = MyStats() + do_one(fakeStats, destIP, hostname, timeout, + mySeqNumber, packet_size, quiet=True) + time.sleep(0.5) + + for i in range(count): + delay = do_one(myStats, destIP, hostname, timeout, + mySeqNumber, packet_size, quiet=True) + + if delay == None: + delay = 0 + + mySeqNumber += 1 + + # Pause for the remainder of the MAX_SLEEP period (if applicable) + if (MAX_SLEEP > delay): + time.sleep((MAX_SLEEP - delay)/1000) + + if myStats.pktsSent > 0: + myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)/myStats.pktsSent + if myStats.pktsRcvd > 0: + myStats.avrgTime = myStats.totTime / myStats.pktsRcvd + + # return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost) + return myStats.maxTime, myStats.minTime, myStats.avrgTime, myStats.fracLoss + +# =============================================================================# + + + +#================================================================================ +# Globals +# These are needed because callback functions are used. +# Need to retain state across calls +#================================================================================ +SIZE=(320,240) + +class MyGlobals: + axis_pings = None + ping_x_array = [] + ping_y_array = [] + +g_my_globals = MyGlobals() + +#================================================================================ +# Performs *** PING! *** +#================================================================================ +def run_a_ping_and_graph(): + global g_my_globals # graphs are global so that can be retained across multiple calls to this callback + + #===================== Do the ping =====================# + response = quiet_ping('google.com',timeout=1000) + if response[0] == 0: + ping_time = 1000 + else: + ping_time = response[0] + #===================== Store current ping in historical array =====================# + g_my_globals.ping_x_array.append(len(g_my_globals.ping_x_array)) + g_my_globals.ping_y_array.append(ping_time) + # ===================== Only graph last 100 items =====================# + if len(g_my_globals.ping_x_array) > 100: + x_array = g_my_globals.ping_x_array[-100:] + y_array = g_my_globals.ping_y_array[-100:] + else: + x_array = g_my_globals.ping_x_array + y_array = g_my_globals.ping_y_array + + # ===================== Call graphinc functions =====================# + g_my_globals.axis_ping.clear() # clear before graphing + set_chart_labels() + g_my_globals.axis_ping.plot(x_array,y_array) # graph the ping values + +#================================================================================ +# Function: Set graph titles and Axis labels +# Sets the text for the subplots +# Have to do this in 2 places... initially when creating and when updating +# So, putting into a function so don't have to duplicate code +#================================================================================ +def set_chart_labels(): + global g_my_globals + + g_my_globals.axis_ping.set_xlabel('Time', fontsize=8) + g_my_globals.axis_ping.set_ylabel('Ping (ms)', fontsize=8) + g_my_globals.axis_ping.set_title('Current Ping Duration', fontsize = 8) + +def draw(fig, canvas): + # Magic code that draws the figure onto the Canvas Element's canvas + figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds + figure_w, figure_h = int(figure_w), int(figure_h) + photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) + canvas.create_image(SIZE[0] / 2, SIZE[1] / 2, image=photo) + figure_canvas_agg = FigureCanvasAgg(fig) + figure_canvas_agg.draw() + tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) + return photo + +#================================================================================ +# Function: MAIN +#================================================================================ +def main(): + global g_my_globals + + # define the form layout + layout = [[ sg.Canvas(size=SIZE, background_color='white',key='canvas') , sg.ReadButton('Exit', pad=(0, (210, 0)))]] + + # create the form and show it without the plot + window = sg.Window('Ping Graph', background_color='white', grab_anywhere=True).Layout(layout).Finalize() + + canvas_elem = window.FindElement('canvas') + canvas = canvas_elem.TKCanvas + + fig = plt.figure(figsize=(3.1, 2.25), tight_layout={'pad':0}) + g_my_globals.axis_ping = fig.add_subplot(1,1,1) + plt.rcParams['xtick.labelsize'] = 8 + plt.rcParams['ytick.labelsize'] = 8 + set_chart_labels() + plt.tight_layout() + + while True: + button, values = window.ReadNonBlocking() + if button is 'Exit' or values is None: + exit(0) + + run_a_ping_and_graph() + photo = draw(fig, canvas) + + +if __name__ == '__main__': + main() diff --git a/Demo_Matplotlib_Ping_Graph_Large.py b/Demo_Matplotlib_Ping_Graph_Large.py new file mode 100644 index 000000000..a7328a702 --- /dev/null +++ b/Demo_Matplotlib_Ping_Graph_Large.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import matplotlib.pyplot as plt +import ping +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureCanvasAgg +import matplotlib.backends.tkagg as tkagg +import tkinter as tk + +#================================================================================ +# Globals +# These are needed because callback functions are used. +# Need to retain state across calls +#================================================================================ +class MyGlobals: + axis_pings = None + ping_x_array = [] + ping_y_array = [] + +g_my_globals = MyGlobals() + +#================================================================================ +# Performs *** PING! *** +#================================================================================ +def run_a_ping_and_graph(): + global g_my_globals # graphs are global so that can be retained across multiple calls to this callback + + #===================== Do the ping =====================# + response = ping.quiet_ping('google.com',timeout=1000) + if response[0] == 0: + ping_time = 1000 + else: + ping_time = response[0] + #===================== Store current ping in historical array =====================# + g_my_globals.ping_x_array.append(len(g_my_globals.ping_x_array)) + g_my_globals.ping_y_array.append(ping_time) + # ===================== Only graph last 100 items =====================# + if len(g_my_globals.ping_x_array) > 100: + x_array = g_my_globals.ping_x_array[-100:] + y_array = g_my_globals.ping_y_array[-100:] + else: + x_array = g_my_globals.ping_x_array + y_array = g_my_globals.ping_y_array + + # ===================== Call graphinc functions =====================# + g_my_globals.axis_ping.clear() # clear before graphing + g_my_globals.axis_ping.plot(x_array,y_array) # graph the ping values + +#================================================================================ +# Function: Set graph titles and Axis labels +# Sets the text for the subplots +# Have to do this in 2 places... initially when creating and when updating +# So, putting into a function so don't have to duplicate code +#================================================================================ +def set_chart_labels(): + global g_my_globals + + g_my_globals.axis_ping.set_xlabel('Time') + g_my_globals.axis_ping.set_ylabel('Ping (ms)') + g_my_globals.axis_ping.set_title('Current Ping Duration', fontsize = 12) + +def draw(fig, canvas): + # Magic code that draws the figure onto the Canvas Element's canvas + figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds + figure_w, figure_h = int(figure_w), int(figure_h) + photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) + canvas.create_image(640 / 2, 480 / 2, image=photo) + figure_canvas_agg = FigureCanvasAgg(fig) + figure_canvas_agg.draw() + tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) + return photo + +#================================================================================ +# Function: MAIN +#================================================================================ +def main(): + global g_my_globals + + # define the form layout + layout = [[sg.Text('Animated Ping', size=(40, 1), justification='center', font='Helvetica 20')], + [sg.Canvas(size=(640, 480), key='canvas')], + [sg.ReadButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]] + + # create the form and show it without the plot + window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize() + + canvas_elem = window.FindElement('canvas') + canvas = canvas_elem.TKCanvas + + fig = plt.figure() + g_my_globals.axis_ping = fig.add_subplot(1,1,1) + set_chart_labels() + plt.tight_layout() + + while True: + button, values = window.ReadNonBlocking() + if button is 'Exit' or values is None: + break + + run_a_ping_and_graph() + photo = draw(fig, canvas) + + +if __name__ == '__main__': + main() + + diff --git a/Demo_Media_Player.py b/Demo_Media_Player.py new file mode 100644 index 000000000..1a4e0d5f2 --- /dev/null +++ b/Demo_Media_Player.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +# +# An Async Demonstration of a media player +# Uses button images for a super snazzy look +# See how it looks here: +# https://user-images.githubusercontent.com/13696193/43159403-45c9726e-8f50-11e8-9da0-0d272e20c579.jpg +# +def MediaPlayerGUI(): + background = '#F0F0F0' + # Set the backgrounds the same as the background on the buttons + sg.SetOptions(background_color=background, element_background_color=background) + # Images are located in a subfolder in the Demo Media Player.py folder + image_pause = './ButtonGraphics/Pause.png' + image_restart = './ButtonGraphics/Restart.png' + image_next = './ButtonGraphics/Next.png' + image_exit = './ButtonGraphics/Exit.png' + + # A text element that will be changed to display messages in the GUI + + + # define layout of the rows + layout= [[sg.Text('Media File Player',size=(17,1), font=("Helvetica", 25))], + [sg.Text('', size=(15, 2), font=("Helvetica", 14), key='output')], + [sg.ReadButton('Restart Song', button_color=(background,background), + image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.ReadButton('Pause', button_color=(background,background), + image_filename=image_pause, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.ReadButton('Next', button_color=(background,background), + image_filename=image_next, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.Text(' ' * 2), sg.Button('Exit', button_color=(background,background), + image_filename=image_exit, image_size=(50, 50), image_subsample=2, border_width=0)], + [sg.Text('_'*20)], + [sg.Text(' '*30)], + [ + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15)), + sg.Text(' ' * 2), + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15)), + sg.Text(' ' * 2), + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15))], + [sg.Text(' Bass', font=("Helvetica", 15), size=(9, 1)), + sg.Text('Treble', font=("Helvetica", 15), size=(7, 1)), + sg.Text('Volume', font=("Helvetica", 15), size=(7, 1))] + ] + + # Open a form, note that context manager can't be used generally speaking for async forms + window = sg.Window('Media File Player', auto_size_text=True, default_element_size=(20, 1), + font=("Helvetica", 25), no_titlebar=True).Layout(layout) + # Our event loop + while(True): + # Read the form (this call will not block) + button, values = window.ReadNonBlocking() + if button == 'Exit': + break + # If a button was pressed, display it on the GUI by updating the text element + if button: + window.FindElement('output').Update(button) + +MediaPlayerGUI() + diff --git a/Demo_Menus.py b/Demo_Menus.py new file mode 100644 index 000000000..e88cbe36b --- /dev/null +++ b/Demo_Menus.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI_mod as sg +else: + import PySimpleGUI27 as sg +""" + Demonstration of MENUS! + How do menus work? Like buttons is how. + Check out the variable menu_def for a hint on how to + define menus +""" +def SecondForm(): + + layout = [[sg.Text('The second form is small \nHere to show that opening a window using a window works')], + [sg.OK()]] + + window = sg.Window('Second Form').Layout(layout) + b, v = window.Read() + + +def TestMenus(): + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('LightGreen') + sg.SetOptions(element_padding=(0, 0)) + + # ------ Menu Definition ------ # + menu_def = [['&File', ['&Open', '&Save', '---', 'Properties', 'E&xit' ]], + ['&Edit', ['Paste', ['Special', 'Normal',], 'Undo'],], + ['' + '&Help', '&About...'],] + + # ------ GUI Defintion ------ # + layout = [ + [sg.Menu(menu_def, tearoff=False)], + [sg.Output(size=(60,20))], + [sg.In('Test', key='input', do_not_clear=True)] + ] + + window = sg.Window("Windows-like program", default_element_size=(12, 1), auto_size_text=False, auto_size_buttons=False, + default_button_element_size=(12, 1)).Layout(layout) + + # ------ Loop & Process button menu choices ------ # + while True: + button, values = window.Read() + if button is None or button == 'Exit': + return + print('Button = ', button) + # ------ Process menu choices ------ # + if button == 'About...': + window.Hide() + sg.Popup('About this program','Version 1.0', 'PySimpleGUI rocks...', grab_anywhere=True) + window.UnHide() + elif button == 'Open': + filename = sg.PopupGetFile('file to open', no_window=True) + print(filename) + elif button == 'Properties': + SecondForm() + + + +TestMenus() \ No newline at end of file diff --git a/Demo_NonBlocking_Form.py b/Demo_NonBlocking_Form.py new file mode 100644 index 000000000..0c489c696 --- /dev/null +++ b/Demo_NonBlocking_Form.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import time + +# Window that doen't block +# good for applications with an loop that polls hardware +def StatusOutputExample(): + # Create a text element that will be updated with status information on the GUI itself + # Create the rows + layout = [[sg.Text('Non-blocking GUI with updates')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='output')], + [sg.ReadButton('LED On'), sg.ReadButton('LED Off'), sg.ReadButton('Quit')]] + # Layout the rows of the Window and perform a read. Indicate the Window is non-blocking! + window = sg.Window('Running Timer', auto_size_text=True).Layout(layout) + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your window every now and then or + # else it won't refresh. + # + # your program's main loop + i=0 + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100)) + if button == 'Quit' or values is None: + break + if button == 'LED On': + print('Turning on the LED') + elif button == 'LED Off': + print('Turning off the LED') + + i += 1 + # Your code begins here + time.sleep(.01) + + # Broke out of main loop. Close the window. + window.CloseNonBlocking() + + +def RemoteControlExample(): + + layout = [[sg.Text('Robotics Remote Control')], + [sg.T(' '*10), sg.RealtimeButton('Forward')], + [ sg.RealtimeButton('Left'), sg.T(' '*15), sg.RealtimeButton('Right')], + [sg.T(' '*10), sg.RealtimeButton('Reverse')], + [sg.T('')], + [sg.Quit(button_color=('black', 'orange'))] + ] + + window = sg.Window('Robotics Remote Control', auto_size_text=True).Layout(layout).Finalize() + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your window every now and then or + # else it won't refresh. + # + # your program's main loop + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + if button is not None: + print(button) + if button == 'Quit' or values is None: + break + # time.sleep(.01) + + window.CloseNonBlocking() + + +def main(): + RemoteControlExample() + StatusOutputExample() + sg.Popup('End of non-blocking demonstration') + + +if __name__ == '__main__': + + main() diff --git a/Demo_OpenCV.py b/Demo_OpenCV.py new file mode 100644 index 000000000..84f8331c2 --- /dev/null +++ b/Demo_OpenCV.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import cv2 as cv +from PIL import Image +import tempfile +import os +from sys import exit as exit + +""" +Demo program to open and play a file using OpenCV +Unsure how to get the frames coming from OpenCV into the right format, so saving each frame to +a temp file. Clearly... clearly... this is not the optimal solution and one is being searched for now. + +Until then enjoy it working somewhat slowly. +""" + + +def main(): + # filename = 'C:/Python/MIDIVideo/PlainVideos/- 08-30 Ted Talk/TED Talk Short - Video+.mp4' + filename = sg.PopupGetFile('Filename to play') + if filename is None: + exit(69) + vidFile = cv.VideoCapture(filename) + # ---===--- Get some Stats --- # + num_frames = vidFile.get(cv.CAP_PROP_FRAME_COUNT) + fps = vidFile.get(cv.CAP_PROP_FPS) + + sg.ChangeLookAndFeel('Dark') + + # define the window layout + layout = [[sg.Text('OpenCV Demo', size=(15, 1),pad=((510,0),3), justification='center', font='Helvetica 20')], + [sg.Image(filename='', key='image')], + [sg.Slider(range=(0, num_frames), size=(115, 10), orientation='h', key='slider')], + [sg.ReadButton('Exit', size=(10, 2), pad=((600, 0), 3), font='Helvetica 14')]] + + # create the window and show it without the plot + window = sg.Window('Demo Application - OpenCV Integration', no_titlebar=False, location=(0,0)) + window.Layout(layout) + window.ReadNonBlocking() + + + # ---===--- LOOP through video file by frame --- # + i = 0 + temp_filename = next(tempfile._get_candidate_names()) + '.png' + while vidFile.isOpened(): + button, values = window.ReadNonBlocking() + if button is 'Exit' or values is None: + os.remove(temp_filename) + exit(69) + ret, frame = vidFile.read() + if not ret: # if out of data stop looping + break + + window.FindElement('slider').Update(i) + i += 1 + + with open(temp_filename, 'wb') as f: + Image.fromarray(frame).save(temp_filename, 'PNG') # save the PIL image as file + window.FindElement('image').Update(filename=temp_filename) + + +main() \ No newline at end of file diff --git a/Demo_PDF_Viewer.py b/Demo_PDF_Viewer.py new file mode 100644 index 000000000..5d9b150c5 --- /dev/null +++ b/Demo_PDF_Viewer.py @@ -0,0 +1,189 @@ +""" +@created: 2018-08-19 18:00:00 + +@author: (c) 2018 Jorj X. McKie + +Display a PyMuPDF Document using Tkinter +------------------------------------------------------------------------------- + +Dependencies: +------------- +PyMuPDF, PySimpleGUI > v2.9.0, Tkinter with Tk v8.6+, Python 3 + + +License: +-------- +GNU GPL V3+ + +Description +------------ +Read filename from command line and start display with page 1. +Pages can be directly jumped to, or buttons for paging can be used. +For experimental / demonstration purposes, we have included options to zoom +into the four page quadrants (top-left, bottom-right, etc.). + +We also interpret keyboard events to support paging by PageDown / PageUp +keys as if the resp. buttons were clicked. Similarly, we do not include +a 'Quit' button. Instead, the ESCAPE key can be used, or cancelling the window. + +To improve paging performance, we are not directly creating pixmaps from +pages, but instead from the fitz.DisplayList of the page. A display list +will be stored in a list and looked up by page number. This way, zooming +pixmaps and page re-visits will re-use a once-created display list. + +""" +import sys +import fitz +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +from sys import exit as exit +from binascii import hexlify + +sg.ChangeLookAndFeel('GreenTan') + +if len(sys.argv) == 1: + rc, fname = sg.PopupGetFile('PDF Browser', 'PDF file to open', file_types=(("PDF Files", "*.pdf"),)) + if rc is False: + sg.PopupCancel('Cancelling') + exit(0) +else: + fname = sys.argv[1] + +doc = fitz.open(fname) +page_count = len(doc) + +# storage for page display lists +dlist_tab = [None] * page_count + +title = "PyMuPDF display of '%s', pages: %i" % (fname, page_count) + + +def get_page(pno, zoom=0): + """Return a PNG image for a document page number. If zoom is other than 0, one of the 4 page quadrants are zoomed-in instead and the corresponding clip returned. + + """ + dlist = dlist_tab[pno] # get display list + if not dlist: # create if not yet there + dlist_tab[pno] = doc[pno].getDisplayList() + dlist = dlist_tab[pno] + r = dlist.rect # page rectangle + mp = r.tl + (r.br - r.tl) * 0.5 # rect middle point + mt = r.tl + (r.tr - r.tl) * 0.5 # middle of top edge + ml = r.tl + (r.bl - r.tl) * 0.5 # middle of left edge + mr = r.tr + (r.br - r.tr) * 0.5 # middle of right egde + mb = r.bl + (r.br - r.bl) * 0.5 # middle of bottom edge + mat = fitz.Matrix(2, 2) # zoom matrix + if zoom == 1: # top-left quadrant + clip = fitz.Rect(r.tl, mp) + elif zoom == 4: # bot-right quadrant + clip = fitz.Rect(mp, r.br) + elif zoom == 2: # top-right + clip = fitz.Rect(mt, mr) + elif zoom == 3: # bot-left + clip = fitz.Rect(ml, mb) + if zoom == 0: # total page + pix = dlist.getPixmap(alpha=False) + else: + pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip) + return pix.getPNGData() # return the PNG image + + +window = sg.Window(title, return_keyboard_events=True, use_default_focus=False) + +cur_page = 0 +data = get_page(cur_page) # show page 1 for start +image_elem = sg.Image(data=data) +goto = sg.InputText(str(cur_page + 1), size=(5, 1), do_not_clear=True) + +layout = [ + [ + sg.ReadButton('Next'), + sg.ReadButton('Prev'), + sg.Text('Page:'), + goto, + ], + [ + sg.Text("Zoom:"), + sg.ReadButton('Top-L'), + sg.ReadButton('Top-R'), + sg.ReadButton('Bot-L'), + sg.ReadButton('Bot-R'), + ], + [image_elem], +] + +window.Layout(layout) +my_keys = ("Next", "Next:34", "Prev", "Prior:33", "Top-L", "Top-R", + "Bot-L", "Bot-R", "MouseWheel:Down", "MouseWheel:Up") +zoom_buttons = ("Top-L", "Top-R", "Bot-L", "Bot-R") + +old_page = 0 +old_zoom = 0 # used for zoom on/off +# the zoom buttons work in on/off mode. + +while True: + button, value = window.ReadNonBlocking() + zoom = 0 + force_page = False + if button is None and value is None: + break + if button is None: + continue + + if button in ("Escape:27",): # this spares me a 'Quit' button! + break + # print("hex(button)", hexlify(button.encode())) + if button[0] == chr(13): # surprise: this is 'Enter'! + try: + cur_page = int(value[0]) - 1 # check if valid + while cur_page < 0: + cur_page += page_count + except: + cur_page = 0 # this guy's trying to fool me + goto.Update(str(cur_page + 1)) + # goto.TKStringVar.set(str(cur_page + 1)) + + elif button in ("Next", "Next:34", "MouseWheel:Down"): + cur_page += 1 + elif button in ("Prev", "Prior:33", "MouseWheel:Up"): + cur_page -= 1 + elif button == "Top-L": + zoom = 1 + elif button == "Top-R": + zoom = 2 + elif button == "Bot-L": + zoom = 3 + elif button == "Bot-R": + zoom = 4 + + # sanitize page number + if cur_page >= page_count: # wrap around + cur_page = 0 + while cur_page < 0: # we show conventional page numbers + cur_page += page_count + + # prevent creating same data again + if cur_page != old_page: + zoom = old_zoom = 0 + force_page = True + + if button in zoom_buttons: + if 0 < zoom == old_zoom: + zoom = 0 + force_page = True + + if zoom != old_zoom: + force_page = True + + if force_page: + data = get_page(cur_page, zoom) + image_elem.Update(data=data) + old_page = cur_page + old_zoom = zoom + + # update page number field + if button in my_keys or not value[0]: + goto.Update(str(cur_page + 1)) + # goto.TKStringVar.set(str(cur_page + 1)) diff --git a/Demo_PNG_Viewer.py b/Demo_PNG_Viewer.py new file mode 100644 index 000000000..75aac14af --- /dev/null +++ b/Demo_PNG_Viewer.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import os +from sys import exit as exit + +# Simple Image Browser based on PySimpleGUI + +# Get the folder containing the images from the user +folder = sg.PopupGetFolder('Image folder to open') +if folder is None: + sg.PopupCancel('Cancelling') + exit(0) + +# get list of PNG files in folder +png_files = [folder + '\\' + f for f in os.listdir(folder) if '.png' in f] +filenames_only = [f for f in os.listdir(folder) if '.png' in f] + +if len(png_files) == 0: + sg.Popup('No PNG images in folder') + exit(0) + + +# define menu layout +menu = [['File', ['Open Folder', 'Exit']], ['Help', ['About',]]] + +# define layout, show and read the window +col = [[sg.Text(png_files[0], size=(80, 3), key='filename')], + [sg.Image(filename=png_files[0], key='image')], + [sg.ReadButton('Next', size=(8,2)), sg.ReadButton('Prev', size=(8,2)), + sg.Text('File 1 of {}'.format(len(png_files)), size=(15,1), key='filenum')]] + +col_files = [[sg.Listbox(values=filenames_only, size=(60,30), key='listbox')], + [sg.ReadButton('Read')]] +layout = [[sg.Menu(menu)], [sg.Column(col_files), sg.Column(col)]] +window = sg.Window('Image Browser', return_keyboard_events=True, location=(0,0), use_default_focus=False ).Layout(layout) + +# loop reading the user input and displaying image, filename +i=0 +while True: + + button, values = window.Read() + # --------------------- Button & Keyboard --------------------- + if button is None: + break + elif button in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34') and i < len(png_files)-1: + i += 1 + elif button in ('Prev', 'MouseWheel:Up', 'Up:38', 'Prior:33') and i > 0: + i -= 1 + elif button == 'Exit': + exit(69) + + filename = folder + '/' + values['listbox'][0] if button == 'Read' else png_files[i] + + # ----------------- Menu choices ----------------- + if button == 'Open Folder': + newfolder = sg.PopupGetFolder('New folder', no_window=True) + if newfolder is None: + continue + folder = newfolder + png_files = [folder + '/' + f for f in os.listdir(folder) if '.png' in f] + filenames_only = [f for f in os.listdir(folder) if '.png' in f] + window.FindElement('listbox').Update(values=filenames_only) + window.Refresh() + i = 0 + elif button == 'About': + sg.Popup('Demo PNG Viewer Program', 'Please give PySimpleGUI a try!') + + # update window with new image + window.FindElement('image').Update(filename=filename) + # update window with filename + window.FindElement('filename').Update(filename) + # update page display + window.FindElement('filenum').Update('File {} of {}'.format(i+1, len(png_files))) + diff --git a/Demo_Password_Login.py b/Demo_Password_Login.py new file mode 100644 index 000000000..16a4a840b --- /dev/null +++ b/Demo_Password_Login.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import hashlib +from sys import exit as exit + +""" + Create a secure login for your scripts without having to include your password + in the program. Create an SHA1 hash code for your password using the GUI. Paste into variable in final program + 1. Choose a password + 2. Generate a hash code for your chosen password by running program and entering 'gui' as the password + 3. Type password into the GUI + 4. Copy and paste hash code from GUI into variable named login_password_hash + 5. Run program again and test your login! + 6. Are you paying attention? The first person that can post an issue on GitHub with the + matching password to the hash code in this example gets a $5 PayPal payment +""" + +# Use this GUI to get your password's hash code +def HashGeneratorGUI(): + layout = [[sg.T('Password Hash Generator', size=(30,1), font='Any 15')], + [sg.T('Password'), sg.In(key='password')], + [sg.T('SHA Hash'), sg.In('', size=(40,1), key='hash')], + ] + + window = sg.Window('SHA Generator', auto_size_text=False, default_element_size=(10,1), + text_justification='r', return_keyboard_events=True, grab_anywhere=False).Layout(layout) + + while True: + button, values = window.Read() + if button is None: + exit(69) + + password = values['password'] + try: + password_utf = password.encode('utf-8') + sha1hash = hashlib.sha1() + sha1hash.update(password_utf) + password_hash = sha1hash.hexdigest() + window.FindElement('hash').Update(password_hash) + except: + pass + +# ----------------------------- Paste this code into your program / script ----------------------------- +# determine if a password matches the secret password by comparing SHA1 hash codes +def PasswordMatches(password, hash): + password_utf = password.encode('utf-8') + sha1hash = hashlib.sha1() + sha1hash.update(password_utf) + password_hash = sha1hash.hexdigest() + return password_hash == hash + + +login_password_hash = 'e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4' +password = sg.PopupGetText('Password', password_char='*') +if password == 'gui': # Remove when pasting into your program + HashGeneratorGUI() # Remove when pasting into your program + exit(69) # Remove when pasting into your program +if PasswordMatches(password, login_password_hash): + print('Login SUCCESSFUL') +else: + print('Login FAILED!!') diff --git a/Demo_Pi_LEDs.py b/Demo_Pi_LEDs.py new file mode 100644 index 000000000..bd8991e55 --- /dev/null +++ b/Demo_Pi_LEDs.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +# GUI for switching an LED on and off to GPIO14 + +# GPIO and time library: +import RPi.GPIO as GPIO +import time + +# determine that GPIO numbers are used: +GPIO.setmode(GPIO.BCM) +GPIO.setup(14, GPIO.OUT) + +def SwitchLED(): + varLEDStatus = GPIO.input(14) + varLedStatus = 0 + if varLedStatus == 0: + GPIO.output(14, GPIO.HIGH) + return "LED is switched ON" + else: + GPIO.output(14, GPIO.LOW) + return "LED is switched OFF" + + +def FlashLED(): + for i in range(5): + GPIO.output(14, GPIO.HIGH) + time.sleep(0.5) + GPIO.output(14, GPIO.LOW) + time.sleep(0.5) + +layout = [[sg.T('Raspberry Pi LEDs')], + [sg.T('', size=(14, 1), key='output')], + [sg.ReadButton('Switch LED')], + [sg.ReadButton('Flash LED')], + [sg.Exit()]] + +window = sg.Window('Raspberry Pi GUI', grab_anywhere=False).Layout(layout) + +while True: + button, values = window.Read() + if button is None: + break + + if button is 'Switch LED': + window.FindElement('output').Update(SwitchLED()) + elif button is 'Flash LED': + window.FindElement('output').Update('LED is Flashing') + window.ReadNonBlocking() + FlashLED() + window.FindElement('output').Update('') + +sg.Popup('Done... exiting') diff --git a/Demo_Pi_Robotics.py b/Demo_Pi_Robotics.py new file mode 100644 index 000000000..494dd2008 --- /dev/null +++ b/Demo_Pi_Robotics.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +# Robotics design pattern +# Uses Realtime Buttons to simulate the controls for a robot +# Rather than sending a single click when a button is clicked, Realtime Buttons +# send button presses continuously while the button is pressed down. +# Two examples, one using fancy graphics, one plain. + +def RemoteControlExample(): + # Make a form, but don't use context manager + sg.SetOptions(element_padding=(0,0)) + back ='#eeeeee' + image_forward = 'ButtonGraphics/RobotForward.png' + image_backward = 'ButtonGraphics/RobotBack.png' + image_left = 'ButtonGraphics/RobotLeft.png' + image_right = 'ButtonGraphics/RobotRight.png' + + sg.SetOptions(border_width=0, button_color=('black', back), background_color=back, element_background_color=back, text_element_background_color=back) + + layout = [[sg.Text('Robotics Remote Control')], + [sg.T('', justification='center', size=(19,1), key='status')], + [ sg.RealtimeButton('Forward', image_filename=image_forward, pad=((50,0),0))], + [ sg.RealtimeButton('Left', image_filename=image_left), sg.RealtimeButton('Right', image_filename=image_right, pad=((50,0), 0))], + [ sg.RealtimeButton('Reverse', image_filename=image_backward, pad=((50,0),0))], + [sg.T('')], + [sg.Quit(button_color=('black', 'orange'))]] + + window = sg.Window('Robotics Remote Control', auto_size_text=True, grab_anywhere=False).Layout(layout) + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your form every now and then or + # else it won't refresh. + # + # your program's main loop + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + if button is not None: + window.FindElement('status').Update(button) + else: + window.FindElement('status').Update('') + # if user clicked quit button OR closed the form using the X, then break out of loop + if button == 'Quit' or values is None: + break + + window.CloseNonBlocking() + + +def RemoteControlExample_NoGraphics(): + # Make a form, but don't use context manager + + layout = [[sg.Text('Robotics Remote Control', justification='center')], + [sg.T('', justification='center', size=(19,1), key='status')], + [sg.T(' '*8), sg.RealtimeButton('Forward')], + [ sg.RealtimeButton('Left'), sg.T(' '), sg.RealtimeButton('Right')], + [sg.T(' '*8), sg.RealtimeButton('Reverse')], + [sg.T('')], + [sg.Quit(button_color=('black', 'orange'))]] + # Display form to user + window = sg.Window('Robotics Remote Control', auto_size_text=True, grab_anywhere=False).Layout(layout) + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your form every now and then or + # else it won't refresh. + # + # your program's main loop + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + if button is not None: + window.FindElement('status').Update(button) + else: + window.FindElement('status').Update('') + # if user clicked quit button OR closed the form using the X, then break out of loop + if button == 'Quit' or values is None: + break + + window.CloseNonBlocking() + + + + +# ------------------------------------- main ------------------------------------- +def main(): + RemoteControlExample_NoGraphics() + # Uncomment to get the fancy graphics version. Be sure and download the button images! + RemoteControlExample() + # sg.Popup('End of non-blocking demonstration') + +if __name__ == '__main__': + + main() diff --git a/Demo_Ping_Line_Graph.py b/Demo_Ping_Line_Graph.py new file mode 100644 index 000000000..2395f8857 --- /dev/null +++ b/Demo_Ping_Line_Graph.py @@ -0,0 +1,665 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +from threading import Thread +import time +from sys import exit as exit + +# !/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" + A pure python ping implementation using raw sockets. + + (This is Python 3 port of https://github.com/jedie/python-ping) + (Tested and working with python 2.7, should work with 2.6+) + + Note that ICMP messages can only be sent from processes running as root + (in Windows, you must run this script as 'Administrator'). + + Derived from ping.c distributed in Linux's netkit. That code is + copyright (c) 1989 by The Regents of the University of California. + That code is in turn derived from code written by Mike Muuss of the + US Army Ballistic Research Laboratory in December, 1983 and + placed in the public domain. They have my thanks. + + Bugs are naturally mine. I'd be glad to hear about them. There are + certainly word - size dependencies here. + + Copyright (c) Matthew Dixon Cowles, . + Distributable under the terms of the GNU General Public License + version 2. Provided with no warranties of any sort. + + Original Version from Matthew Dixon Cowles: + -> ftp://ftp.visi.com/users/mdc/ping.py + + Rewrite by Jens Diemer: + -> http://www.python-forum.de/post-69122.html#69122 + + Rewrite by George Notaras: + -> http://www.g-loaded.eu/2009/10/30/python-ping/ + + Enhancements by Martin Falatic: + -> http://www.falatic.com/index.php/39/pinging-with-python + + Enhancements and fixes by Georgi Kolev: + -> http://github.com/jedie/python-ping/ + + Bug fix by Andrejs Rozitis: + -> http://github.com/rozitis/python-ping/ + + Revision history + ~~~~~~~~~~~~~~~~ + May 1, 2014 + ----------- + Little modifications by Mohammad Emami + - Added Python 3 support. For now this project will just support + python 3.x + - Tested with python 3.3 + - version was upped to 0.6 + + March 19, 2013 + -------------- + * Fixing bug to prevent divide by 0 during run-time. + + January 26, 2012 + ---------------- + * Fixing BUG #4 - competability with python 2.x [tested with 2.7] + - Packet data building is different for 2.x and 3.x. + 'cose of the string/bytes difference. + * Fixing BUG #10 - the multiple resolv issue. + - When pinging domain names insted of hosts (for exmaple google.com) + you can get different IP every time you try to resolv it, we should + resolv the host only once and stick to that IP. + * Fixing BUGs #3 #10 - Doing hostname resolv only once. + * Fixing BUG #14 - Removing all 'global' stuff. + - You should not use globul! Its bad for you...and its not thread safe! + * Fix - forcing the use of different times on linux/windows for + more accurate mesurments. (time.time - linux/ time.clock - windows) + * Adding quiet_ping function - This way we'll be able to use this script + as external lib. + * Changing default timeout to 3s. (1second is not enought) + * Switching data syze to packet size. It's easyer for the user to ignore the + fact that the packet headr is 8b and the datasize 64 will make packet with + size 72. + + October 12, 2011 + -------------- + Merged updates from the main project + -> https://github.com/jedie/python-ping + + September 12, 2011 + -------------- + Bugfixes + cleanup by Jens Diemer + Tested with Ubuntu + Windows 7 + + September 6, 2011 + -------------- + Cleanup by Martin Falatic. Restored lost comments and docs. Improved + functionality: constant time between pings, internal times consistently + use milliseconds. Clarified annotations (e.g., in the checksum routine). + Using unsigned data in IP & ICMP header pack/unpack unless otherwise + necessary. Signal handling. Ping-style output formatting and stats. + + August 3, 2011 + -------------- + Ported to py3k by Zach Ware. Mostly done by 2to3; also minor changes to + deal with bytes vs. string changes (no more ord() in checksum() because + >source_string< is actually bytes, added .encode() to data in + send_one_ping()). That's about it. + + March 11, 2010 + -------------- + changes by Samuel Stauffer: + - replaced time.clock with default_timer which is set to + time.clock on windows and time.time on other systems. + + November 8, 2009 + ---------------- + Improved compatibility with GNU/Linux systems. + + Fixes by: + * George Notaras -- http://www.g-loaded.eu + Reported by: + * Chris Hallman -- http://cdhallman.blogspot.com + + Changes in this release: + - Re-use time.time() instead of time.clock(). The 2007 implementation + worked only under Microsoft Windows. Failed on GNU/Linux. + time.clock() behaves differently under the two OSes[1]. + + [1] http://docs.python.org/library/time.html#time.clock + + May 30, 2007 + ------------ + little rewrite by Jens Diemer: + - change socket asterisk import to a normal import + - replace time.time() with time.clock() + - delete "return None" (or change to "return" only) + - in checksum() rename "str" to "source_string" + + December 4, 2000 + ---------------- + Changed the struct.pack() calls to pack the checksum and ID as + unsigned. My thanks to Jerome Poincheval for the fix. + + November 22, 1997 + ----------------- + Initial hack. Doesn't do much, but rather than try to guess + what features I (or others) will want in the future, I've only + put in what I need now. + + December 16, 1997 + ----------------- + For some reason, the checksum bytes are in the wrong order when + this is run under Solaris 2.X for SPARC but it works right under + Linux x86. Since I don't know just what's wrong, I'll swap the + bytes always and then do an htons(). + + =========================================================================== + IP header info from RFC791 + -> http://tools.ietf.org/html/rfc791) + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |Version| IHL |Type of Service| Total Length | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Identification |Flags| Fragment Offset | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Time to Live | Protocol | Header Checksum | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Source Address | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Destination Address | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Options | Padding | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + =========================================================================== + ICMP Echo / Echo Reply Message header info from RFC792 + -> http://tools.ietf.org/html/rfc792 + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Type | Code | Checksum | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Identifier | Sequence Number | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Data ... + +-+-+-+-+- + + =========================================================================== + ICMP parameter info: + -> http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml + + =========================================================================== + An example of ping's typical output: + + PING heise.de (193.99.144.80): 56 data bytes + 64 bytes from 193.99.144.80: icmp_seq=0 ttl=240 time=127 ms + 64 bytes from 193.99.144.80: icmp_seq=1 ttl=240 time=127 ms + 64 bytes from 193.99.144.80: icmp_seq=2 ttl=240 time=126 ms + 64 bytes from 193.99.144.80: icmp_seq=3 ttl=240 time=126 ms + 64 bytes from 193.99.144.80: icmp_seq=4 ttl=240 time=127 ms + + ----heise.de PING Statistics---- + 5 packets transmitted, 5 packets received, 0.0% packet loss + round-trip (ms) min/avg/max/med = 126/127/127/127 + + =========================================================================== +""" + +# =============================================================================# +import argparse +import os, sys, socket, struct, select, time, signal + +__description__ = 'A pure python ICMP ping implementation using raw sockets.' + +if sys.platform == "win32": + # On Windows, the best timer is time.clock() + default_timer = time.clock +else: + # On most other platforms the best timer is time.time() + default_timer = time.time + +NUM_PACKETS = 3 +PACKET_SIZE = 64 +WAIT_TIMEOUT = 3.0 + +# =============================================================================# +# ICMP parameters + +ICMP_ECHOREPLY = 0 # Echo reply (per RFC792) +ICMP_ECHO = 8 # Echo request (per RFC792) +ICMP_MAX_RECV = 2048 # Max size of incoming buffer + +MAX_SLEEP = 1000 + + +class MyStats: + thisIP = "0.0.0.0" + pktsSent = 0 + pktsRcvd = 0 + minTime = 999999999 + maxTime = 0 + totTime = 0 + avrgTime = 0 + fracLoss = 1.0 + + +myStats = MyStats # NOT Used globally anymore. + + +# =============================================================================# +def checksum(source_string): + """ + A port of the functionality of in_cksum() from ping.c + Ideally this would act on the string as a series of 16-bit ints (host + packed), but this works. + Network data is big-endian, hosts are typically little-endian + """ + countTo = (int(len(source_string) / 2)) * 2 + sum = 0 + count = 0 + + # Handle bytes in pairs (decoding as short ints) + loByte = 0 + hiByte = 0 + while count < countTo: + if (sys.byteorder == "little"): + loByte = source_string[count] + hiByte = source_string[count + 1] + else: + loByte = source_string[count + 1] + hiByte = source_string[count] + try: # For Python3 + sum = sum + (hiByte * 256 + loByte) + except: # For Python2 + sum = sum + (ord(hiByte) * 256 + ord(loByte)) + count += 2 + + # Handle last byte if applicable (odd-number of bytes) + # Endianness should be irrelevant in this case + if countTo < len(source_string): # Check for odd length + loByte = source_string[len(source_string) - 1] + try: # For Python3 + sum += loByte + except: # For Python2 + sum += ord(loByte) + + sum &= 0xffffffff # Truncate sum to 32 bits (a variance from ping.c, which + # uses signed ints, but overflow is unlikely in ping) + + sum = (sum >> 16) + (sum & 0xffff) # Add high 16 bits to low 16 bits + sum += (sum >> 16) # Add carry from above (if any) + answer = ~sum & 0xffff # Invert and truncate to 16 bits + answer = socket.htons(answer) + + return answer + + +# =============================================================================# +def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False): + """ + Returns either the delay (in ms) or None on timeout. + """ + delay = None + + try: # One could use UDP here, but it's obscure + mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) + except socket.error as e: + print("failed. (socket error: '%s')" % e.args[1]) + raise # raise the original error + + my_ID = os.getpid() & 0xFFFF + + sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, packet_size) + if sentTime == None: + mySocket.close() + return delay + + myStats.pktsSent += 1 + + recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout) + + mySocket.close() + + if recvTime: + delay = (recvTime - sentTime) * 1000 + if not quiet: + print("%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms" % ( + dataSize, socket.inet_ntoa(struct.pack("!I", iphSrcIP)), icmpSeqNumber, iphTTL, delay) + ) + myStats.pktsRcvd += 1 + myStats.totTime += delay + if myStats.minTime > delay: + myStats.minTime = delay + if myStats.maxTime < delay: + myStats.maxTime = delay + else: + delay = None + print("Request timed out.") + + return delay + + +# =============================================================================# +def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size): + """ + Send one ping to the given >destIP<. + """ + # destIP = socket.gethostbyname(destIP) + + # Header is type (8), code (8), checksum (16), id (16), sequence (16) + # (packet_size - 8) - Remove header size from packet size + myChecksum = 0 + + # Make a dummy heder with a 0 checksum. + header = struct.pack( + "!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber + ) + + padBytes = [] + startVal = 0x42 + # 'cose of the string/byte changes in python 2/3 we have + # to build the data differnely for different version + # or it will make packets with unexpected size. + if sys.version[:1] == '2': + bytes = struct.calcsize("d") + data = ((packet_size - 8) - bytes) * "Q" + data = struct.pack("d", default_timer()) + data + else: + for i in range(startVal, startVal + (packet_size - 8)): + padBytes += [(i & 0xff)] # Keep chars in the 0-255 range + # data = bytes(padBytes) + data = bytearray(padBytes) + + # Calculate the checksum on the data and the dummy header. + myChecksum = checksum(header + data) # Checksum is in network order + + # Now that we have the right checksum, we put that in. It's just easier + # to make up a new header than to stuff it into the dummy. + header = struct.pack( + "!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber + ) + + packet = header + data + + sendTime = default_timer() + + try: + mySocket.sendto(packet, (destIP, 1)) # Port number is irrelevant for ICMP + except socket.error as e: + print("General failure (%s)" % (e.args[1])) + return + + return sendTime + + +# =============================================================================# +def receive_one_ping(mySocket, myID, timeout): + """ + Receive the ping from the socket. Timeout = in ms + """ + timeLeft = timeout / 1000 + + while True: # Loop while waiting for packet or timeout + startedSelect = default_timer() + whatReady = select.select([mySocket], [], [], timeLeft) + howLongInSelect = (default_timer() - startedSelect) + if whatReady[0] == []: # Timeout + return None, 0, 0, 0, 0 + + timeReceived = default_timer() + + recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV) + + ipHeader = recPacket[:20] + iphVersion, iphTypeOfSvc, iphLength, \ + iphID, iphFlags, iphTTL, iphProtocol, \ + iphChecksum, iphSrcIP, iphDestIP = struct.unpack( + "!BBHHHBBHII", ipHeader + ) + + icmpHeader = recPacket[20:28] + icmpType, icmpCode, icmpChecksum, \ + icmpPacketID, icmpSeqNumber = struct.unpack( + "!BBHHH", icmpHeader + ) + + if icmpPacketID == myID: # Our packet + dataSize = len(recPacket) - 28 + # print (len(recPacket.encode())) + return timeReceived, (dataSize + 8), iphSrcIP, icmpSeqNumber, iphTTL + + timeLeft = timeLeft - howLongInSelect + if timeLeft <= 0: + return None, 0, 0, 0, 0 + + +# =============================================================================# +def dump_stats(myStats): + """ + Show stats when pings are done + """ + print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP)) + + if myStats.pktsSent > 0: + myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) / myStats.pktsSent + + print("%d packets transmitted, %d packets received, %0.1f%% packet loss" % ( + myStats.pktsSent, myStats.pktsRcvd, 100.0 * myStats.fracLoss + )) + + if myStats.pktsRcvd > 0: + print("round-trip (ms) min/avg/max = %d/%0.1f/%d" % ( + myStats.minTime, myStats.totTime / myStats.pktsRcvd, myStats.maxTime + )) + + print("") + return + + +# =============================================================================# +def signal_handler(signum, frame): + """ + Handle exit via signals + """ + dump_stats() + print("\n(Terminated with signal %d)\n" % (signum)) + sys.exit(0) + + +# =============================================================================# +def verbose_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, + packet_size=PACKET_SIZE, path_finder=False): + """ + Send >count< ping to >destIP< with the given >timeout< and display + the result. + """ + signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl-C + if hasattr(signal, "SIGBREAK"): + # Handle Ctrl-Break e.g. under Windows + signal.signal(signal.SIGBREAK, signal_handler) + + myStats = MyStats() # Reset the stats + + mySeqNumber = 0 # Starting value + + try: + destIP = socket.gethostbyname(hostname) + print("\nPYTHON PING %s (%s): %d data bytes" % (hostname, destIP, packet_size)) + except socket.gaierror as e: + print("\nPYTHON PING: Unknown host: %s (%s)" % (hostname, e.args[1])) + print() + return + + myStats.thisIP = destIP + + for i in range(count): + delay = do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size) + + if delay == None: + delay = 0 + + mySeqNumber += 1 + + # Pause for the remainder of the MAX_SLEEP period (if applicable) + if (MAX_SLEEP > delay): + time.sleep((MAX_SLEEP - delay) / 1000) + + dump_stats(myStats) + + +# =============================================================================# +def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, + packet_size=PACKET_SIZE, path_finder=False): + """ + Same as verbose_ping, but the results are returned as tuple + """ + myStats = MyStats() # Reset the stats + mySeqNumber = 0 # Starting value + + try: + destIP = socket.gethostbyname(hostname) + except socket.gaierror as e: + return False + + myStats.thisIP = destIP + + # This will send packet that we dont care about 0.5 seconds before it starts + # acrutally pinging. This is needed in big MAN/LAN networks where you sometimes + # loose the first packet. (while the switches find the way... :/ ) + if path_finder: + fakeStats = MyStats() + do_one(fakeStats, destIP, hostname, timeout, + mySeqNumber, packet_size, quiet=True) + time.sleep(0.5) + + for i in range(count): + delay = do_one(myStats, destIP, hostname, timeout, + mySeqNumber, packet_size, quiet=True) + + if delay == None: + delay = 0 + + mySeqNumber += 1 + + # Pause for the remainder of the MAX_SLEEP period (if applicable) + if (MAX_SLEEP > delay): + time.sleep((MAX_SLEEP - delay) / 1000) + + if myStats.pktsSent > 0: + myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) / myStats.pktsSent + if myStats.pktsRcvd > 0: + myStats.avrgTime = myStats.totTime / myStats.pktsRcvd + + # return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost) + return myStats.maxTime, myStats.minTime, myStats.avrgTime, myStats.fracLoss + + +# =============================================================================# +def main(): + parser = argparse.ArgumentParser(description=__description__) + parser.add_argument('-q', '--quiet', action='store_true', + help='quiet output') + parser.add_argument('-c', '--count', type=int, default=NUM_PACKETS, + help=('number of packets to be sent ' + '(default: %(default)s)')) + parser.add_argument('-W', '--timeout', type=float, default=WAIT_TIMEOUT, + help=('time to wait for a response in seoncds ' + '(default: %(default)s)')) + parser.add_argument('-s', '--packet-size', type=int, default=PACKET_SIZE, + help=('number of data bytes to be sent ' + '(default: %(default)s)')) + parser.add_argument('destination') + # args = parser.parse_args() + + ping = verbose_ping + # if args.quiet: + # ping = quiet_ping + ping('Google.com', timeout=1000) + # ping(args.destination, timeout=args.timeout*1000, count=args.count, + # packet_size=args.packet_size) + + +# set coordinate system +canvas_right = 300 +canvas_left = 0 +canvas_top = 0 +canvas_bottom = 300 +# define the coordinates you'll use for your graph +x_right = 100 +x_left = 0 +y_bottom = 0 +y_top = 500 + +# globale used to communicate with thread.. yea yea... it's working fine +g_exit = False +g_response_time = None + +def ping_thread(args): + global g_exit, g_response_time + + while not g_exit: + g_response_time = quiet_ping('google.com', timeout=1000) + + +def convert_xy_to_canvas_xy(x_in,y_in): + scale_x = (canvas_right - canvas_left) / (x_right - x_left) + scale_y = (canvas_top - canvas_bottom) / (y_top - y_bottom) + new_x = canvas_left + scale_x * (x_in - x_left) + new_y = canvas_bottom + scale_y * (y_in - y_bottom) + return new_x, new_y + + + +# start ping measurement thread +thread = Thread(target=ping_thread, args=(None,)) +thread.start() + +layout = [ [sg.T('Ping times to Google.com', font='Any 18')], + [sg.Canvas(size=(canvas_right, canvas_bottom), background_color='white', key='canvas')], + [sg.Quit()] ] + +window = sg.Window('Ping Times To Google.com', grab_anywhere=True).Layout(layout).Finalize() + +canvas = window.FindElement('canvas').TKCanvas + +prev_response_time = None +i=0 +prev_x, prev_y = canvas_left, canvas_bottom +while True: + time.sleep(.2) + + button, values = window.ReadNonBlocking() + if button == 'Quit' or values is None: + break + + if g_response_time is None or prev_response_time == g_response_time: + continue + try: + new_x, new_y = convert_xy_to_canvas_xy(i, g_response_time[0]) + except: continue + + prev_response_time = g_response_time + canvas.create_line(prev_x, prev_y, new_x, new_y, width=1, fill='black') + prev_x, prev_y = new_x, new_y + if i >= x_right: + i = 0 + prev_x = prev_y = last_x = last_y = 0 + canvas.delete('all') + else: i += 1 + +# tell thread we're done. wait for thread to exit +g_exit = True +thread.join() + + +exit(69) \ No newline at end of file diff --git a/Demo_Pong.py b/Demo_Pong.py new file mode 100644 index 000000000..2e8b5cd2a --- /dev/null +++ b/Demo_Pong.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import random +import time +from sys import exit as exit + + +""" + Pong code supplied by Daniel Young (Neonzz) + Modified. Original code: https://www.pygame.org/project/3649/5739 +""" + +class Ball: + def __init__(self, canvas, bat, bat2, color): + self.canvas = canvas + self.bat = bat + self.bat2 = bat2 + self.playerScore = 0 + self.player1Score = 0 + self.drawP1 = None + self.drawP = None + self.id = self.canvas.create_oval(10, 10, 35, 35, fill=color) + self.canvas.move(self.id, 327, 220) + self.canvas_height = self.canvas.winfo_height() + self.canvas_width = self.canvas.winfo_width() + self.x = random.choice([-2.5, 2.5]) + self.y = -2.5 + + def checkwin(self): + winner = None + if self.playerScore >= 10: + winner = 'Player left wins' + if self.player1Score >= 10: + winner = 'Player Right' + return winner + + + def updatep(self, val): + self.canvas.delete(self.drawP) + self.drawP = self.canvas.create_text(170, 50, font=('freesansbold.ttf', 40), text=str(val), fill='white') + + def updatep1(self, val): + self.canvas.delete(self.drawP1) + self.drawP1 = self.canvas.create_text(550, 50, font=('freesansbold.ttf', 40), text=str(val), fill='white') + + def hit_bat(self, pos): + bat_pos = self.canvas.coords(self.bat.id) + if pos[2] >= bat_pos[0] and pos[0] <= bat_pos[2]: + if pos[3] >= bat_pos[1] and pos[3] <= bat_pos[3]: + return True + return False + + def hit_bat2(self, pos): + bat_pos = self.canvas.coords(self.bat2.id) + if pos[2] >= bat_pos[0] and pos[0] <= bat_pos[2]: + if pos[3] >= bat_pos[1] and pos[3] <= bat_pos[3]: + return True + return False + + def draw(self): + self.canvas.move(self.id, self.x, self.y) + pos = self.canvas.coords(self.id) + if pos[1] <= 0: + self.y = 4 + if pos[3] >= self.canvas_height: + self.y = -4 + if pos[0] <= 0: + self.player1Score += 1 + self.canvas.move(self.id, 327, 220) + self.x = 4 + self.updatep1(self.player1Score) + if pos[2] >= self.canvas_width: + self.playerScore += 1 + self.canvas.move(self.id, -327, -220) + self.x = -4 + self.updatep(self.playerScore) + if self.hit_bat(pos): + self.x = 4 + if self.hit_bat2(pos): + self.x = -4 + + +class pongbat(): + def __init__(self, canvas, color): + self.canvas = canvas + self.id = self.canvas.create_rectangle(40, 200, 25, 310, fill=color) + self.canvas_height = self.canvas.winfo_height() + self.canvas_width = self.canvas.winfo_width() + self.y = 0 + + def up(self, evt): + self.y = -5 + + def down(self, evt): + self.y = 5 + + def draw(self): + self.canvas.move(self.id, 0, self.y) + pos = self.canvas.coords(self.id) + if pos[1] <= 0: + self.y = 0 + if pos[3] >= 400: + self.y = 0 + + +class pongbat2(): + def __init__(self, canvas, color): + self.canvas = canvas + self.id = self.canvas.create_rectangle(680, 200, 660, 310, fill=color) + self.canvas_height = self.canvas.winfo_height() + self.canvas_width = self.canvas.winfo_width() + self.y = 0 + + def up(self, evt): + self.y = -5 + + def down(self, evt): + self.y = 5 + + def draw(self): + self.canvas.move(self.id, 0, self.y) + pos = self.canvas.coords(self.id) + if pos[1] <= 0: + self.y = 0 + if pos[3] >= 400: + self.y = 0 + + +def pong(): + # ------------- Define GUI layout ------------- + layout = [[sg.Canvas(size=(700, 400), background_color='black', key='canvas')], + [sg.T(''), sg.ReadButton('Quit')]] + # ------------- Create window ------------- + window = sg.Window('The Classic Game of Pong', return_keyboard_events=True).Layout(layout).Finalize() + # window.Finalize() # TODO Replace with call to window.Finalize once code released + + # ------------- Get the tkinter Canvas we're drawing on ------------- + canvas = window.FindElement('canvas').TKCanvas + + # ------------- Create line down center, the bats and ball ------------- + canvas.create_line(350, 0, 350, 400, fill='white') + bat1 = pongbat(canvas, 'white') + bat2 = pongbat2(canvas, 'white') + ball1 = Ball(canvas, bat1, bat2, 'green') + + # ------------- Event Loop ------------- + while True: + # ------------- Draw ball and bats ------------- + ball1.draw() + bat1.draw() + bat2.draw() + + # ------------- Read the form, get keypresses ------------- + button, values = window.ReadNonBlocking() + # ------------- If quit ------------- + if button is None and values is None or button == 'Quit': + exit(69) + # ------------- Keypresses ------------- + if button is not None: + if button.startswith('Up'): + bat2.up(2) + elif button.startswith('Down'): + bat2.down(2) + elif button == 'w': + bat1.up(1) + elif button == 's': + bat1.down(1) + + if ball1.checkwin(): + sg.Popup('Game Over', ball1.checkwin() + ' won!!') + break + + + # ------------- Bottom of loop, delay between animations ------------- + # time.sleep(.01) + canvas.after(10) + +if __name__ == '__main__': + pong() + + + diff --git a/Demo_Popups.py b/Demo_Popups.py new file mode 100644 index 000000000..c55a55cd7 --- /dev/null +++ b/Demo_Popups.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +# Here, have some windows on me.... +[sg.PopupNoWait(location=(500+100*x,500)) for x in range(10)] + +answer = sg.PopupYesNo('Do not worry about all those open windows... they will disappear at the end', 'Are you OK with that?') + +if answer == 'No': + sg.PopupCancel('OK, we will destroy those windows as soon as you close this window') + sys.exit() + +sg.PopupNonBlocking('Your answer was',answer, location=(1000,600)) + +text = sg.PopupGetText('This is a call to PopopGetText', location=(1000,200)) +sg.PopupGetFile('Get file') +sg.PopupGetFolder('Get folder') + + +sg.Popup('Simple popup') + +sg.PopupNoTitlebar('No titlebar') +sg.PopupNoBorder('No border') +sg.PopupNoFrame('No frame') +# sg.PopupNoButtons('No Buttons') # don't mix with non-blocking... disaster ahead... +sg.PopupCancel('Cancel') +sg.PopupOKCancel('OK Cancel') +sg.PopupAutoClose('Autoclose') diff --git a/Demo_Progress_Meters.py b/Demo_Progress_Meters.py new file mode 100644 index 000000000..0fd70e241 --- /dev/null +++ b/Demo_Progress_Meters.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +from time import sleep +from sys import exit as exit + + +""" + Demonstration of simple and multiple OneLineProgressMeter's + + Shows how 2 progress meters can be running at the same time. + Note -- If the user wants to cancel a meter, it's important to use the "Cancel" button, not the X + If the software determined that a meter should be cancelled early, + calling OneLineProgresMeterCancel(key) will cancel the meter with the matching key +""" + +# sg.ChangeLookAndFeel('Dark') + + +""" + The simple case is that you want to add a single meter to your code. The one-line solution +""" + +def DemoOneLineProgressMeter(): + # Display a progress meter. Allow user to break out of loop using cancel button + for i in range(1000): + if not sg.OneLineProgressMeter('My 1-line progress meter', i+1, 1000, 'meter key' ): + break + + + layout = [ + [sg.T('One-Line Progress Meter Demo', font=('Any 18'))], + [sg.T('Outer Loop Count', size=(15,1), justification='r'), sg.In(default_text='100', size=(5,1), key='CountOuter', do_not_clear=True), + sg.T('Delay'), sg.In(default_text='10', key='TimeOuter', size=(5,1), do_not_clear=True), sg.T('ms')], + [sg.T('Inner Loop Count', size=(15,1), justification='r'), sg.In(default_text='100', size=(5,1), key='CountInner', do_not_clear=True) , + sg.T('Delay'), sg.In(default_text='10', key='TimeInner', size=(5,1), do_not_clear=True), sg.T('ms')], + [sg.Button('Show', pad=((0,0), 3), bind_return_key=True), sg.T('me the meters!')] + ] + + window = sg.Window('One-Line Progress Meter Demo').Layout(layout) + + while True: + button, values = window.Read() + if button is None: + break + if button == 'Show': + max_outer = int(values['CountOuter']) + max_inner = int(values['CountInner']) + delay_inner = int(values['TimeInner']) + delay_outer = int(values['TimeOuter']) + for i in range(max_outer): + if not sg.OneLineProgressMeter('Outer Loop', i+1, max_outer, 'outer'): + break + sleep(delay_outer/1000) + for j in range(max_inner): + if not sg.OneLineProgressMeter('Inner Loop', j+1, max_inner, 'inner'): + break + sleep(delay_inner/1000) + +''' + Make your own progress meter! + Embed the meter right into your window +''' + +def CustomMeter(): + # layout the form + layout = [[sg.Text('A custom progress meter')], + [sg.ProgressBar(10000, orientation='h', size=(20,20), key='progress')], + [sg.Cancel()]] + + # create the form` + window = sg.Window('Custom Progress Meter').Layout(layout) + progress_bar = window.FindElement('progress') + # loop that would normally do something useful + for i in range(10000): + # check to see if the cancel button was clicked and exit loop if clicked + button, values = window.ReadNonBlocking() + if button == 'Cancel' or values == None: + break + # update bar with loop value +1 so that bar eventually reaches the maximum + progress_bar.UpdateBar(i+1) + # done with loop... need to destroy the window as it's still open + window.CloseNonBlocking() + +CustomMeter() +DemoOneLineProgressMeter() \ No newline at end of file diff --git a/Demo_Script_Launcher.py b/Demo_Script_Launcher.py new file mode 100644 index 000000000..088aa5fcd --- /dev/null +++ b/Demo_Script_Launcher.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import glob +import ntpath +import subprocess + +LOCATION_OF_YOUR_SCRIPTS = '' + +# Execute the command. Will not see the output from the command until it completes. +def execute_command_blocking(command, *args): + expanded_args = [] + for a in args: + expanded_args.append(a) + # expanded_args += a + try: + sp = subprocess.Popen([command,expanded_args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = sp.communicate() + if out: + print(out.decode("utf-8")) + if err: + print(err.decode("utf-8")) + except: + out = '' + return out + +# Executes command and immediately returns. Will not see anything the script outputs +def execute_command_nonblocking(command, *args): + expanded_args = [] + for a in args: + expanded_args += a + try: + sp = subprocess.Popen([command,expanded_args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + except: pass + +def Launcher2(): + sg.ChangeLookAndFeel('GreenTan') + window = sg.Window('Script launcher') + + filelist = glob.glob(LOCATION_OF_YOUR_SCRIPTS+'*.py') + namesonly = [] + for file in filelist: + namesonly.append(ntpath.basename(file)) + + layout = [ + [sg.Listbox(values=namesonly, size=(30, 19), select_mode=sg.SELECT_MODE_EXTENDED, key='demolist'), sg.Output(size=(88, 20), font='Courier 10')], + [sg.Checkbox('Wait for program to complete', default=False, key='wait')], + [sg.ReadButton('Run'), sg.ReadButton('Shortcut 1'), sg.ReadButton('Fav Program'), sg.Button('EXIT')], + ] + + window.Layout(layout) + + # ---===--- Loop taking in user input and using it to query HowDoI --- # + while True: + (button, value) = window.Read() + if button in ('EXIT', None): + break # exit button clicked + if button in ('Shortcut 1', 'Fav Program'): + print('Quickly launch your favorite programs using these shortcuts') + print('Or copy files to your github folder. Or anything else you type on the command line') + # copyfile(source, dest) + elif button is 'Run': + for index, file in enumerate(value['demolist']): + print('Launching %s'%file) + window.Refresh() # make the print appear immediately + if value['wait']: + execute_command_blocking(LOCATION_OF_YOUR_SCRIPTS + file) + else: + execute_command_nonblocking(LOCATION_OF_YOUR_SCRIPTS + file) + + +if __name__ == '__main__': + Launcher2() + diff --git a/Demo_Script_Parameters.py b/Demo_Script_Parameters.py new file mode 100644 index 000000000..93dfeb6b4 --- /dev/null +++ b/Demo_Script_Parameters.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + + +''' +Quickly add a GUI to your script! + +This simple script shows a 1-line-GUI addition to a typical Python command line script. + +Previously this script accepted 1 parameter on the command line. When executed, that +parameter is read into the variable fname. + +The 1-line-GUI shows a form that allows the user to browse to find the filename. The GUI +stores the result in the variable fname, just like the command line parsing did. +''' + +if len(sys.argv) == 1: + button, (fname,) = sg.Window('My Script').LayoutAndRead([[sg.T('Document to open')], + [sg.In(), sg.FileBrowse()], + [sg.Open(), sg.Cancel()]]) +else: + fname = sys.argv[1] + +if not fname: + sg.Popup("Cancel", "No filename supplied") + raise SystemExit("Cancelling: no filename supplied") diff --git a/Demo_Spinner_Compound_Element.py b/Demo_Spinner_Compound_Element.py new file mode 100644 index 000000000..219149bd3 --- /dev/null +++ b/Demo_Spinner_Compound_Element.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +""" + Demo of how to combine elements into your own custom element +""" + +sg.SetOptions(element_padding=(0,0)) +# sg.ChangeLookAndFeel('Dark') +# --- Define our "Big-Button-Spinner" compound element. Has 2 buttons and an input field --- # +NewSpinner = [sg.ReadButton('-', size=(2,1), font='Any 12'), + sg.In('0', size=(2,1), font='Any 14', justification='r', key='spin'), + sg.ReadButton('+', size=(2,1), font='Any 12')] +# --- Define Window --- # +layout = [ + [sg.Text('Spinner simulation')], + NewSpinner, + [sg.T('')], + [sg.Ok()] + ] + +window = sg.Window('Spinner simulation').Layout(layout) + +# --- Event Loop --- # +counter = 0 +while True: + button, value = window.Read() + + if button == 'Ok' or button is None: # be nice to your user, always have an exit from your form + break + + # --- do spinner stuff --- # + counter += 1 if button =='+' else -1 if button == '-' else 0 + window.FindElement('spin').Update(counter) diff --git a/Demo_Super_Simple_Form.py b/Demo_Super_Simple_Form.py new file mode 100644 index 000000000..df7575a2e --- /dev/null +++ b/Demo_Super_Simple_Form.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +""" + Simple Form showing how to use keys on your input fields +""" + +layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText('1', key='name')], + [sg.Text('Address', size=(15, 1)), sg.InputText('2', key='address')], + [sg.Text('Phone', size=(15, 1)), sg.InputText('3', key='phone')], + [sg.Submit(), sg.Cancel()] + ] + +window = sg.Window('Simple Data Entry Window').Layout(layout) +button, values = window.Read() + +sg.Popup(button, values, values['name'], values['address'], values['phone']) \ No newline at end of file diff --git a/Demo_Table_CSV.py b/Demo_Table_CSV.py new file mode 100644 index 000000000..ae4e9423f --- /dev/null +++ b/Demo_Table_CSV.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import csv + + +def table_example(): + filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),)) + # --- populate table with file contents --- # + if filename == '': + sys.exit(69) + data = [] + header_list = [] + button = sg.PopupYesNo('Does this file have column names already?') + if filename is not None: + with open(filename, "r") as infile: + reader = csv.reader(infile) + if button == 'Yes': + header_list = next(reader) + try: + data = list(reader) # read everything else into a list of rows + if button == 'No': + header_list = ['column' + str(x) for x in range(len(data[0]))] + except: + sg.PopupError('Error reading file') + sys.exit(69) + sg.SetOptions(element_padding=(0, 0)) + + col_layout = [[sg.Table(values=data, headings=header_list, max_col_width=25, + auto_size_columns=True, justification='right', size=(None, len(data)))]] + + canvas_size = (13*10*len(header_list), 600) # estimate canvas size - 13 pixels per char * 10 char per column * num columns + layout = [[sg.Column(col_layout, size=canvas_size, scrollable=True)],] + + window = sg.Window('Table', grab_anywhere=False).Layout(layout) + b, v = window.Read() + + sys.exit(69) + +table_example() diff --git a/Demo_Table_Element.py b/Demo_Table_Element.py new file mode 100644 index 000000000..237b575d5 --- /dev/null +++ b/Demo_Table_Element.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import csv + + +filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),)) +# --- populate table with file contents --- # +data = [] +if filename is not None: + with open(filename, "r") as infile: + reader = csv.reader(infile) + try: + data = list(reader) # read everything else into a list of rows + except: + sg.PopupError('Error reading file') + sys.exit(69) + +sg.SetOptions(element_padding=(0, 0)) + +col_layout = [[sg.Table(values=data[1:][:], headings=[data[0][x] for x in range(len(data[0]))], max_col_width=25, + auto_size_columns=True, display_row_numbers=True, justification='right', size=(None, len(data)))]] + +layout = [[sg.Column(col_layout, size=(1200,600), scrollable=True)],] +window = sg.Window('Table', grab_anywhere=False).Layout(layout) + +b, v = window.Read() + +sys.exit(69) diff --git a/Demo_Table_Pandas.py b/Demo_Table_Pandas.py new file mode 100644 index 000000000..022aa1bfa --- /dev/null +++ b/Demo_Table_Pandas.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import pandas as pd + + +def table_example(): + sg.SetOptions(auto_size_buttons=True) + filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"),)) + # --- populate table with file contents --- # + if filename == '': + sys.exit(69) + data = [] + header_list = [] + button = sg.PopupYesNo('Does this file have column names already?') + if filename is not None: + try: + df = pd.read_csv(filename, sep=',', engine='python', header=None) # Header=None means you directly pass the columns names to the dataframe + data = df.values.tolist() # read everything else into a list of rows + if button == 'Yes': # Press if you named your columns in the csv + header_list = df.iloc[0].tolist() # Uses the first row (which should be column names) as columns names + data = df[1:].values.tolist() # Drops the first row in the table (otherwise the header names and the first row will be the same) + elif button == 'No': # Press if you didn't name the columns in the csv + header_list = ['column' + str(x) for x in range(len(data[0]))] # Creates columns names for each column ('column0', 'column1', etc) + except: + sg.PopupError('Error reading file') + sys.exit(69) + # sg.SetOptions(element_padding=(0, 0)) + + col_layout = [[sg.Table(values=data, headings=header_list, display_row_numbers=True, + auto_size_columns=False, size=(None, len(data)))]] + + canvas_size = (13*10*len(header_list), 600) # estimate canvas size - 13 pixels per char * 10 per column * num columns + layout = [[sg.Column(col_layout, size=canvas_size, scrollable=True)]] + + window = sg.Window('Table', grab_anywhere=False) + b, v = window.LayoutAndRead(layout) + + sys.exit(69) + +table_example() diff --git a/Demo_Table_Simulation.py b/Demo_Table_Simulation.py new file mode 100644 index 000000000..0889ed4f8 --- /dev/null +++ b/Demo_Table_Simulation.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import csv + + +def TableSimulation(): + """ + Display data in a table format + """ + sg.SetOptions(element_padding=(0,0)) + sg.PopupNoWait('Give it a few seconds to load please...', auto_close=True) + + menu_def = [['File', ['Open', 'Save', 'Exit']], + ['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],], + ['Help', 'About...'],] + + columm_layout = [[]] + + MAX_ROWS = 60 + MAX_COL = 10 + for i in range(MAX_ROWS): + inputs = [sg.T('{}'.format(i), size=(4,1), justification='right')] + [sg.In(size=(10, 1), pad=(1, 1), justification='right', key=(i,j), do_not_clear=True) for j in range(MAX_COL)] + columm_layout.append(inputs) + + layout = [ [sg.Menu(menu_def)], + [sg.T('Table Using Combos and Input Elements', font='Any 18')], + [sg.T('Type in a row, column and value. The form will update the values in realtime as you type'), + sg.In(key='inputrow', justification='right', size=(8,1), pad=(1,1), do_not_clear=True), + sg.In(key='inputcol', size=(8,1), pad=(1,1), justification='right', do_not_clear=True), + sg.In(key='value', size=(8,1), pad=(1,1), justification='right', do_not_clear=True)], + [sg.Column(columm_layout, size=(800,600), scrollable=True)] ] + + window = sg.Window('Table', return_keyboard_events=True, grab_anywhere=False).Layout(layout) + + while True: + button, values = window.Read() + # --- Process buttons --- # + if button is None or button == 'Exit': + break + elif button == 'About...': + sg.Popup('Demo of table capabilities') + elif button == 'Open': + filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),)) + # --- populate table with file contents --- # + if filename is not None: + with open(filename, "r") as infile: + reader = csv.reader(infile) + try: + data = list(reader) # read everything else into a list of rows + except: + sg.PopupError('Error reading file') + continue + # clear the table + [window.FindElement((i,j)).Update('') for j in range(MAX_COL) for i in range(MAX_ROWS)] + + for i, row in enumerate(data): + for j, item in enumerate(row): + location = (i,j) + try: # try the best we can at reading and filling the table + target_element = window.FindElement(location) + new_value = item + if target_element is not None and new_value != '': + target_element.Update(new_value) + except: + pass + + # if a valid table location entered, change that location's value + try: + location = (int(values['inputrow']), int(values['inputcol'])) + target_element = window.FindElement(location) + new_value = values['value'] + if target_element is not None and new_value != '': + target_element.Update(new_value) + except: + pass + +TableSimulation() \ No newline at end of file diff --git a/Demo_Tabs.py b/Demo_Tabs.py new file mode 100644 index 000000000..673c93076 --- /dev/null +++ b/Demo_Tabs.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +tab1_layout = [[sg.T('This is inside tab 1')]] + +tab2_layout = [[sg.T('This is inside tab 2')], + [sg.In(key='in')]] + +layout = [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout), sg.Tab('Tab 2', tab2_layout)]])], + [sg.RButton('Read')]] + +window = sg.Window('My window with tabs', default_element_size=(12,1)).Layout(layout) + +while True: + b, v = window.Read() + print(b,v) + if b is None: # always, always give a way out! + break \ No newline at end of file diff --git a/Demo_Tabs_Nested.py b/Demo_Tabs_Nested.py new file mode 100644 index 000000000..1c0b87b69 --- /dev/null +++ b/Demo_Tabs_Nested.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +sg.ChangeLookAndFeel('GreenTan') +tab2_layout = [[sg.T('This is inside tab 2')], + [sg.T('Tabs can be anywhere now!')]] + +tab1_layout = [[sg.T('Type something here and click button'), sg.In(key='in')]] + +tab3_layout = [[sg.T('This is inside tab 3')]] +tab4_layout = [[sg.T('This is inside tab 4')]] + +tab_layout = [[sg.T('This is inside of a tab')]] +tab_group = sg.TabGroup([[sg.Tab('Tab 7', tab_layout), sg.Tab('Tab 8', tab_layout)]]) + +tab5_layout = [[sg.T('Watch this window')], + [sg.Output(size=(40,5))]] +tab6_layout = [[sg.T('This is inside tab 6')], + [sg.T('How about a second row of stuff in tab 6?'), tab_group]] + +layout = [[sg.T('My Window!')], [sg.Frame('A Frame', layout= + [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout), sg.Tab('Tab 2', tab2_layout)]]), sg.TabGroup([[sg.Tab('Tab3', tab3_layout), sg.Tab('Tab 4', tab4_layout)]])]])], + [sg.T('This text is on a row with a column'),sg.Column(layout=[[sg.T('In a column')], + [sg.TabGroup([[sg.Tab('Tab 5', tab5_layout), sg.Tab('Tab 6', tab6_layout)]])], + [sg.RButton('Click me')]])],] + +window = sg.Window('My window with tabs', default_element_size=(12,1)).Layout(layout).Finalize() + +print('Are there enough tabs for you?') + +while True: + button, values = window.Read() + print(button,values) + if button is None: # always, always give a way out! + break \ No newline at end of file diff --git a/Demo_Template.py b/Demo_Template.py new file mode 100644 index 000000000..286c6fa48 --- /dev/null +++ b/Demo_Template.py @@ -0,0 +1,39 @@ +#choose one of these are your starting point. Copy, paste, have fun + +# ---------------------------------# +# DESIGN PATTERN 1 - Simple Window # +# ---------------------------------# +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[ sg.Text('My layout') ], + [ sg.Button('Next Window')]] + +window = sg.Window('My window').Layout(layout) +button, value = window.Read() + + +# -------------------------------------# +# DESIGN PATTERN 2 - Persistent Window # +# -------------------------------------# +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg + +layout = [[ sg.Text('My layout') ], + [ sg.RButton('Read The Window')]] + +window = sg.Window('My new window').Layout(layout) + +while True: # Event Loop + button, value = window.Read() + if button is None: + break + print(button, value) \ No newline at end of file diff --git a/Demo_Timer.py b/Demo_Timer.py new file mode 100644 index 000000000..cff69f768 --- /dev/null +++ b/Demo_Timer.py @@ -0,0 +1,43 @@ +import PySimpleGUI as sg +import time + +# form that doen't block +# good for applications with an loop that polls hardware +def Timer(): + sg.ChangeLookAndFeel('Dark') + sg.SetOptions(element_padding=(0,0)) + # Make a form, but don't use context manager + form = sg.FlexForm('Running Timer', no_titlebar=True, auto_size_buttons=False) + # Create a text element that will be updated with status information on the GUI itself + # Create the rows + form_rows = [[sg.Text('')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='text')], + [sg.ReadFormButton('Pause'), sg.ReadFormButton('Reset'), sg.Exit(button_color=('white','firebrick4'))]] + # Layout the rows of the form and perform a read. Indicate the form is non-blocking! + form.Layout(form_rows) + # + # your program's main loop + i = 0 + paused = False + while (True): + # This is the code that reads and updates your window + button, values = form.ReadNonBlocking() + form.FindElement('text').Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100)) + + if values is None or button == 'Exit': + break + + if button is 'Reset': + i=0 + elif button is 'Pause': + paused = not paused + + if not paused: + i += 1 + # Your code begins here + time.sleep(.01) + + # Broke out of main loop. Close the window. + form.CloseNonBlockingForm() + +Timer() \ No newline at end of file diff --git a/Demo_Youtube-dl_Frontend.py b/Demo_Youtube-dl_Frontend.py new file mode 100644 index 000000000..6e0f30e4e --- /dev/null +++ b/Demo_Youtube-dl_Frontend.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +import sys +if sys.version_info[0] >= 3: + import PySimpleGUI as sg +else: + import PySimpleGUI27 as sg +import subprocess + +""" +Simple wrapper for youtube-dl.exe. +Paste the youtube link into the GUI. The GUI link is queried when you click Get List. +Get List will populate the pulldown list with the language options available for the video. +Choose the language to download and click Download +""" + +def DownloadSubtitlesGUI(): + sg.ChangeLookAndFeel('Dark') + + combobox = sg.InputCombo(values=['',], size=(10,1), key='lang') + layout = [ + [sg.Text('Subtitle Grabber', size=(40, 1), font=('Any 15'))], + [sg.T('YouTube Link'),sg.In(default_text='',size=(60,1), key='link', do_not_clear=True) ], + [sg.Output(size=(90,20), font='Courier 12')], + [sg.ReadButton('Get List')], + [sg.T('Language Code'), combobox, sg.ReadButton('Download')], + [sg.Button('Exit', button_color=('white', 'firebrick3'))] + ] + + window = sg.Window('Subtitle Grabber launcher', text_justification='r', default_element_size=(15,1), font=('Any 14')).Layout(layout) + + # ---===--- Loop taking in user input and using it to query HowDoI --- # + while True: + (button, gui) = window.Read() + if button in ('EXIT', None): + break # exit button clicked + link = gui['link'] + if button is 'Get List': + print('Getting list of subtitles....') + window.Refresh() + command = [f'C:/Python/PycharmProjects/GooeyGUI/youtube-dl --list-subs {link}',] + output = ExecuteCommandSubprocess(command, wait=True, quiet=True) + lang_list = [o[:5].rstrip() for o in output.split('\n') if 'vtt' in o] + lang_list = sorted(lang_list) + combobox.Update(values=lang_list) + print('Done') + + elif button is 'Download': + lang = gui['lang'] + if lang is '': + lang = 'en' + print(f'Downloading subtitle for {lang}...') + window.Refresh() + command = (f'C:/Python/PycharmProjects/GooeyGUI/youtube-dl --sub-lang {lang} --write-sub {link}',) + ExecuteCommandSubprocess(command, wait=True) + print('Done') + + +def ExecuteCommandSubprocess(command, wait=False, quiet=True, *args): + try: + sp = subprocess.Popen([command,*args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if wait: + out, err = sp.communicate() + if not quiet: + if out: + print(out.decode("utf-8")) + if err: + print(err.decode("utf-8")) + except: return '' + + return (out.decode('utf-8')) + + +if __name__ == '__main__': + DownloadSubtitlesGUI() + diff --git a/Mike_Cashes_Tkinter.py b/Mike_Cashes_Tkinter.py new file mode 100644 index 000000000..4dc7e357a --- /dev/null +++ b/Mike_Cashes_Tkinter.py @@ -0,0 +1,93 @@ +import PySimpleGUI as sg +import psutil +import time +from threading import Thread +import operator + +""" + Crashes with this information: + Tcl_AsyncDelete: async handler deleted by the wrong thread + + Process finished with exit code -2147483645 +""" + +# globale used to communicate with thread.. yea yea... it's working fine +g_interval = 1 +g_cpu_percent = 0 +g_procs = None +g_exit = False + +def CPU_thread(args): + global g_interval, g_cpu_percent, g_procs, g_exit + + while not g_exit: + try: + g_cpu_percent = psutil.cpu_percent(interval=g_interval) + g_procs = psutil.process_iter() + except: + pass + + +def main(): + global g_interval, g_procs, g_exit + + sg.PopupOKCancel('My popup') + + # ---------------- Create Form ---------------- + sg.ChangeLookAndFeel('Black') + form_rows = [[sg.Text('', size=(8,1), font=('Helvetica', 20),text_color=sg.YELLOWS[0], justification='center', key='text')], + [sg.Text('', size=(30, 8), font=('Courier New', 12),text_color='white', justification='left', key='processes')], + [sg.Exit(button_color=('white', 'firebrick4'), pad=((15,0), 0)), sg.Spin([x+1 for x in range(10)], 1, key='spin')],] + + form = sg.FlexForm('CPU Utilization', no_titlebar=True, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True) + form.Layout(form_rows) + # start cpu measurement thread + thread = Thread(target=CPU_thread,args=(None,)) + thread.start() + # ---------------- main loop ---------------- + while (True): + # --------- Read and update window -------- + button, values = form.ReadNonBlocking() + + # --------- Do Button Operations -------- + if values is None or button == 'Exit': + break + try: + g_interval = int(values['spin']) + except: + g_interval = 1 + + # cpu_percent = psutil.cpu_percent(interval=interval) # if don't wan to use a task + cpu_percent = g_cpu_percent + + # let the GUI run ever 700ms regardless of CPU polling time. makes window be more responsive + time.sleep(.7) + + display_string = '' + if g_procs: + # --------- Create list of top % CPU porocesses -------- + try: + top = {proc.name() : proc.cpu_percent() for proc in g_procs} + except: pass + + + top_sorted = sorted(top.items(), key=operator.itemgetter(1), reverse=True) + if top_sorted: + top_sorted.pop(0) + display_string = '' + for proc, cpu in top_sorted: + display_string += '{:2.2f} {}\n'.format(cpu/10, proc) + + + # --------- Display timer in window -------- + form.FindElement('text').Update('CPU {}'.format(cpu_percent)) + form.FindElement('processes').Update(display_string) + + # Broke out of main loop. Close the window. + form.CloseNonBlockingForm() + g_exit = True + thread.join() + exit(69) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/ProgrammingClassExamples/1a PSG (Entry and PopUp).py b/ProgrammingClassExamples/1a PSG (Entry and PopUp).py new file mode 100644 index 000000000..ed6600fcb --- /dev/null +++ b/ProgrammingClassExamples/1a PSG (Entry and PopUp).py @@ -0,0 +1,29 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +layout = [ + [sg.Text('Celcius'), sg.InputText()], #layout, Text, Input + [sg.Submit()], #button on line below + ] + +#setup window with Title +window = sg.Window('Temperature Converter').Layout(layout) + +button, value = window.Read() #get value (part of a list) + +fahrenheit = round(9/5*float(value[0]) +32, 1) #convert and create string +result = 'Temperature in Fahrenheit is: ' + str(fahrenheit) +sg.Popup('Result', result) #display in Popup + + + + + + + + + + diff --git a/ProgrammingClassExamples/1b PSG (Format).py b/ProgrammingClassExamples/1b PSG (Format).py new file mode 100644 index 000000000..d5b5540b5 --- /dev/null +++ b/ProgrammingClassExamples/1b PSG (Format).py @@ -0,0 +1,37 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +#Set formatting options for all elements rather than individually. +sg.SetOptions (background_color = 'LightBlue', + element_background_color = 'LightBlue', + text_element_background_color = 'LightBlue', + font = ('Arial', 10, 'bold'), + text_color = 'Blue', + input_text_color ='Blue', + button_color = ('White', 'Blue') + ) +#adjust widths +layout = [ + [sg.Text('Celcius', size =(12,1)), sg.InputText(size = (8,1))], + [sg.Submit()] + ] + +window = sg.Window('Converter').Layout(layout) +button, value = window.Read() + +fahrenheit = round(9/5*float(value[0]) +32, 1) +result = 'Temperature in Fahrenheit is: ' + str(fahrenheit) +sg.Popup('Result',result) + + + + + + + + + + diff --git a/ProgrammingClassExamples/1c PSG (persistent form and bind key).py b/ProgrammingClassExamples/1c PSG (persistent form and bind key).py new file mode 100644 index 000000000..bae93423c --- /dev/null +++ b/ProgrammingClassExamples/1c PSG (persistent form and bind key).py @@ -0,0 +1,32 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (background_color = 'LightBlue', + element_background_color = 'LightBlue', + text_element_background_color = 'LightBlue', + font = ('Arial', 10, 'bold'), + text_color = 'Blue', + input_text_color ='Blue', + button_color = ('White', 'Blue') + ) +#update (via list) values and and display answers +#value[0] is celcius input, value[1] is input to place result. +#Use ReadButton with while true: - keeps window open. + +layout = [ [sg.Text('Enter a Temperature in Celcius')], + [sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1))], + [sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1))], + [sg.ReadButton('Submit', bind_return_key = True)]] #Return = button press + +window = sg.Window('Converter').Layout(layout) + +while True: + button, value = window.Read() #get result + if button is not None: #break out of loop is button not pressed. + fahrenheit = round(9/5*float(value[0]) +32, 1) + window.FindElement(1).Update(fahrenheit) #put result in 2nd input box + else: + break diff --git a/ProgrammingClassExamples/1d PSG (named input keys and catch errors).py b/ProgrammingClassExamples/1d PSG (named input keys and catch errors).py new file mode 100644 index 000000000..e62fae8d3 --- /dev/null +++ b/ProgrammingClassExamples/1d PSG (named input keys and catch errors).py @@ -0,0 +1,35 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (background_color = 'LightBlue', + element_background_color = 'LightBlue', + text_element_background_color = 'LightBlue', + font = ('Arial', 10, 'bold'), + text_color = 'Blue', + input_text_color ='Blue', + button_color = ('White', 'Blue') + ) +#name inputs (key) uses dictionary- easy to see updating of results +#value[input] first input value te c... +layout = [ [sg.Text('Enter a Temperature in Celcius')], + [sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1),key = 'input')], + [sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1),key = 'result')], + [sg.ReadButton('Submit', bind_return_key = True)]] + +window = sg.FlexForm('Temp Converter').Layout(layout) + +while True: + button, value = window.Read() + if button is not None: + #catch program errors for text or blank entry: + try: + fahrenheit = round(9/5*float(value['input']) +32, 1) + window.FindElement('result').Update(fahrenheit) #put result in text box + except ValueError: + sg.Popup('Error','Please try again') #display error + + else: + break diff --git a/ProgrammingClassExamples/1e PSG (validation and Look and Feel).py b/ProgrammingClassExamples/1e PSG (validation and Look and Feel).py new file mode 100644 index 000000000..e6b435a3e --- /dev/null +++ b/ProgrammingClassExamples/1e PSG (validation and Look and Feel).py @@ -0,0 +1,34 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +#Can use a variety of themes - plus individual options +sg.ChangeLookAndFeel('SandyBeach') +sg.SetOptions (font = ('Arial', 10, 'bold')) + + +layout = [ [sg.Text('Enter a Temperature in Celcius')], + [sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1),key = 'input')], + [sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1),key = 'result')], + [sg.ReadButton('Submit', bind_return_key = True)]] + +window = sg.FlexForm('Temp Converter').Layout(layout) + +while True: + button, value = window.Read() + if button is not None: + #catch program errors for text, floats or blank entry: + #Also validation for range [0, 50] + try: + if float(value['input']) > 50 or float(value['input']) <0: + sg.Popup('Error','Out of range') + else: + fahrenheit = round(9/5*int(value['input']) +32, 1) + window.FindElement('result').Update(fahrenheit) #put result in text box + except ValueError: + sg.Popup('Error','Please try again') #display error + + else: + break diff --git a/ProgrammingClassExamples/2a. PSG (checkbox and radiobuttons).py b/ProgrammingClassExamples/2a. PSG (checkbox and radiobuttons).py new file mode 100644 index 000000000..6c54f600d --- /dev/null +++ b/ProgrammingClassExamples/2a. PSG (checkbox and radiobuttons).py @@ -0,0 +1,40 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.ChangeLookAndFeel('GreenTan') #Set colour scheme +sg.SetOptions (font =('Calibri',12,'bold') ) #and font + + + +#One checkbox and three radio buttons (grouped as 'Radio1' +layout = [[sg.Text('Membership Calculator', font = ('Calibri', 16, 'bold'))], + [sg.Checkbox(' Student? 10% off', size = (25,1)), #value[0] + sg.ReadButton('Display Cost', size = (14,1))], + [sg.Radio('1 month $50', 'Radio1', default = True), #value[1] + sg.Radio('3 months $100', 'Radio1'), #value[2] + sg.Radio('1 year $300', 'Radio1')], #value[3] + [sg.Text('', size = (30,1), justification = 'center', font =('Calibri', 16, 'bold'), key = 'result')]] + +window = sg.Window('Gym Membership').Layout(layout) + +while True: + button, value = window.Read() + if button is not None: + if value[1]: + cost = 50 + elif value[2]: + cost = 100 + else: + cost = 300 + if value[0]: + cost = cost*0.9 #apply discount + + #format as currency $ symbol and 2 d.p. - make a string + result = str(' Cost: ' + '${:.2f}'.format(cost)) + window.FindElement('result').Update(result) #put the result in Textbox + + else: + break diff --git a/ProgrammingClassExamples/2b_makewinexe_file.py b/ProgrammingClassExamples/2b_makewinexe_file.py new file mode 100644 index 000000000..351f082d1 --- /dev/null +++ b/ProgrammingClassExamples/2b_makewinexe_file.py @@ -0,0 +1,36 @@ +import PySimpleGUI as sg +#pip install PyInstaller +#windows command prompt pyinstaller -wF 2b_makewinexe_file.py +#must CD to directory where py file is + +sg.ChangeLookAndFeel('GreenTan') #Set colour scheme +sg.SetOptions (font =('Calibri',12,'bold') ) #and font + +form = sg.FlexForm('Gym Membership') + + +layout = [[sg.Text('Membership Calculator', font = ('Calibri', 16, 'bold'))], + [sg.Checkbox('CGS student?', size = (22,1)), #value[0] + sg.ReadButton('Display Cost', size = (14,1))], + [sg.Radio('One Month', 'Radio1', default = True), #value[1] + sg.Radio('Three Month', 'Radio1'), #value[2] + sg.Radio('One Year', 'Radio1')], #value[3] + [sg.Text('', size = (30,1), justification = 'center', font =('Calibri', 16, 'bold'), key = 'result')]] + +form.Layout(layout) +while True: + button, value = form.Read() + if button is not None: + if value[1]: + cost = 50 + elif value[2]: + cost = 100 + else: + cost = 300 + if value[0]: + cost = cost*0.9 + result = str(' Cost: ' + '${:.2f}'.format(cost)) #format as currency - make a string + form.FindElement('result').Update(result) #put the result in Textbox + + else: + break diff --git a/ProgrammingClassExamples/3 PSG (multiline display).py b/ProgrammingClassExamples/3 PSG (multiline display).py new file mode 100644 index 000000000..91ac114a5 --- /dev/null +++ b/ProgrammingClassExamples/3 PSG (multiline display).py @@ -0,0 +1,40 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.ChangeLookAndFeel('GreenTan') + +sg.SetOptions(font = ('Courier New', 12)) + + + +layout = [ + [sg.Text('Enter and Add Data to Display', font = ('Calibri', 14,'bold'))], + [sg.Text('Race:', size = (5,1)), sg.InputText(size = (8,1)), + sg.Text('Club:', size = (5,1)), sg.InputText(size = (8,1))], + [sg.Text('Name:', size = (5,1)), sg.InputText(size = (8,1)), + sg.Text('Time:', size = (5,1)), sg.InputText(size = (8,1)),sg.Text(' '), + sg.ReadButton('Add Data', font = ('Calibri', 12, 'bold'))], + [sg.Text('_'*40)], + [sg.Text(' Race Club Name Time')], + [sg.Multiline(size =(40,6),key = 'Multiline')] + ] + +window = sg.Window('Enter & Display Data').Layout(layout) + +string = '' +S=[] +while True: + + button, value = window.Read() + if button is not None: + #use string formatting - best way? plus Courier New font - non-proportional font + S = S + ['{:^9s}{:<11s}{:<10s}{:>8s}'.format(value[0],value[1],value[2],value[3])] + for s in S: + string = string + s + '\n' + window.FindElement('Multiline').Update(string) + string ='' + else: + break diff --git a/ProgrammingClassExamples/4a PSG (Sliders and combo).py b/ProgrammingClassExamples/4a PSG (Sliders and combo).py new file mode 100644 index 000000000..f933a16d7 --- /dev/null +++ b/ProgrammingClassExamples/4a PSG (Sliders and combo).py @@ -0,0 +1,48 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +#use of Column to help with layout - vertical sliders take up space + +column1 = [ + [sg.Text('Pick operation', size = (15,1), font = ('Calibri', 12, 'bold'))], +[sg.InputCombo(['Add','Subtract','Multiply','Divide'], size = (10,6))], + [sg.Text('', size =(1,4))]] +column2 = [ + [sg.ReadButton('Submit', font = ('Calibri', 12, 'bold'), button_color = ('White', 'Red'))], + [sg.Text('Result:', font = ('Calibri', 12, 'bold'))],[sg.InputText(size = (12,1), key = 'result')] + ] + + +layout = [ + [sg.Text('Slider and Combo box demo', font = ('Calibri', 14,'bold'))], + [sg.Slider(range = (-9, 9),orientation = 'v', size = (5,20), default_value = 0), + sg.Slider(range = (-9, 9),orientation = 'v', size = (5, 20), default_value = 0), + sg.Text(' '), sg.Column(column1), sg.Column(column2)]] + +#added grab_anywhere to when moving slider, who window doesn't move. + +window = sg.Window('Enter & Display Data',grab_anywhere = False).Layout(layout) + +#Get selection from combo: value[2] +#Slider values: value[0] and value[1] +while True: + button, value = window.Read() + if button is not None: + if value[2] == 'Add': + result = value[0] + value[1] + elif value[2] == 'Multiply': + result = value[0] * value[1] + elif value[2] == 'Subtract': + result = value[0] - value[1] + elif value[2] == 'Divide': #check for zero + if value[1] ==0: + sg.Popup('Second value can\'t be zero') + result = 'NA' + else: + result = value[0] / value[1] + window.FindElement('result').Update(result) + else: + break diff --git a/ProgrammingClassExamples/4b PSG (Spinner and combo) .py b/ProgrammingClassExamples/4b PSG (Spinner and combo) .py new file mode 100644 index 000000000..b41e8478a --- /dev/null +++ b/ProgrammingClassExamples/4b PSG (Spinner and combo) .py @@ -0,0 +1,39 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg +sg.SetOptions(font= ('Calibri', 12, 'bold')) + +layout = [ + [sg.Text('Spinner and Combo box demo', font = ('Calibri', 14, 'bold'))], + [sg.Spin([sz for sz in range (-9,10)], size = (2,1),initial_value = 0), + sg.Spin([sz for sz in range (-9,10)], size = (2,1), initial_value = 0), + sg.Text('Pick operation ->', size = (15,1)), + sg.InputCombo(['Add','Subtract','Multiply','Divide'], size = (8,6))], + [sg.Text('Result: ')],[sg.InputText(size = (5,1), key = 'result'), + sg.ReadButton('Calculate', button_color = ('White', 'Red'))]] + +window = sg.Window('Enter & Display Data', grab_anywhere= False).Layout(layout) + +while True: + button, value = window.Read() + + if button is not None: + #convert returned values to integers + val = [int(value[0]), int(value[1])] + if value[2] == 'Add': + result = val[0] + val[1] + elif value[2] == 'Multiply': + result = val[0] * val[1] + elif value[2] == 'Subtract': + result = val[0] - val[1] + elif value[2] == 'Divide': + if val[1] ==0: + sg.Popup('Second value can\'t be zero') + result = 'NA' + else: + result = round( val[0] / val[1], 3) + window.FindElement('result').Update(result) + else: + break diff --git a/ProgrammingClassExamples/5a PSG (listboxes add remove).py b/ProgrammingClassExamples/5a PSG (listboxes add remove).py new file mode 100644 index 000000000..7b60504e8 --- /dev/null +++ b/ProgrammingClassExamples/5a PSG (listboxes add remove).py @@ -0,0 +1,39 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.ChangeLookAndFeel('BlueMono') + +#use column feature with height listbox takes up +column1 = [ + [sg.Text('Add or Delete Items\nfrom a Listbox', font = ('Arial', 12, 'bold'))], + [sg.InputText( size = (15,1), key = 'add'), sg.ReadButton('Add')], + [sg.ReadButton('Delete selected entry')]] + +List = ['Austalia', 'Canada', 'Greece'] #initial listbox entries + +#add initial List to listbox +layout = [ + [sg.Listbox(values=[l for l in List], size = (30,8), key ='listbox'), + sg.Column(column1)]] + +window = sg.Window('Listbox').Layout(layout) + +while True: + button, value = window.Read() + if button is not None: + #value[listbox] returns a list + if button == 'Delete selected entry': #using value[listbox][0] give the string + if value['listbox'] == []: #ensure something is selected + sg.Popup('Error','You must select a Country') + else: + List.remove(value['listbox'][0]) #find and remove this + if button == 'Add': + List.append(value['add']) #add string in add box to list + List.sort() #sort + #update listbox + window.FindElement('listbox').Update(List) + else: + break diff --git a/ProgrammingClassExamples/6 PSG sort and search .py b/ProgrammingClassExamples/6 PSG sort and search .py new file mode 100644 index 000000000..70541403d --- /dev/null +++ b/ProgrammingClassExamples/6 PSG sort and search .py @@ -0,0 +1,130 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (font =('Calibri',12,'bold')) + + +#setup column (called column1) of buttons to sue in layout + +column1 = [[sg.ReadButton('Original list', size = (13,1))], + [sg.ReadButton('Default sort', size = (13,1))], + [sg.ReadButton('Sort: selection',size = (13,1))], + [sg.ReadButton('Sort: quick', size = (13,1))]] + +layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))], +[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)], + [sg.Text('_'*32,font = ('Calibri', 12))], + [sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')], + [sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))], + ] + +window = sg.Window('Search and Sort Demo').Layout(layout) + +#names for Demo, could be loaded from a file +Names= ['Roberta', 'Kylie', 'Jenny', 'Helen', + 'Andrea', 'Meredith','Deborah','Pauline', + 'Belinda', 'Wendy'] + +#function to display list +def displayList(List): + global ListDisplayed #store list in Multiline text globally + ListDisplayed = List + display = '' + for l in List: #add list elements with new line + display = display + l + '\n' + window.FindElement('display').Update(display) + +#use inbuilt python sort +def default(Names): + L = Names[:] + L.sort() #inbuilt sort + displayList(L) + +#Selection sort - See Janson Ch 7 +def selSort(Names): + L = Names[:] + for i in range(len(L)): + smallest = i + for j in range(i+1, len(L)): + if L[j] < L[smallest]: #find smallest value + smallest = j #swap it to front + L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion + displayList(L) + +#Quick sort - See Janson Ch 7 +def qsortHolder(Names): + L = Names[:] #pass List, first and last + quick_sort(L, 0, len(L) -1) #Start process + displayList(L) + +def quick_sort(L, first, last): #Quicksort is a partition sort + if first >= last: + return L + pivot = L[first] + low = first + high = last + while low < high: + while L[high] > pivot: + high = high -1 + while L[low] < pivot: + low = low + 1 + if low <= high: + L[high], L[low] = L[low], L[high] + low = low + 1 + high = high -1 + quick_sort(L, first, low -1) #continue splitting - sort small lsist + quick_sort(L, low, last) + +#Linear Search - no need for Ordered list +def linearSearch(): + L = Names[:] + found = False + for l in L: + if l == value['linear']: #Check each value + found = True + window.FindElement('display').Update('Linear search\n' + l + ' found.') + break + if not found: + window.FindElement('display').Update(value['linear'] + ' was \nNot found') + +#Binary Search - only works fot ordered lists +def binarySearch(): + L = ListDisplayed[:] #get List currently in multiline display + lo = 0 + hi = len(L)-1 + found = False #Start with found is Flase + while lo <= hi: + mid = (lo + hi) //2 #Start in middle + if L[mid] == value['binary']: #get the value from the search box + window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.') + found = True #If found display + break #and stop + elif L[mid] < value['binary']: + lo = mid + 1 #Search in top half + else: + hi = mid - 1 #Search in lower half + if not found: #If we get to end - display not found + window.FindElement('display').Update(value['binary'] + ' was \nNot found') + + +while True: + button, value = window.Read() + if button is not None: + if button == 'Original list': + displayList(Names) + if button == 'Default sort': + default(Names) + if button == 'Sort: selection': + selSort(Names) + if button == 'Sort: quick': + qsortHolder(Names) + if button == 'Linear Search': + linearSearch() + if button == 'Binary Search': + binarySearch() + else: + break + diff --git a/ProgrammingClassExamples/6a PSG search.py b/ProgrammingClassExamples/6a PSG search.py new file mode 100644 index 000000000..090ba7b22 --- /dev/null +++ b/ProgrammingClassExamples/6a PSG search.py @@ -0,0 +1,78 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (font =('Calibri',12,'bold')) + +layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')], +[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'), + sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')], + [sg.Text('_'*32,font = ('Calibri', 12))], + [sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')], + [sg.ReadButton('Linear Search', size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))], + ] +window = sg.Window('Search Demo').Layout(layout) + +#names for Demo, could be loaded from a file +Names = ['Roberta', 'Kylie', 'Jenny', 'Helen', + 'Andrea', 'Meredith','Deborah','Pauline', + 'Belinda', 'Wendy'] + +SortedNames = ['Andrea','Belinda','Deborah','Helen', + 'Jenny','Kylie','Meredith','Pauline', + 'Roberta','Wendy'] + +#function to display list +def displayList(List, display): + names = '' + for l in List: #add list elements with new line + names = names + l + '\n' + window.FindElement(display).Update(names) + +#Linear Search - no need for Ordered list +def linearSearch(): + L = Names[:] + found = False + for l in L: + if l == value['linear']: #Check each value + found = True + window.FindElement('display1').Update('Linear search\n' + l + ' found.') + break + if not found: + window.FindElement('display1').Update(value['linear'] + ' was \nNot found') + +#Binary Search - only works for ordered lists +def binarySearch(): + L = SortedNames[:] + lo = 0 + hi = len(L)-1 + found = False #Start with found is Flase + while lo <= hi: + mid = (lo + hi) //2 #Start in middle + if L[mid] == value['binary']: #get the value from the search box + window.FindElement('display2').Update('Binary search\n' + L[mid] + ' found.') + found = True #If found display + break #and stop + elif L[mid] < value['binary']: + lo = mid + 1 #Search in top half + else: + hi = mid - 1 #Search in lower half + if not found: #If we get to end - display not found + window.FindElement('display2').Update(value['binary'] + ' was \nNot found') + +while True: + button, value = window.Read() + + if button is not None: + if button == 'Show Names': #show names - unordered and sorted + displayList(Names,'display1') + displayList(SortedNames, 'display2') + if button == 'Linear Search': #Find and display + linearSearch() + if button == 'Binary Search': #Find and display + binarySearch() + else: + break + diff --git a/ProgrammingClassExamples/6b PSG search (disabled buttons).py b/ProgrammingClassExamples/6b PSG search (disabled buttons).py new file mode 100644 index 000000000..2e1dfd83e --- /dev/null +++ b/ProgrammingClassExamples/6b PSG search (disabled buttons).py @@ -0,0 +1,82 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (font =('Calibri',12,'bold')) + +layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')], +[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'), + sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')], + [sg.Text('_'*32,font = ('Calibri', 12))], + [sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')], + [sg.ReadButton('Linear Search', size = (13,1),key = 'ls'), sg.ReadButton('Binary Search', size = (14,1),key='bs')], + ] +window = sg.Window('Search Demo').Layout(layout) +window.Finalize() #finalize allows the disabling +window.FindElement('ls').Update(disabled=True) #of the two buttons +window.FindElement('bs').Update(disabled=True) + +#names for Demo, could be loaded from a file +Names = ['Roberta', 'Kylie', 'Jenny', 'Helen', + 'Andrea', 'Meredith','Deborah','Pauline', + 'Belinda', 'Wendy'] + +SortedNames = ['Andrea','Belinda','Deborah','Helen', + 'Jenny','Kylie','Meredith','Pauline', + 'Roberta','Wendy'] + +#function to display list +def displayList(List, display): + names = '' + for l in List: #add list elements with new line + names = names + l + '\n' + window.FindElement(display).Update(names) + window.FindElement('ls').Update(disabled=False) #enable buttons now + window.FindElement('bs').Update(disabled=False) #now data loaded + +#Linear Search - no need for Ordered list +def linearSearch(): + L = Names[:] + found = False + for l in L: + if l == value['linear']: #Check each value + found = True + window.FindElement('display1').Update('Linear search\n' + l + ' found.') + break + if not found: + window.FindElement('display1').Update(value['linear'] + ' was \nNot found') + +#Binary Search - only works for ordered lists +def binarySearch(): + L = SortedNames[:] + lo = 0 + hi = len(L)-1 + found = False #Start with found is Flase + while lo <= hi: + mid = (lo + hi) //2 #Start in middle + if L[mid] == value['binary']: #get the value from the search box + window.FindElement('display2').Update('Binary search\n' + L[mid] + ' found.') + found = True #If found display + break #and stop + elif L[mid] < value['binary']: + lo = mid + 1 #Search in top half + else: + hi = mid - 1 #Search in lower half + if not found: #If we get to end - display not found + window.FindElement('display2').Update(value['binary'] + ' was \nNot found') + +while True: + button, value = window.Read() + if button is not None: + if button == 'Show Names': #show names - unordered and sorted + displayList(Names,'display1') + displayList(SortedNames, 'display2') + if button == 'ls': #Find and display + linearSearch() + if button == 'bs': #Find and display + binarySearch() + else: + break + diff --git a/ProgrammingClassExamples/6c PSG search text preloaded.py b/ProgrammingClassExamples/6c PSG search text preloaded.py new file mode 100644 index 000000000..cbc6832c8 --- /dev/null +++ b/ProgrammingClassExamples/6c PSG search text preloaded.py @@ -0,0 +1,79 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (font =('Calibri',12,'bold')) + +#names for Demo, could be loaded from a file + +Names = ['Roberta', 'Kylie', 'Jenny', 'Helen', + 'Andrea', 'Meredith','Deborah','Pauline', + 'Belinda', 'Wendy'] +names = '' +for l in Names: + names = names + l + '\n' + +SortedNames = ['Andrea','Belinda','Deborah','Helen', + 'Jenny','Kylie','Meredith','Pauline', + 'Roberta','Wendy'] + +sortnames = '' +for l in SortedNames: + sortnames = sortnames + l +'\n' + +layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold'))], +[sg.Text(names,size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'), + sg.Text(sortnames,size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')], + [sg.Text('_'*32,font = ('Calibri', 12))], + [sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')], + [sg.ReadButton('Linear Search', bind_return_key=True, size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))], + ] +window = sg.Window('Search Demo').Layout(layout) + +#Linear Search - no need for Ordered list +def linearSearch(): + L = Names[:] + found = False + for l in L: + if l == value['linear']: #Check each value + found = True + sg.Popup('Linear search\n' + l + ' found.') + break + if not found: + sg.Popup('Linear search\n' +(value['linear'] + ' was not found')) + +#Binary Search - only works for ordered lists +def binarySearch(): + L = SortedNames[:] + lo = 0 + hi = len(L)-1 + found = False #Start with found is Flase + while lo <= hi: + mid = (lo + hi) //2 #Start in middle + if L[mid] == value['binary']: #get the value from the search box + sg.Popup('Binary search\n' + L[mid] + ' found.') + found = True #If found display + break #and stop + elif L[mid] < value['binary']: + lo = mid + 1 #Search in top half + else: + hi = mid - 1 #Search in lower half + if not found: #If we get to end - display not found + sg.Popup('Binary search\n' +(value['binary'] + ' was not found')) + +while True: + button, value = window.Read() + + if button is not None: + if button == 'Show Names': #show names - unordered and sorted + displayList(Names,'display1') + displayList(SortedNames, 'display2') + if button == 'Linear Search': #Find and display + linearSearch() + if button == 'Binary Search': #Find and display + binarySearch() + else: + break + diff --git a/ProgrammingClassExamples/6d PSG sort and search.py b/ProgrammingClassExamples/6d PSG sort and search.py new file mode 100644 index 000000000..68d84be4e --- /dev/null +++ b/ProgrammingClassExamples/6d PSG sort and search.py @@ -0,0 +1,130 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (font =('Calibri',12,'bold')) + + +#setup column (called column1) of buttons to sue in layout + +column1 = [[sg.ReadButton('Original list', size = (13,1))], + [sg.ReadButton('Default sort', size = (13,1))], + [sg.ReadButton('Sort: selection',size = (13,1))], + [sg.ReadButton('Sort: quick', size = (13,1))]] + +layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))], +[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)], + [sg.Text('_'*32,font = ('Calibri', 12))], + [sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')], + [sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))], + ] + +window = sg.Window('Search and Sort Demo').Layout(layout) + +#names for Demo, could be loaded from a file +Names= ['Roberta', 'Kylie', 'Jenny', 'Helen', + 'Andrea', 'Meredith','Deborah','Pauline', + 'Belinda', 'Wendy'] + +#function to display list +def displayList(List): + global ListDisplayed #store list in Multiline text globally + ListDisplayed = List + display = '' + for l in List: #add list elements with new line + display = display + l + '\n' + window.FindElement('display').Update(display) + +#use inbuilt python sort +def default(Names): + L = Names[:] + L.sort() #inbuilt sort + displayList(L) + +#Selection sort - See Janson Ch 7 +def selSort(Names): + L = Names[:] + for i in range(len(L)): + smallest = i + for j in range(i+1, len(L)): + if L[j] < L[smallest]: #find smallest value + smallest = j #swap it to front + L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion + displayList(L) + +#Quick sort - See Janson Ch 7 +def qsortHolder(Names): + L = Names[:] #pass List, first and last + quick_sort(L, 0, len(L) -1) #Start process + displayList(L) + +def quick_sort(L, first, last): #Quicksort is a partition sort + if first >= last: + return L + pivot = L[first] + low = first + high = last + while low < high: + while L[high] > pivot: + high = high -1 + while L[low] < pivot: + low = low + 1 + if low <= high: + L[high], L[low] = L[low], L[high] + low = low + 1 + high = high -1 + quick_sort(L, first, low -1) #continue splitting - sort small lsist + quick_sort(L, low, last) + +#Linear Search - no need for Ordered list +def linearSearch(): + L = Names[:] + found = False + for l in L: + if l == value['linear']: #Check each value + found = True + window.FindElement('display').Update('Linear search\n' + l + ' found.') + break + if not found: + window.FindElement('display').Update(value['linear'] + ' was \nNot found') + +#Binary Search - only works for ordered lists +def binarySearch(): + L = ListDisplayed[:] #get List currently in multiline display + lo = 0 + hi = len(L)-1 + found = False #Start with found is Flase + while lo <= hi: + mid = (lo + hi) //2 #Start in middle + if L[mid] == value['binary']: #get the value from the search box + window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.') + found = True #If found display + break #and stop + elif L[mid] < value['binary']: + lo = mid + 1 #Search in top half + else: + hi = mid - 1 #Search in lower half + if not found: #If we get to end - display not found + window.FindElement('display').Update(value['binary'] + ' was \nNot found') + + +while True: + button, value = window.Read() + if button is not None: + if button == 'Original list': + displayList(Names) + if button == 'Default sort': + default(Names) + if button == 'Sort: selection': + selSort(Names) + if button == 'Sort: quick': + qsortHolder(Names) + if button == 'Linear Search': + linearSearch() + if button == 'Binary Search': + binarySearch() + else: + break + diff --git a/ProgrammingClassExamples/6e PSG sort and search (listbox) TODO.py b/ProgrammingClassExamples/6e PSG sort and search (listbox) TODO.py new file mode 100644 index 000000000..68d84be4e --- /dev/null +++ b/ProgrammingClassExamples/6e PSG sort and search (listbox) TODO.py @@ -0,0 +1,130 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg + +sg.SetOptions (font =('Calibri',12,'bold')) + + +#setup column (called column1) of buttons to sue in layout + +column1 = [[sg.ReadButton('Original list', size = (13,1))], + [sg.ReadButton('Default sort', size = (13,1))], + [sg.ReadButton('Sort: selection',size = (13,1))], + [sg.ReadButton('Sort: quick', size = (13,1))]] + +layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))], +[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)], + [sg.Text('_'*32,font = ('Calibri', 12))], + [sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')], + [sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))], + ] + +window = sg.Window('Search and Sort Demo').Layout(layout) + +#names for Demo, could be loaded from a file +Names= ['Roberta', 'Kylie', 'Jenny', 'Helen', + 'Andrea', 'Meredith','Deborah','Pauline', + 'Belinda', 'Wendy'] + +#function to display list +def displayList(List): + global ListDisplayed #store list in Multiline text globally + ListDisplayed = List + display = '' + for l in List: #add list elements with new line + display = display + l + '\n' + window.FindElement('display').Update(display) + +#use inbuilt python sort +def default(Names): + L = Names[:] + L.sort() #inbuilt sort + displayList(L) + +#Selection sort - See Janson Ch 7 +def selSort(Names): + L = Names[:] + for i in range(len(L)): + smallest = i + for j in range(i+1, len(L)): + if L[j] < L[smallest]: #find smallest value + smallest = j #swap it to front + L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion + displayList(L) + +#Quick sort - See Janson Ch 7 +def qsortHolder(Names): + L = Names[:] #pass List, first and last + quick_sort(L, 0, len(L) -1) #Start process + displayList(L) + +def quick_sort(L, first, last): #Quicksort is a partition sort + if first >= last: + return L + pivot = L[first] + low = first + high = last + while low < high: + while L[high] > pivot: + high = high -1 + while L[low] < pivot: + low = low + 1 + if low <= high: + L[high], L[low] = L[low], L[high] + low = low + 1 + high = high -1 + quick_sort(L, first, low -1) #continue splitting - sort small lsist + quick_sort(L, low, last) + +#Linear Search - no need for Ordered list +def linearSearch(): + L = Names[:] + found = False + for l in L: + if l == value['linear']: #Check each value + found = True + window.FindElement('display').Update('Linear search\n' + l + ' found.') + break + if not found: + window.FindElement('display').Update(value['linear'] + ' was \nNot found') + +#Binary Search - only works for ordered lists +def binarySearch(): + L = ListDisplayed[:] #get List currently in multiline display + lo = 0 + hi = len(L)-1 + found = False #Start with found is Flase + while lo <= hi: + mid = (lo + hi) //2 #Start in middle + if L[mid] == value['binary']: #get the value from the search box + window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.') + found = True #If found display + break #and stop + elif L[mid] < value['binary']: + lo = mid + 1 #Search in top half + else: + hi = mid - 1 #Search in lower half + if not found: #If we get to end - display not found + window.FindElement('display').Update(value['binary'] + ' was \nNot found') + + +while True: + button, value = window.Read() + if button is not None: + if button == 'Original list': + displayList(Names) + if button == 'Default sort': + default(Names) + if button == 'Sort: selection': + selSort(Names) + if button == 'Sort: quick': + qsortHolder(Names) + if button == 'Linear Search': + linearSearch() + if button == 'Binary Search': + binarySearch() + else: + break + diff --git a/ProgrammingClassExamples/7a PSG Text file save and retrieve.py b/ProgrammingClassExamples/7a PSG Text file save and retrieve.py new file mode 100644 index 000000000..eea4bf0fa --- /dev/null +++ b/ProgrammingClassExamples/7a PSG Text file save and retrieve.py @@ -0,0 +1,59 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +import PySimpleGUI as sg +import os #to work with windows OS + +sg.ChangeLookAndFeel('GreenTan') +sg.SetOptions(font = ('Calibri', 12, 'bold')) + +layout = [ + [sg.Text('Enter a Name and four Marks')], + [sg.Text('Name:', size =(10,1)), sg.InputText(size = (12,1), key = 'name')], + [sg.Text('Mark1:', size =(10,1)), sg.InputText(size = (6,1), key = 'm1')], + [sg.Text('Mark2:', size =(10,1)), sg.InputText(size = (6,1), key = 'm2')], + [sg.Text('Mark3:', size =(10,1)), sg.InputText(size = (6,1), key = 'm3')], + [sg.Text('Mark4:', size =(10,1)), sg.InputText(size = (6,1), key = 'm4')], + [sg.ReadButton('Save', size = (8,1),key = 'save'), sg.Text('Press to Save to file')], + [sg.ReadButton('Display',size = (8,1), key = 'display'), sg.Text('To retrieve and Display')], + [sg.Multiline(size = (28,4), key = 'multiline')]] + +window = sg.Window('Simple Average Finder').Layout(layout) + + +while True: + button, value = window.Read() #value is a dictionary holding name and marks (4) + if button is not None: + #initialise variables + total = 0.0 + index = '' + Name = value['name'] #get name + dirname, filename = os.path.split(os.path.abspath(__file__)) #get pathname to current file + pathname = dirname + '\\results.txt' #add desired file name for saving to path + + #needs validation and try/catch error checking, will crash if blank or text entry for marks + + if button == 'save': + for i in range (1,5): + index = 'm' + str(i) #create dictionary index m1 ... m4 + total += float(value[index]) + average = total/4 + f = open(pathname, 'w') #open file and save + print (Name, file = f) + print (total, file = f) + print (average, file = f) + f.close() + + #some error checking for missing file needed here + + if button == 'display': + #This loads the file line by line into a list called data. + #the strip() removes whitespaces from beginning and end of each line. + data = [line.strip() for line in open(pathname)] + #create single string to display in multiline object. + string = 'Name: ' + data[0] +'\nTotal: ' + str(data[1]) + '\nAverage: ' + str(data[2]) + window.FindElement('multiline').Update(string) + else: + break + diff --git a/ProgrammingClassExamples/8a PSG Data to plot from csv file.py b/ProgrammingClassExamples/8a PSG Data to plot from csv file.py new file mode 100644 index 000000000..99d3a3203 --- /dev/null +++ b/ProgrammingClassExamples/8a PSG Data to plot from csv file.py @@ -0,0 +1,38 @@ +#Matplotlib, pyplt and csv +#Tony Crewe +#Sep 2017 - updated Sep 2018 + +import matplotlib.pyplot as plt +import csv +from matplotlib.ticker import MaxNLocator + + +x=[] +y=[] + +with open('weight 20182.csv', 'r', encoding = 'utf-8-sig') as csvfile: + plots = csv.reader(csvfile) + for data in plots: + var1 = (data[0]) #get heading for x and y axes + var2 = (data[1]) + break + for data in plots: #get values - add to x list and y list + x.append(data[0]) + y.append(float(data[1])) + + +ax = plt.subplot(1,1,1) +ax.set_ylim([82, 96]) +ax.xaxis.set_major_locator(MaxNLocator(10)) +ax.spines['right'].set_color('none') +ax.spines['top'].set_color('none') + +plt.plot(x,y, label = 'data loaded\nfrom csv file') +plt.axhline(y = 85.5, color = 'orange', linestyle = '--', label = 'target') +plt.xlabel(var1) +plt.ylabel(var2) +plt.title('weight loss from\n first quarter 2018') + + +plt.legend() +plt.show() diff --git a/ProgrammingClassExamples/8b PSG Tables and calc from csv file.py b/ProgrammingClassExamples/8b PSG Tables and calc from csv file.py new file mode 100644 index 000000000..442e15f85 --- /dev/null +++ b/ProgrammingClassExamples/8b PSG Tables and calc from csv file.py @@ -0,0 +1,41 @@ +#PySimple examples (v 3.8) +#Tony Crewe +#Sep 2018 + +#Based of Example program from MikeTheWatchGuy +#https://gitlab.com/lotspaih/PySimpleGUI + +import sys +import PySimpleGUI as sg +import csv + +def table_example(): + filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),)) + #populate table with file contents + #Assume we know csv has haeding in row 1 + #assume we know 7 columns of data - relevenat to AFL w/o Pts or % shown + #data will be data[0] = team, data [1] P, data [2] W, data[3] L + #data [4] D, data[5] F, data[6] A + #no error checking or validation used. + + data = [] + header_list = [] + with open(filename, "r") as infile: + reader = csv.reader(infile) + for i in range (1): #get headings + header = next(reader) + data = list(reader) # read everything else into a list of rows + + + col_layout = [[sg.Table(values=data, headings=header, max_col_width=25, + auto_size_columns=True, justification='right', size=(None, len(data)))]] + + canvas_size = (13*10*len(header), 600) # estimate canvas size - 13 pixels per char * 10 char per column * num columns + layout = [[sg.Column(col_layout, size=canvas_size, scrollable=True)],] + + window = sg.Window('Table', grab_anywhere=False).Layout(layout) + b, v = window.Read() + + sys.exit(69) + +table_example() diff --git a/ProgrammingClassExamples/9a Plot Matplotlib numpy pyplot(y=sinx).py b/ProgrammingClassExamples/9a Plot Matplotlib numpy pyplot(y=sinx).py new file mode 100644 index 000000000..792408a70 --- /dev/null +++ b/ProgrammingClassExamples/9a Plot Matplotlib numpy pyplot(y=sinx).py @@ -0,0 +1,22 @@ +#matplotlib, numpy, pyplot +#Tony Crewe +#Sep 2017 - updated Sep 2018 + +import matplotlib.pyplot as plt +import numpy as np + + +fig=plt.figure() +ax = fig.add_subplot(111) +x = np.linspace(-np.pi*2, np.pi*2, 100) +y= np.sin(x) +ax.plot(x,y) + +ax.set_title('sin(x)') + + +plt.show() + + + + diff --git a/ProgrammingClassExamples/9b Plot (axes moved).py b/ProgrammingClassExamples/9b Plot (axes moved).py new file mode 100644 index 000000000..7dfba0529 --- /dev/null +++ b/ProgrammingClassExamples/9b Plot (axes moved).py @@ -0,0 +1,27 @@ +#matplotlib, numpy, pyplot +#Tony Crewe +#Sep 2017 - updated Sep 2018import matplotlib.pyplot as plt +import numpy as np +import matplotlib.pyplot as plt + + +fig=plt.figure() +ax = fig.add_subplot(111) +x = np.linspace(-np.pi*2, np.pi*2, 100) +y= np.sin(x) +ax.plot(x,y) + +ax.set_title('sin(x)') +#centre bottom and keft axes to zero + +ax.spines['left'].set_position('zero') +ax.spines['right'].set_color('none') +ax.spines['bottom'].set_position('zero') +ax.spines['top'].set_color('none') + + +plt.show() + + + + diff --git a/ProgrammingClassExamples/9c Plot (axes pi format).py b/ProgrammingClassExamples/9c Plot (axes pi format).py new file mode 100644 index 000000000..75c882372 --- /dev/null +++ b/ProgrammingClassExamples/9c Plot (axes pi format).py @@ -0,0 +1,28 @@ +#Plt using matplylib, plotly and numpy +#Tony Crewe +#Sep 2017 updated Sep 2018 + +import matplotlib.pyplot as plt +import numpy as np +import matplotlib.ticker as ticker + +fig=plt.figure() +ax = fig.add_subplot(111) +x = np.linspace(-np.pi*2, np.pi*2, 100) +y= np.sin(x) +ax.plot(x/np.pi,y) + +ax.set_title('sin(x)') +ax.spines['left'].set_position('zero') +ax.spines['right'].set_color('none') +ax.spines['bottom'].set_position('zero') +ax.spines['top'].set_color('none') + +#Format axes - nicer eh! +ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$')) + +plt.show() + + + + diff --git a/ProgrammingClassExamples/Text files.py b/ProgrammingClassExamples/Text files.py new file mode 100644 index 000000000..cc1d22332 --- /dev/null +++ b/ProgrammingClassExamples/Text files.py @@ -0,0 +1,88 @@ +# TCC +#20/1/18 Oz date + +from tkinter import * + +def callback(event): #used to allow Return key as well as + calculate() # button press for mark entry + + +def calculate(): + global i, total,name + name = entry_name.get() #get the name and prevent another + mark[i] = entry_mark.get() + label_name.configure(state = DISABLED) + entry_name.configure(state = DISABLED) + mark[i] = entry_mark.get() #get and store in mark list and clear entry + entry_mark.delete(0,END) + i = i + 1 #get total i - needs to be global + if i == 4: #if four marks - stop + button_done.configure(state = NORMAL) + button_calculate.configure(state = DISABLED) + +def done(): + total = 0 + for m in mark: #total marks - convery to integer + total += int(m) + average = total/4 #calculate average + f = open(pathname, 'w') + print(name, file= f) + print(total, file= f) #write to file + print(average, file= f) + f.close() + button_done.configure(state = DISABLED) #stop button being pressed again + button_display.configure(state = NORMAL) + + +def display(): + #create list of three valuesand combine elemnets into one string - use \n for new line + data = [line.strip() for line in open(pathname)] + s= 'Name: ' + data[0] +'\nTotal: ' + str(data[1]) + '\nAverage: ' + str(data[2]) + label_displayresults.configure(text = s) + + +root = Tk() +root.title('text files') + +#set up controls +label_instructs = Label(justify = LEFT, padx = 10, pady=10,width = 30, height =4, text = 'Enter a Name then a Mark then press\nCalculate, do this 4 times.Then press\nDone to Save Name, Total and Average.') +label_name = Label(text='Name: ', width = 8) +entry_name = Entry(width = 8) +label_mark = Label(text='Mark: ', width = 8) +entry_mark = Entry(width = 8) +button_calculate = Button(text = 'Calculate', command=calculate) +button_done= Button(pady = 8, text='Done', command = done, state = DISABLED) +button_display = Button(pady =8,text = 'Display', command=display, state = DISABLED) +label_displaytext = Label(justify = LEFT, text='Press display to\nretrieve recent\nTotal & Average') +label_displayresults=Label(justify = LEFT, padx = 10, height = 5,) + +#set up positioning of controls +label_instructs.grid(row = 0, columnspan = 3) +label_name.grid(row = 1, column = 0) +entry_name.grid(row = 1, column = 1) +label_mark.grid(row = 2, column = 0) +entry_mark.grid(row = 2, column = 1) + +entry_mark.bind('', callback) #create binding for Return key for mark entry box + +button_calculate.grid(row =3, column = 0) +button_done.grid(row = 3, column = 1) +button_display.grid(row = 4, column = 0) +label_displaytext.grid(row = 4, column = 1) +label_displayresults.grid(row = 5, columnspan = 2) + +#global variables when used in more than one function +global i +global mark +global total +global average +i=total=0 +mark = [0,0,0,0] +average = 0.0 +entry_name.focus() #set initial focus + +global pathname + +pathname = "C:\\Users\\tcrewe\\Dropbox\\01 Teaching folders\\07 TCC Python stuff\\TCC py files\\TCC sample files\wordlist.txt" + +mainloop() diff --git a/PySimpleGUI.py b/PySimpleGUI.py new file mode 100644 index 000000000..705d87f8c --- /dev/null +++ b/PySimpleGUI.py @@ -0,0 +1,4713 @@ +#!/usr/bin/python3 +import tkinter as tk +from tkinter import filedialog +from tkinter.colorchooser import askcolor +from tkinter import ttk +import tkinter.scrolledtext as tkst +import tkinter.font +import datetime +import sys +import textwrap +import pickle +import calendar + + +g_time_start = 0 +g_time_end = 0 +g_time_delta = 0 + +import time +def TimerStart(): + global g_time_start + + g_time_start = time.time() + +def TimerStop(): + global g_time_delta, g_time_end + + g_time_end = time.time() + g_time_delta = g_time_end - g_time_start + print(g_time_delta) + +# ----====----====----==== Constants the user CAN safely change ====----====----====----# +DEFAULT_WINDOW_ICON = 'default_icon.ico' +DEFAULT_ELEMENT_SIZE = (45,1) # In CHARACTERS +DEFAULT_BUTTON_ELEMENT_SIZE = (10,1) # In CHARACTERS +DEFAULT_MARGINS = (10,5) # Margins for each LEFT/RIGHT margin is first term +DEFAULT_ELEMENT_PADDING = (5,3) # Padding between elements (row, col) in pixels +DEFAULT_AUTOSIZE_TEXT = True +DEFAULT_AUTOSIZE_BUTTONS = True +DEFAULT_FONT = ("Helvetica", 10) +DEFAULT_TEXT_JUSTIFICATION = 'left' +DEFAULT_BORDER_WIDTH = 1 +DEFAULT_AUTOCLOSE_TIME = 3 # time in seconds to show an autoclose form +DEFAULT_DEBUG_WINDOW_SIZE = (80,20) +DEFAULT_WINDOW_LOCATION = (None,None) +MAX_SCROLLED_TEXT_BOX_HEIGHT = 50 +DEFAULT_TOOLTIP_TIME = 400 +#################### COLOR STUFF #################### +BLUES = ("#082567","#0A37A3","#00345B") +PURPLES = ("#480656","#4F2398","#380474") +GREENS = ("#01826B","#40A860","#96D2AB", "#00A949","#003532") +YELLOWS = ("#F3FB62", "#F0F595") +TANS = ("#FFF9D5","#F4EFCF","#DDD8BA") +NICE_BUTTON_COLORS = ((GREENS[3], TANS[0]), ('#000000','#FFFFFF'),('#FFFFFF', '#000000'), (YELLOWS[0], PURPLES[1]), + (YELLOWS[0], GREENS[3]), (YELLOWS[0], BLUES[2])) + +COLOR_SYSTEM_DEFAULT = '1234567890' # Colors should never be this long +if sys.platform == 'darwin': + DEFAULT_BUTTON_COLOR = COLOR_SYSTEM_DEFAULT # Foreground, Background (None, None) == System Default + OFFICIAL_PYSIMPLEGUI_BUTTON_COLOR = COLOR_SYSTEM_DEFAULT # Colors should never be this long +else: + DEFAULT_BUTTON_COLOR = ('white', BLUES[0]) # Foreground, Background (None, None) == System Default + OFFICIAL_PYSIMPLEGUI_BUTTON_COLOR = ('white', BLUES[0]) # Colors should never be this long + +DEFAULT_ERROR_BUTTON_COLOR =("#FFFFFF", "#FF0000") +DEFAULT_BACKGROUND_COLOR = None +DEFAULT_ELEMENT_BACKGROUND_COLOR = None +DEFAULT_ELEMENT_TEXT_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR = None +DEFAULT_TEXT_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_INPUT_ELEMENTS_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_INPUT_TEXT_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_SCROLLBAR_COLOR = None +# DEFAULT_BUTTON_COLOR = (YELLOWS[0], PURPLES[0]) # (Text, Background) or (Color "on", Color) as a way to remember +# DEFAULT_BUTTON_COLOR = (GREENS[3], TANS[0]) # Foreground, Background (None, None) == System Default +# DEFAULT_BUTTON_COLOR = (YELLOWS[0], GREENS[4]) # Foreground, Background (None, None) == System Default +# DEFAULT_BUTTON_COLOR = ('white', 'black') # Foreground, Background (None, None) == System Default +# DEFAULT_BUTTON_COLOR = (YELLOWS[0], PURPLES[2]) # Foreground, Background (None, None) == System Default +# DEFAULT_PROGRESS_BAR_COLOR = (GREENS[2], GREENS[0]) # a nice green progress bar +# DEFAULT_PROGRESS_BAR_COLOR = (BLUES[1], BLUES[1]) # a nice green progress bar +# DEFAULT_PROGRESS_BAR_COLOR = (BLUES[0], BLUES[0]) # a nice green progress bar +# DEFAULT_PROGRESS_BAR_COLOR = (PURPLES[1],PURPLES[0]) # a nice purple progress bar + +# A transparent button is simply one that matches the background +TRANSPARENT_BUTTON = ('#F0F0F0', '#F0F0F0') +#-------------------------------------------------------------------------------- +# Progress Bar Relief Choices +RELIEF_RAISED = 'raised' +RELIEF_SUNKEN = 'sunken' +RELIEF_FLAT = 'flat' +RELIEF_RIDGE = 'ridge' +RELIEF_GROOVE = 'groove' +RELIEF_SOLID = 'solid' + +DEFAULT_PROGRESS_BAR_COLOR = (GREENS[0], '#D0D0D0') # a nice green progress bar +DEFAULT_PROGRESS_BAR_SIZE = (25,20) # Size of Progress Bar (characters for length, pixels for width) +DEFAULT_PROGRESS_BAR_BORDER_WIDTH=1 +DEFAULT_PROGRESS_BAR_RELIEF = RELIEF_GROOVE +PROGRESS_BAR_STYLES = ('default','winnative', 'clam', 'alt', 'classic', 'vista', 'xpnative') +DEFAULT_PROGRESS_BAR_STYLE = 'default' +DEFAULT_METER_ORIENTATION = 'Horizontal' +DEFAULT_SLIDER_ORIENTATION = 'vertical' +DEFAULT_SLIDER_BORDER_WIDTH=1 +DEFAULT_SLIDER_RELIEF = tk.FLAT +DEFAULT_FRAME_RELIEF = tk.GROOVE + +DEFAULT_LISTBOX_SELECT_MODE = tk.SINGLE +SELECT_MODE_MULTIPLE = tk.MULTIPLE +LISTBOX_SELECT_MODE_MULTIPLE = 'multiple' +SELECT_MODE_BROWSE = tk.BROWSE +LISTBOX_SELECT_MODE_BROWSE = 'browse' +SELECT_MODE_EXTENDED = tk.EXTENDED +LISTBOX_SELECT_MODE_EXTENDED = 'extended' +SELECT_MODE_SINGLE = tk.SINGLE +LISTBOX_SELECT_MODE_SINGLE = 'single' + +TABLE_SELECT_MODE_NONE = tk.NONE +TABLE_SELECT_MODE_BROWSE = tk.BROWSE +TABLE_SELECT_MODE_EXTENDED = tk.EXTENDED +DEFAULT_TABLE_SECECT_MODE = TABLE_SELECT_MODE_EXTENDED + +TITLE_LOCATION_TOP = tk.N +TITLE_LOCATION_BOTTOM = tk.S +TITLE_LOCATION_LEFT = tk.W +TITLE_LOCATION_RIGHT = tk.E +TITLE_LOCATION_TOP_LEFT = tk.NW +TITLE_LOCATION_TOP_RIGHT = tk.NE +TITLE_LOCATION_BOTTOM_LEFT = tk.SW +TITLE_LOCATION_BOTTOM_RIGHT = tk.SE + + + + + +# DEFAULT_METER_ORIENTATION = 'Vertical' +# ----====----====----==== Constants the user should NOT f-with ====----====----====----# +ThisRow = 555666777 # magic number + + +# DEFAULT_WINDOW_ICON = '' +MESSAGE_BOX_LINE_WIDTH = 60 + +# a shameful global variable. This represents the top-level window information. Needed because opening a second window is different than opening the first. +class MyWindows(): + def __init__(self): + self.NumOpenWindows = 0 + self.user_defined_icon = None + + def Decrement(self): + self.NumOpenWindows -= 1 * (self.NumOpenWindows != 0) # decrement if not 0 + # print('---- DECREMENTING Num Open Windows = {} ---'.format(self.NumOpenWindows)) + + def Increment(self): + self.NumOpenWindows += 1 + # print('++++ INCREMENTING Num Open Windows = {} ++++'.format(self.NumOpenWindows)) + +_my_windows = MyWindows() # terrible hack using globals... means need a class for collecing windows + +# ====================================================================== # +# One-liner functions that are handy as f_ck # +# ====================================================================== # +def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue) + +# ====================================================================== # +# Enums for types # +# ====================================================================== # +# ------------------------- Button types ------------------------- # +#todo Consider removing the Submit, Cancel types... they are just 'RETURN' type in reality +#uncomment this line and indent to go back to using Enums +# class ButtonType(Enum): +BUTTON_TYPE_BROWSE_FOLDER = 1 +BUTTON_TYPE_BROWSE_FILE = 2 +BUTTON_TYPE_BROWSE_FILES = 21 +BUTTON_TYPE_SAVEAS_FILE = 3 +BUTTON_TYPE_CLOSES_WIN = 5 +BUTTON_TYPE_CLOSES_WIN_ONLY = 6 +BUTTON_TYPE_READ_FORM = 7 +BUTTON_TYPE_REALTIME = 9 +BUTTON_TYPE_CALENDAR_CHOOSER = 30 +BUTTON_TYPE_COLOR_CHOOSER = 40 + +# ------------------------- Element types ------------------------- # +# class ElementType(Enum): +ELEM_TYPE_TEXT = 1 +ELEM_TYPE_INPUT_TEXT = 20 +ELEM_TYPE_INPUT_COMBO = 21 +ELEM_TYPE_INPUT_OPTION_MENU = 22 +ELEM_TYPE_INPUT_RADIO = 5 +ELEM_TYPE_INPUT_MULTILINE = 7 +ELEM_TYPE_INPUT_CHECKBOX = 8 +ELEM_TYPE_INPUT_SPIN = 9 +ELEM_TYPE_BUTTON = 3 +ELEM_TYPE_IMAGE = 30 +ELEM_TYPE_CANVAS = 40 +ELEM_TYPE_FRAME = 41 +ELEM_TYPE_GRAPH = 42 +ELEM_TYPE_TAB = 50 +ELEM_TYPE_TAB_GROUP = 51 +ELEM_TYPE_INPUT_SLIDER = 10 +ELEM_TYPE_INPUT_LISTBOX = 11 +ELEM_TYPE_OUTPUT = 300 +ELEM_TYPE_COLUMN = 555 +ELEM_TYPE_MENUBAR = 600 +ELEM_TYPE_PROGRESS_BAR = 200 +ELEM_TYPE_BLANK = 100 +ELEM_TYPE_TABLE = 700 + +# ------------------------- Popup Buttons Types ------------------------- # +POPUP_BUTTONS_YES_NO = 1 +POPUP_BUTTONS_CANCELLED = 2 +POPUP_BUTTONS_ERROR = 3 +POPUP_BUTTONS_OK_CANCEL = 4 +POPUP_BUTTONS_OK = 0 +POPUP_BUTTONS_NO_BUTTONS = 5 + + +# ------------------------------------------------------------------------- # +# ToolTip used by the Elements # +# ------------------------------------------------------------------------- # + +class ToolTip: + """ Create a tooltip for a given widget + + (inspired by https://stackoverflow.com/a/36221216) + """ + + def __init__(self, widget, text, timeout=DEFAULT_TOOLTIP_TIME): + self.widget = widget + self.text = text + self.timeout = timeout + #self.wraplength = wraplength if wraplength else widget.winfo_screenwidth() // 2 + self.tipwindow = None + self.id = None + self.x = self.y = 0 + self.widget.bind("", self.enter) + self.widget.bind("", self.leave) + self.widget.bind("", self.leave) + + def enter(self, event=None): + self.schedule() + + def leave(self, event=None): + self.unschedule() + self.hidetip() + + def schedule(self): + self.unschedule() + self.id = self.widget.after(self.timeout, self.showtip) + + def unschedule(self): + if self.id: + self.widget.after_cancel(self.id) + self.id = None + + def showtip(self): + if self.tipwindow: + return + x = self.widget.winfo_rootx() + 20 + y = self.widget.winfo_rooty() + self.widget.winfo_height() - 20 + self.tipwindow = tk.Toplevel(self.widget) + self.tipwindow.wm_overrideredirect(True) + self.tipwindow.wm_geometry("+%d+%d" % (x, y)) + label = ttk.Label(self.tipwindow, text=self.text, justify=tk.LEFT, + background="#ffffe0", relief=tk.SOLID, borderwidth=1) + label.pack() + + def hidetip(self): + if self.tipwindow: + self.tipwindow.destroy() + self.tipwindow = None + + +# ---------------------------------------------------------------------- # +# Cascading structure.... Objects get larger # +# Button # +# Element # +# Row # +# Form # +# ---------------------------------------------------------------------- # +# ------------------------------------------------------------------------- # +# Element CLASS # +# ------------------------------------------------------------------------- # +class Element(): + def __init__(self, type, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + self.Size = size + self.Type = type + self.AutoSizeText = auto_size_text + self.Pad = DEFAULT_ELEMENT_PADDING if pad is None else pad + self.Font = font + + self.TKStringVar = None + self.TKIntVar = None + self.TKText = None + self.TKEntry = None + self.TKImage = None + + self.ParentForm=None + self.ParentContainer=None # will be a Form, Column, or Frame element + self.TextInputDefault = None + self.Position = (0,0) # Default position Row 0, Col 0 + self.BackgroundColor = background_color if background_color is not None else DEFAULT_ELEMENT_BACKGROUND_COLOR + self.TextColor = text_color if text_color is not None else DEFAULT_ELEMENT_TEXT_COLOR + self.Key = key # dictionary key for return values + self.Tooltip = tooltip + self.TooltipObject = None + + def FindReturnKeyBoundButton(self, form): + for row in form.Rows: + for element in row: + if element.Type == ELEM_TYPE_BUTTON: + if element.BindReturnKey: + return element + if element.Type == ELEM_TYPE_COLUMN: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + if element.Type == ELEM_TYPE_FRAME: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + if element.Type == ELEM_TYPE_TAB_GROUP: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + if element.Type == ELEM_TYPE_TAB: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + return None + + def TextClickedHandler(self, event): + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.DisplayText + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + + def ReturnKeyHandler(self, event): + MyForm = self.ParentForm + button_element = self.FindReturnKeyBoundButton(MyForm) + if button_element is not None: + button_element.ButtonCallBack() + + + def ListboxSelectHandler(self, event): + MyForm = self.ParentForm + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def ComboboxSelectHandler(self, event): + MyForm = self.ParentForm + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def CheckboxHandler(self): + MyForm = self.ParentForm + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() + + def TabGroupSelectHandler(self, event): + MyForm = self.ParentForm + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() + + def __del__(self): + try: + self.TKStringVar.__del__() + except: + pass + try: + self.TKIntVar.__del__() + except: + pass + try: + self.TKText.__del__() + except: + pass + try: + self.TKEntry.__del__() + except: + pass + +# ---------------------------------------------------------------------- # +# Input Class # +# ---------------------------------------------------------------------- # +class InputText(Element): + def __init__(self, default_text ='', size=(None, None), auto_size_text=None, password_char='', + justification=None, background_color=None, text_color=None, font=None, tooltip=None, do_not_clear=False, key=None, focus=False, pad=None): + ''' + Input a line of text Element + :param default_text: Default value to display + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param password_char: If non-blank, will display this character for every character typed + :param background_color: Color for Element. Text or RGB Hex + ''' + self.DefaultText = default_text + self.PasswordCharacter = password_char + bg = background_color if background_color is not None else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + self.Focus = focus + self.do_not_clear = do_not_clear + self.Justification = justification + super().__init__(ELEM_TYPE_INPUT_TEXT, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad, font=font, tooltip=tooltip) + + + def Update(self, value=None, disabled=None): + if disabled is True: + self.TKEntry['state'] = 'disabled' + elif disabled is False: + self.TKEntry['state'] = 'normal' + if value is not None: + try: + self.TKStringVar.set(value) + except: pass + self.DefaultText = value + + def Get(self): + return self.TKStringVar.get() + + def __del__(self): + super().__del__() + + +# ------------------------- INPUT TEXT Element lazy functions ------------------------- # +In = InputText +Input = InputText + +# ---------------------------------------------------------------------- # +# Combo # +# ---------------------------------------------------------------------- # +class InputCombo(Element): + def __init__(self, values, default_value=None, size=(None, None), auto_size_text=None, background_color=None, text_color=None, change_submits=False, disabled=False, key=None, pad=None, tooltip=None): + ''' + Input Combo Box Element (also called Dropdown box) + :param values: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + ''' + self.Values = values + self.DefaultValue = default_value + self.ChangeSubmits = change_submits + self.TKCombo = None + self.InitializeAsDisabled = disabled + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super().__init__(ELEM_TYPE_INPUT_COMBO, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + + def Update(self, value=None, values=None, disabled=None): + ''' + Allows updating of value list, and selecting value by string or index + :param value: value to be selected or None + :param values: list of values to populate InputCombo + :param disabled: update disabled status + :examples: + combo = InputCombo(['A','B','C']) + combo.Update(None, ['A','B','C','D','E']) # sets value list and selects 'A' value + combo.Update('B', ['A','B','C','D']) # sets value list and selects 'B' value + combo.Update('B') # selects 'B' value by string + combo.Update(1) # selects 'B' value by index + ''' + if values is not None: + try: + self.TKCombo['values'] = values + self.TKCombo.current(0) + except: pass + self.Values = values + if value is not None: + for index, v in enumerate(self.Values): + if v == value: + try: + self.TKCombo.current(index) + except: pass + self.DefaultValue = value + + elif value is not None: + try: + if isinstance(value, str): + self.TKCombo.set(self.TKCombo.index(value)) + elif isinstance(value, int): + self.TKCombo.current(value) + except: pass + + elif disabled == True: + self.TKCombo['state'] = 'disable' + elif disabled == False: + self.TKCombo['state'] = 'enable' + + + def __del__(self): + try: + self.TKCombo.__del__() + except: + pass + super().__del__() + +# ------------------------- INPUT COMBO Element lazy functions ------------------------- # +Combo = InputCombo +DropDown = InputCombo +Drop = InputCombo + +# ---------------------------------------------------------------------- # +# Option Menu # +# ---------------------------------------------------------------------- # +class InputOptionMenu(Element): + def __init__(self, values, default_value=None, size=(None, None), auto_size_text=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Input Combo Box Element (also called Dropdown box) + :param values: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + ''' + self.Values = values + self.DefaultValue = default_value + self.TKOptionMenu = None + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super().__init__(ELEM_TYPE_INPUT_OPTION_MENU, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + + def Update(self, value=None, values=None, disabled=None): + if values is not None: + self.Values = values + if self.Values is not None: + for index, v in enumerate(self.Values): + if v == value: + try: + self.TKStringVar.set(value) + except: pass + self.DefaultValue = value + break + if disabled == True: + self.TKOptionMenu['state'] = 'disabled' + elif disabled == False: + self.TKOptionMenu['state'] = 'normal' + + + def __del__(self): + try: + self.TKOptionMenu.__del__() + except: + pass + super().__del__() + + +# ------------------------- OPTION MENU Element lazy functions ------------------------- # +OptionMenu = InputOptionMenu + +# ---------------------------------------------------------------------- # +# Listbox # +# ---------------------------------------------------------------------- # +class Listbox(Element): + def __init__(self, values, default_values=None, select_mode=None, change_submits=False, bind_return_key=False, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Listbox Element + :param values: + :param select_mode: SELECT_MODE_BROWSE, SELECT_MODE_EXTENDED, SELECT_MODE_MULTIPLE, SELECT_MODE_SINGLE + :param font: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex ''' + self.Values = values + self.DefaultValues = default_values + self.TKListbox = None + self.ChangeSubmits = change_submits + self.BindReturnKey = bind_return_key + if select_mode == LISTBOX_SELECT_MODE_BROWSE: + self.SelectMode = SELECT_MODE_BROWSE + elif select_mode == LISTBOX_SELECT_MODE_EXTENDED: + self.SelectMode = SELECT_MODE_EXTENDED + elif select_mode == LISTBOX_SELECT_MODE_MULTIPLE: + self.SelectMode = SELECT_MODE_MULTIPLE + elif select_mode == LISTBOX_SELECT_MODE_SINGLE: + self.SelectMode = SELECT_MODE_SINGLE + else: + self.SelectMode = DEFAULT_LISTBOX_SELECT_MODE + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + + super().__init__(ELEM_TYPE_INPUT_LISTBOX, size=size, auto_size_text=auto_size_text, font=font, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + + def Update(self, values=None, disabled=None): + if disabled == True: + self.TKListbox.configure(state='disabled') + elif disabled == False: + self.TKListbox.configure(state='normal') + if values is not None: + self.TKListbox.delete(0, 'end') + for item in values: + self.TKListbox.insert(tk.END, item) + self.TKListbox.selection_set(0, 0) + self.Values = values + + + + def SetValue(self, values): + for index, item in enumerate(self.Values): + try: + if item in values: + self.TKListbox.selection_set(index) + else: + self.TKListbox.selection_clear(index) + except: pass + self.DefaultValues = values + + def __del__(self): + try: + self.TKListBox.__del__() + except: + pass + super().__del__() + + + +# ---------------------------------------------------------------------- # +# Radio # +# ---------------------------------------------------------------------- # +class Radio(Element): + def __init__(self, text, group_id, default=False, size=(None, None), auto_size_text=None, background_color=None, text_color=None, font=None, key=None, pad=None, tooltip=None): + ''' + Radio Button Element + :param text: + :param group_id: + :param default: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + :param font: + ''' + self.InitialState = default + self.Text = text + self.TKRadio = None + self.GroupID = group_id + self.Value = None + self.TextColor = text_color if text_color else DEFAULT_TEXT_COLOR + + super().__init__(ELEM_TYPE_INPUT_RADIO, size=size, auto_size_text=auto_size_text, font=font, background_color=background_color, text_color=self.TextColor, key=key, pad=pad, tooltip=tooltip) + + def Update(self, value=None, disabled=None): + location = EncodeRadioRowCol(self.Position[0], self.Position[1]) + if value is not None: + try: + self.TKIntVar.set(location) + except: pass + self.InitialState = value + if disabled == True: + self.TKRadio['state'] = 'disabled' + elif disabled == False: + self.TKRadio['state'] = 'normal' + + def __del__(self): + try: + self.TKRadio.__del__() + except: + pass + super().__del__() + +# ---------------------------------------------------------------------- # +# Checkbox # +# ---------------------------------------------------------------------- # +class Checkbox(Element): + def __init__(self, text, default=False, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, change_submits=False, key=None, pad=None, tooltip=None): + ''' + Check Box Element + :param text: + :param default: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + :param font: + ''' + self.Text = text + self.InitialState = default + self.Value = None + self.TKCheckbutton = None + self.TextColor = text_color if text_color else DEFAULT_TEXT_COLOR + self.ChangeSubmits = change_submits + + super().__init__(ELEM_TYPE_INPUT_CHECKBOX, size=size, auto_size_text=auto_size_text, font=font, + background_color=background_color, text_color=self.TextColor, key=key, pad=pad, tooltip=tooltip) + + def Get(self): + return self.TKIntVar.get() + + def Update(self, value=None, disabled=None): + if value is not None: + try: + self.TKIntVar.set(value) + self.InitialState = value + except: pass + if disabled == True: + self.TKCheckbutton.configure(state='disabled') + elif disabled == False: + self.TKCheckbutton.configure(state='normal') + + + def __del__(self): + super().__del__() + + +# ------------------------- CHECKBOX Element lazy functions ------------------------- # +CB = Checkbox +CBox = Checkbox +Check = Checkbox + + +# ---------------------------------------------------------------------- # +# Spin # +# ---------------------------------------------------------------------- # + +class Spin(Element): + # Values = None + # TKSpinBox = None + def __init__(self, values, initial_value=None, change_submits=False, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Spin Box Element + :param values: + :param initial_value: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + :param font: + ''' + self.Values = values + self.DefaultValue = initial_value + self.ChangeSubmits = change_submits + self.TKSpinBox = None + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super().__init__(ELEM_TYPE_INPUT_SPIN, size, auto_size_text, font=font,background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + return + + def Update(self, value=None, values=None, disabled=None): + if values != None: + old_value = self.TKStringVar.get() + self.Values = values + self.TKSpinBox.configure(values=values) + self.TKStringVar.set(old_value) + if value is not None: + try: + self.TKStringVar.set(value) + except: pass + self.DefaultValue = value + if disabled == True: + self.TKSpinBox.configure(state='disabled') + elif disabled == False: + self.TKSpinBox.configure(state='normal') + + + def SpinChangedHandler(self, event): + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def __del__(self): + try: + self.TKSpinBox.__del__() + except: + pass + super().__del__() + +# ---------------------------------------------------------------------- # +# Multiline # +# ---------------------------------------------------------------------- # +class Multiline(Element): + def __init__(self, default_text='', enter_submits = False, autoscroll=False, size=(None, None), auto_size_text=None, background_color=None, text_color=None, do_not_clear=False, key=None, focus=False, pad=None, tooltip=None): + ''' + Input Multi-line Element + :param default_text: + :param enter_submits: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + ''' + self.DefaultText = default_text + self.EnterSubmits = enter_submits + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + self.Focus = focus + self.do_not_clear = do_not_clear + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + self.Autoscroll = autoscroll + + super().__init__(ELEM_TYPE_INPUT_MULTILINE, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + return + + def Update(self, value=None, disabled=None, append=False): + if value is not None: + try: + if not append: + self.TKText.delete('1.0', tk.END) + self.TKText.insert(tk.END, value) + except: pass + self.DefaultText = value + if self.Autoscroll: + self.TKText.see(tk.END) + if disabled == True: + self.TKText.configure(state='disabled') + elif disabled == False: + self.TKText.configure(state='normal') + + def Get(self): + return self.TKText.get(1.0, tk.END) + + + def __del__(self): + super().__del__() + +# ---------------------------------------------------------------------- # +# Text # +# ---------------------------------------------------------------------- # +class Text(Element): + def __init__(self, text, size=(None, None), auto_size_text=None, click_submits=None, relief=None, font=None, text_color=None, background_color=None,justification=None, pad=None, key=None, tooltip=None): + ''' + Text Element - Displays text in your form. Can be updated in non-blocking forms + :param text: The text to display + :param size: Size of Element in Characters + :param auto_size_text: True if the field should shrink to fit the text + :param font: Font name and size ("name", size) + :param text_color: Text Color name or RGB hex value '#RRGGBB' + :param background_color: Background color for text (name or RGB Hex) + :param justification: 'left', 'right', 'center' + ''' + self.DisplayText = text + self.TextColor = text_color if text_color else DEFAULT_TEXT_COLOR + self.Justification = justification + self.Relief = relief + self.ClickSubmits = click_submits + if background_color is None: + bg = DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR + else: + bg = background_color + super().__init__(ELEM_TYPE_TEXT, size, auto_size_text, background_color=bg, font=font if font else DEFAULT_FONT, text_color=self.TextColor, pad=pad, key=key, tooltip=tooltip) + return + + def Update(self, value = None, background_color=None, text_color=None, font=None): + if value is not None: + self.DisplayText=value + stringvar = self.TKStringVar + stringvar.set(value) + if background_color is not None: + self.TKText.configure(background=background_color) + if text_color is not None: + self.TKText.configure(fg=text_color) + if font is not None: + self.TKText.configure(font=font) + + + def __del__(self): + super().__del__() + + +# ------------------------- Text Element lazy functions ------------------------- # +Txt = Text +T = Text + + +# ---------------------------------------------------------------------- # +# TKProgressBar # +# Emulate the TK ProgressBar using canvas and rectangles +# ---------------------------------------------------------------------- # + +class TKProgressBar(): + def __init__(self, root, max, length=400, width=DEFAULT_PROGRESS_BAR_SIZE[1], style=DEFAULT_PROGRESS_BAR_STYLE, relief=DEFAULT_PROGRESS_BAR_RELIEF, border_width=DEFAULT_PROGRESS_BAR_BORDER_WIDTH, orientation='horizontal', BarColor=(None,None)): + self.Length = length + self.Width = width + self.Max = max + self.Orientation = orientation + self.Count = None + self.PriorCount = 0 + + if orientation[0].lower() == 'h': + s = ttk.Style() + s.theme_use(style) + if BarColor != COLOR_SYSTEM_DEFAULT: + s.configure(str(length)+str(width)+"my.Horizontal.TProgressbar", background=BarColor[0], troughcolor=BarColor[1], troughrelief=relief, borderwidth=border_width, thickness=width) + else: + s.configure(str(length)+str(width)+"my.Horizontal.TProgressbar", troughrelief=relief, borderwidth=border_width, thickness=width) + + self.TKProgressBarForReal = ttk.Progressbar(root, maximum=self.Max, style=str(length)+str(width)+'my.Horizontal.TProgressbar', length=length, orient=tk.HORIZONTAL, mode='determinate') + else: + s = ttk.Style() + s.theme_use(style) + if BarColor != COLOR_SYSTEM_DEFAULT: + s.configure(str(length)+str(width)+"my.Vertical.TProgressbar", background=BarColor[0], troughcolor=BarColor[1], troughrelief=relief, borderwidth=border_width, thickness=width) + else: + s.configure(str(length)+str(width)+"my.Vertical.TProgressbar", troughrelief=relief, borderwidth=border_width, thickness=width) + self.TKProgressBarForReal = ttk.Progressbar(root, maximum=self.Max, style=str(length)+str(width)+'my.Vertical.TProgressbar', length=length, orient=tk.VERTICAL, mode='determinate') + + def Update(self, count=None, max=None): + if max is not None: + self.Max = max + try: + self.TKProgressBarForReal.config(maximum=max) + except: + return False + if count is not None and count > self.Max: return False + if count is not None: + try: + self.TKProgressBarForReal['value'] = count + except: return False + return True + + def __del__(self): + try: + self.TKProgressBarForReal.__del__() + except: + pass + +# ---------------------------------------------------------------------- # +# TKOutput # +# New Type of TK Widget that's a Text Widget in disguise # +# Note that it's inherited from the TKFrame class so that the # +# Scroll bar will span the length of the frame # +# ---------------------------------------------------------------------- # +class TKOutput(tk.Frame): + def __init__(self, parent, width, height, bd, background_color=None, text_color=None, font=None, pad=None): + frame = tk.Frame(parent) + tk.Frame.__init__(self, frame) + self.output = tk.Text(frame, width=width, height=height, bd=bd, font=font) + if background_color and background_color != COLOR_SYSTEM_DEFAULT: + self.output.configure(background=background_color) + frame.configure(background=background_color) + if text_color and text_color != COLOR_SYSTEM_DEFAULT: + self.output.configure(fg=text_color) + self.vsb = tk.Scrollbar(frame, orient="vertical", command=self.output.yview) + self.output.configure(yscrollcommand=self.vsb.set) + self.output.pack(side="left", fill="both", expand=True) + self.vsb.pack(side="left", fill="y", expand=False) + frame.pack(side="left", padx=pad[0], pady=pad[1], expand=True, fill='y') + self.previous_stdout = sys.stdout + self.previous_stderr = sys.stderr + + sys.stdout = self + sys.stderr = self + self.pack() + + def write(self, txt): + try: + self.output.insert(tk.END, str(txt)) + self.output.see(tk.END) + except: + pass + + def Close(self): + sys.stdout = self.previous_stdout + sys.stderr = self.previous_stderr + + def flush(self): + sys.stdout = self.previous_stdout + sys.stderr = self.previous_stderr + + def __del__(self): + sys.stdout = self.previous_stdout + sys.stderr = self.previous_stderr + +# ---------------------------------------------------------------------- # +# Output # +# Routes stdout, stderr to a scrolled window # +# ---------------------------------------------------------------------- # +class Output(Element): + def __init__(self, size=(None, None), background_color=None, text_color=None, pad=None, font=None, tooltip=None, key=None): + ''' + Output Element - reroutes stdout, stderr to this window + :param size: Size of field in characters + :param background_color: Color for Element. Text or RGB Hex + ''' + self._TKOut = None + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super().__init__(ELEM_TYPE_OUTPUT, size=size, background_color=bg, text_color=fg, pad=pad, font=font, tooltip=tooltip, key=key) + + + @property + def TKOut(self): + if self._TKOut is None: + print('*** Did you forget to call Finalize()? Your code should look something like: ***') + print('*** form = sg.Window("My Form").Layout(layout).Finalize() ***') + return self._TKOut + + + def __del__(self): + try: + self._TKOut.__del__() + except: + pass + super().__del__() + +# ---------------------------------------------------------------------- # +# Button Class # +# ---------------------------------------------------------------------- # +class Button(Element): + def __init__(self, button_text='', button_type=BUTTON_TYPE_CLOSES_WIN, target=(None, None), tooltip=None, file_types=(("ALL Files", "*.*"),), initial_folder=None, image_filename=None, image_size=(None, None), image_subsample=None, border_width=None, size=(None, None), auto_size_button=None, button_color=None, default_value = None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + ''' + Button Element - Specifies all types of buttons + :param button_type: + :param target: + :param button_text: + :param file_types: + :param image_filename: + :param image_size: + :param image_subsample: + :param border_width: + :param size: Size of field in characters + :param auto_size_button: + :param button_color: + :param font: + ''' + self.AutoSizeButton = auto_size_button + self.BType = button_type + self.FileTypes = file_types + self.TKButton = None + self.Target = target + self.ButtonText = button_text + self.ButtonColor = button_color if button_color else DEFAULT_BUTTON_COLOR + self.ImageFilename = image_filename + self.ImageSize = image_size + self.ImageSubsample = image_subsample + self.UserData = None + self.BorderWidth = border_width if border_width is not None else DEFAULT_BORDER_WIDTH + self.BindReturnKey = bind_return_key + self.Focus = focus + self.TKCal = None + self.DefaultValue = default_value + self.InitialFolder = initial_folder + + super().__init__(ELEM_TYPE_BUTTON, size=size, font=font, pad=pad, key=key, tooltip=tooltip) + return + + # Realtime button release callback + def ButtonReleaseCallBack(self, parm): + self.LastButtonClickedWasRealtime = False + self.ParentForm.LastButtonClicked = None + + # Realtime button callback + def ButtonPressCallBack(self, parm): + self.ParentForm.LastButtonClickedWasRealtime = True + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.ButtonText + + # ------- Button Callback ------- # + def ButtonCallBack(self): + global _my_windows + # print(f'Parent = {self.ParentForm} Position = {self.Position}') + # Buttons modify targets or return from the form + # If modifying target, get the element object at the target and modify its StrVar + target = self.Target + target_element = None + if target[0] == ThisRow: + target = [self.Position[0], target[1]] + if target[1] < 0: + target[1] = self.Position[1] + target[1] + strvar = None + if target == (None, None): + strvar = self.TKStringVar + else: + if not isinstance(target, str): + if target[0] < 0: + target = [self.Position[0] + target[0], target[1]] + target_element = self.ParentContainer._GetElementAtLocation(target) + else: + target_element = self.ParentForm.FindElement(target) + try: + strvar = target_element.TKStringVar + except: pass + filetypes = [] if self.FileTypes is None else self.FileTypes + if self.BType == BUTTON_TYPE_BROWSE_FOLDER: + folder_name = tk.filedialog.askdirectory(initialdir=self.InitialFolder) # show the 'get folder' dialog box + if folder_name != '': + try: + strvar.set(folder_name) + self.TKStringVar.set(folder_name) + except: pass + elif self.BType == BUTTON_TYPE_BROWSE_FILE: + file_name = tk.filedialog.askopenfilename(filetypes=filetypes, initialdir=self.InitialFolder) # show the 'get file' dialog box + if file_name != '': + strvar.set(file_name) + self.TKStringVar.set(file_name) + elif self.BType == BUTTON_TYPE_COLOR_CHOOSER: + color = tk.colorchooser.askcolor() # show the 'get file' dialog box + color = color[1] # save only the #RRGGBB portion + strvar.set(color) + self.TKStringVar.set(color) + elif self.BType == BUTTON_TYPE_BROWSE_FILES: + file_name = tk.filedialog.askopenfilenames(filetypes=filetypes, initialdir=self.InitialFolder) + if file_name != '': + file_name = ';'.join(file_name) + strvar.set(file_name) + self.TKStringVar.set(file_name) + elif self.BType == BUTTON_TYPE_SAVEAS_FILE: + file_name = tk.filedialog.asksaveasfilename(filetypes=filetypes, initialdir=self.InitialFolder) # show the 'get file' dialog box + if file_name != '': + strvar.set(file_name) + self.TKStringVar.set(file_name) + elif self.BType == BUTTON_TYPE_CLOSES_WIN: # this is a return type button so GET RESULTS and destroy window + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.ButtonText + self.ParentForm.FormRemainedOpen = False + # if the form is tabbed, must collect all form's results and destroy all forms + self.ParentForm._Close() + self.ParentForm.TKroot.quit() + if self.ParentForm.NonBlocking: + self.ParentForm.TKroot.destroy() + _my_windows.Decrement() + elif self.BType == BUTTON_TYPE_READ_FORM: # LEAVE THE WINDOW OPEN!! DO NOT CLOSE + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.ButtonText + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + elif self.BType == BUTTON_TYPE_CLOSES_WIN_ONLY: # this is a return type button so GET RESULTS and destroy window + # if the form is tabbed, must collect all form's results and destroy all forms + self.ParentForm._Close() + if self.ParentForm.NonBlocking: + self.ParentForm.TKroot.destroy() + _my_windows.Decrement() + elif self.BType == BUTTON_TYPE_CALENDAR_CHOOSER: # this is a return type button so GET RESULTS and destroy window + root = tk.Toplevel() + root.title('Calendar Chooser') + self.TKCal = TKCalendar(master=root, firstweekday=calendar.SUNDAY, target_element=target_element) + self.TKCal.pack(expand=1, fill='both') + # self.ParentForm.TKRroot.mainloop() + root.update() + # root.mainloop() + # root.update() + # strvar.set(ttkcal.selection) + + return + + def Update(self, value=None, text=None, button_color=(None, None), disabled=None): + try: + if text is not None: + self.TKButton.configure(text=text) + self.ButtonText = text + if button_color != (None, None): + self.TKButton.config(foreground=button_color[0], background=button_color[1]) + except: + return + if value is not None: + self.DefaultValue = value + if disabled == True: + self.TKButton['state'] = 'disabled' + elif disabled == False: + self.TKButton['state'] = 'normal' + + def GetText(self): + return self.ButtonText + + def __del__(self): + try: + self.TKButton.__del__() + except: + pass + super().__del__() + + +# ---------------------------------------------------------------------- # +# ProgreessBar # +# ---------------------------------------------------------------------- # +class ProgressBar(Element): + def __init__(self, max_value, orientation=None, size=(None, None), auto_size_text=None, bar_color=(None, None), style=None, border_width=None, relief=None, key=None, pad=None): + ''' + Progress Bar Element + :param max_value: + :param orientation: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param bar_color: + :param style: + :param border_width: + :param relief: + ''' + self.MaxValue = max_value + self.TKProgressBar = None + self.Cancelled = False + self.NotRunning = True + self.Orientation = orientation if orientation else DEFAULT_METER_ORIENTATION + self.BarColor = bar_color + self.BarStyle = style if style else DEFAULT_PROGRESS_BAR_STYLE + self.BorderWidth = border_width if border_width else DEFAULT_PROGRESS_BAR_BORDER_WIDTH + self.Relief = relief if relief else DEFAULT_PROGRESS_BAR_RELIEF + self.BarExpired = False + super().__init__(ELEM_TYPE_PROGRESS_BAR, size=size, auto_size_text=auto_size_text, key=key, pad=pad) + return + + # returns False if update failed + def UpdateBar(self, current_count, max=None): + if self.ParentForm.TKrootDestroyed: + return False + self.TKProgressBar.Update(current_count, max=max) + try: + self.ParentForm.TKroot.update() + except: + _my_windows.Decrement() + return False + return True + + def __del__(self): + try: + self.TKProgressBar.__del__() + except: + pass + super().__del__() + +# ---------------------------------------------------------------------- # +# Image # +# ---------------------------------------------------------------------- # +class Image(Element): + def __init__(self, filename=None, data=None, size=(None, None), pad=None, key=None, tooltip=None): + ''' + Image Element + :param filename: + :param size: Size of field in characters + ''' + self.Filename = filename + self.Data = data + self.tktext_label = None + if data is None and filename is None: + print('* Warning... no image specified in Image Element! *') + super().__init__(ELEM_TYPE_IMAGE, size=size, pad=pad, key=key, tooltip=tooltip) + return + + def Update(self, filename=None, data=None): + if filename is not None: + image = tk.PhotoImage(file=filename) + elif data is not None: + if type(data) is bytes: + image = tk.PhotoImage(data=data) + else: + image = data + else: return + width, height = image.width(), image.height() + self.tktext_label.configure(image=image, width=width, height=height) + # self.tktext_label.configure(image=image) + self.tktext_label.image = image + + def __del__(self): + super().__del__() + + +# ---------------------------------------------------------------------- # +# Canvas # +# ---------------------------------------------------------------------- # +class Canvas(Element): + def __init__(self, canvas=None, background_color=None, size=(None, None), pad=None, key=None, tooltip=None): + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + self._TKCanvas = canvas + + super().__init__(ELEM_TYPE_CANVAS, background_color=background_color, size=size, pad=pad, key=key, tooltip=tooltip) + return + + @property + def TKCanvas(self): + if self._TKCanvas is None: + print('*** Did you forget to call Finalize()? Your code should look something like: ***') + print('*** form = sg.Window("My Form").Layout(layout).Finalize() ***') + return self._TKCanvas + + + def __del__(self): + super().__del__() + + + + +# ---------------------------------------------------------------------- # +# Graph # +# ---------------------------------------------------------------------- # +class Graph(Element): + def __init__(self, canvas_size, graph_bottom_left, graph_top_right, background_color=None, pad=None, key=None, tooltip=None): + + self.CanvasSize = canvas_size + self.BottomLeft = graph_bottom_left + self.TopRight = graph_top_right + self._TKCanvas = None + self._TKCanvas2 = None + + super().__init__(ELEM_TYPE_GRAPH, background_color=background_color, size=canvas_size, pad=pad, key=key, tooltip=tooltip) + return + + def _convert_xy_to_canvas_xy(self, x_in, y_in): + scale_x = (self.CanvasSize[0] - 0) / (self.TopRight[0] - self.BottomLeft[0]) + scale_y = (0 - self.CanvasSize[1]) / (self.TopRight[1] - self.BottomLeft[1]) + new_x = 0 + scale_x * (x_in - self.BottomLeft[0]) + new_y = self.CanvasSize[1] + scale_y * (y_in - self.BottomLeft[1]) + return new_x, new_y + + def DrawLine(self, point_from, point_to, color='black', width=1): + converted_point_from = self._convert_xy_to_canvas_xy(point_from[0], point_from[1]) + converted_point_to = self._convert_xy_to_canvas_xy(point_to[0], point_to[1]) + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + return self._TKCanvas2.create_line(converted_point_from, converted_point_to, width=width, fill=color) + + def DrawPoint(self, point, size=2, color='black'): + converted_point = self._convert_xy_to_canvas_xy(point[0], point[1]) + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + return self._TKCanvas2.create_oval(converted_point[0]-size, converted_point[1]-size, converted_point[0]+size, converted_point[1]+size, fill=color, outline=color ) + + def DrawCircle(self, center_location, radius, fill_color=None, line_color='black'): + converted_point = self._convert_xy_to_canvas_xy(center_location[0], center_location[1]) + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + return self._TKCanvas2.create_oval(converted_point[0]-radius, converted_point[1]-radius, converted_point[0]+radius, converted_point[1]+radius, fill=fill_color, outline=line_color) + + def DrawOval(self, top_left, bottom_right, fill_color=None, line_color=None): + converted_top_left = self._convert_xy_to_canvas_xy(top_left[0], top_left[1]) + converted_bottom_right = self._convert_xy_to_canvas_xy(bottom_right[0],bottom_right[1]) + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + return self._TKCanvas2.create_oval(converted_top_left[0], converted_top_left[1], converted_bottom_right[0], converted_bottom_right[1], fill=fill_color, outline=line_color) + + + def DrawRectangle(self, top_left, bottom_right, fill_color=None, line_color=None): + converted_top_left = self._convert_xy_to_canvas_xy(top_left[0], top_left[1] ) + converted_bottom_right = self._convert_xy_to_canvas_xy(bottom_right[0], bottom_right[1]) + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + return self._TKCanvas2.create_rectangle(converted_top_left[0], converted_top_left[1], converted_bottom_right[0], converted_bottom_right[1], fill=fill_color, outline=line_color) + + def DrawText(self, text, location, color='black', font=None, angle=0): + converted_point = self._convert_xy_to_canvas_xy(location[0], location[1]) + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + text_id = self._TKCanvas2.create_text(converted_point[0], converted_point[1], text=text, font=font, fill=color, angle=angle) + return text_id + + + def Erase(self): + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + self._TKCanvas2.delete('all') + + def Update(self, background_color): + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + self._TKCanvas2.configure(background=background_color) + + def Move(self, x_direction, y_direction): + zero_converted = self._convert_xy_to_canvas_xy(0,0) + shift_converted = self._convert_xy_to_canvas_xy(x_direction, y_direction) + shift_amount = (shift_converted[0]-zero_converted[0], shift_converted[1]-zero_converted[1]) + if self._TKCanvas2 is None: + print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') + print('Call Window.Finalize() prior to this operation') + return None + self._TKCanvas2.move('all', shift_amount[0], shift_amount[1]) + + def MoveFigure(self, figure, x_direction, y_direction): + zero_converted = self._convert_xy_to_canvas_xy(0,0) + shift_converted = self._convert_xy_to_canvas_xy(x_direction, y_direction) + shift_amount = (shift_converted[0]-zero_converted[0], shift_converted[1]-zero_converted[1]) + if figure is None: + print('*** WARNING - Your figure is None. It most likely means your did not Finalize your Window ***') + print('Call Window.Finalize() prior to all graph operations') + return None + self._TKCanvas2.move(figure, shift_amount[0], shift_amount[1]) + + @property + def TKCanvas(self): + if self._TKCanvas2 is None: + print('*** Did you forget to call Finalize()? Your code should look something like: ***') + print('*** form = sg.Window("My Form").Layout(layout).Finalize() ***') + return self._TKCanvas2 + + def __del__(self): + super().__del__() + + +# ---------------------------------------------------------------------- # +# Frame # +# ---------------------------------------------------------------------- # +class Frame(Element): + def __init__(self, title, layout, title_color=None, background_color=None, title_location=None , relief=DEFAULT_FRAME_RELIEF, size=(None, None), font=None, pad=None, border_width=None, key=None, tooltip=None): + + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + # self.ParentForm = None + self.TKFrame = None + self.Title = title + self.Relief = relief + self.TitleLocation = title_location + self.BorderWidth = border_width + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + + self.Layout(layout) + + super().__init__(ELEM_TYPE_FRAME, background_color=background_color, text_color=title_color, size=size, font=font, pad=pad, key=key, tooltip=tooltip) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + super().__del__() + + + +# ---------------------------------------------------------------------- # +# Tab # +# ---------------------------------------------------------------------- # +class Tab(Element): + def __init__(self, title, layout, title_color=None, background_color=None, font=None, pad=None, border_width=None, key=None, tooltip=None): + + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + self.TKFrame = None + self.Title = title + self.BorderWidth = border_width + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + + self.Layout(layout) + + super().__init__(ELEM_TYPE_TAB, background_color=background_color, text_color=title_color, font=font, pad=pad, key=key, tooltip=tooltip) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + super().__del__() + + + +# ---------------------------------------------------------------------- # +# TabGroup # +# ---------------------------------------------------------------------- # +class TabGroup(Element): + def __init__(self, layout, title_color=None, background_color=None, font=None, change_submits=False, pad=None, border_width=None, key=None, tooltip=None): + + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + self.TKNotebook = None + self.BorderWidth = border_width + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + self.ChangeSubmits = change_submits + + self.Layout(layout) + + super().__init__(ELEM_TYPE_TAB_GROUP, background_color=background_color, text_color=title_color, font=font, pad=pad, key=key, tooltip=tooltip) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + super().__del__() + + + + +# ---------------------------------------------------------------------- # +# Slider # +# ---------------------------------------------------------------------- # +class Slider(Element): + def __init__(self, range=(None,None), default_value=None, resolution=None, orientation=None, border_width=None, relief=None, change_submits=False, size=(None, None), font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Slider + :param range: + :param default_value: + :param resolution: + :param orientation: + :param border_width: + :param relief: + :param change_submits: + :param scale: + :param size: + :param font: + :param background_color: + :param text_color: + :param key: + :param pad: + ''' + self.TKScale = None + self.Range = (1,10) if range == (None, None) else range + self.DefaultValue = self.Range[0] if default_value is None else default_value + self.Orientation = orientation if orientation else DEFAULT_SLIDER_ORIENTATION + self.BorderWidth = border_width if border_width else DEFAULT_SLIDER_BORDER_WIDTH + self.Relief = relief if relief else DEFAULT_SLIDER_RELIEF + self.Resolution = 1 if resolution is None else resolution + self.ChangeSubmits = change_submits + + super().__init__(ELEM_TYPE_INPUT_SLIDER, size=size, font=font, background_color=background_color, text_color=text_color, key=key, pad=pad, tooltip=tooltip) + return + + def Update(self, value=None, range=(None, None), disabled=None): + if value is not None: + try: + self.TKIntVar.set(value) + if range != (None, None): + self.TKScale.config(from_ = range[0], to_ = range[1]) + except: pass + self.DefaultValue = value + if disabled == True: + self.TKScale['state'] = 'disabled' + elif disabled == False: + self.TKScale['state'] = 'normal' + + def SliderChangedHandler(self, event): + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def __del__(self): + super().__del__() + + +# ---------------------------------------------------------------------- # +# TkScrollableFrame (Used by Column) # +# ---------------------------------------------------------------------- # +class TkScrollableFrame(tk.Frame): + def __init__(self, master, **kwargs): + tk.Frame.__init__(self, master, **kwargs) + + # create a canvas object and a vertical scrollbar for scrolling it + self.vscrollbar = tk.Scrollbar(self, orient=tk.VERTICAL) + self.vscrollbar.pack(side='right', fill="y", expand="false") + + self.hscrollbar = tk.Scrollbar(self, orient=tk.HORIZONTAL) + self.hscrollbar.pack(side='bottom', fill="x", expand="false") + + self.canvas = tk.Canvas(self, yscrollcommand=self.vscrollbar.set, xscrollcommand=self.hscrollbar.set) + self.canvas.pack(side="left", fill="both", expand=True) + + self.vscrollbar.config(command=self.canvas.yview) + self.hscrollbar.config(command=self.canvas.xview) + + # reset the view + self.canvas.xview_moveto(0) + self.canvas.yview_moveto(0) + + # create a frame inside the canvas which will be scrolled with it + self.TKFrame = tk.Frame(self.canvas, **kwargs) + self.frame_id = self.canvas.create_window(0, 0, window=self.TKFrame, anchor="nw") + self.canvas.config(borderwidth=0, highlightthickness=0) + self.TKFrame.config(borderwidth=0, highlightthickness=0) + self.config(borderwidth=0, highlightthickness=0) + + self.bind('', self.set_scrollregion) + + self.bind_mouse_scroll(self.canvas, self.yscroll) + self.bind_mouse_scroll(self.hscrollbar, self.xscroll) + self.bind_mouse_scroll(self.vscrollbar, self.yscroll) + + def resize_frame(self, e): + self.canvas.itemconfig(self.frame_id, height=e.height, width=e.width) + + def yscroll(self, event): + if event.num == 5 or event.delta < 0: + self.canvas.yview_scroll(1, "unit") + elif event.num == 4 or event.delta > 0: + self.canvas.yview_scroll(-1, "unit") + + def xscroll(self, event): + if event.num == 5 or event.delta < 0: + self.canvas.xview_scroll(1, "unit") + elif event.num == 4 or event.delta > 0: + self.canvas.xview_scroll(-1, "unit") + + def bind_mouse_scroll(self, parent, mode): + # ~~ Windows only + parent.bind("", mode) + # ~~ Unix only + parent.bind("", mode) + parent.bind("", mode) + + def set_scrollregion(self, event=None): + """ Set the scroll region on the canvas""" + self.canvas.configure(scrollregion=self.canvas.bbox('all')) + + +# ---------------------------------------------------------------------- # +# Column # +# ---------------------------------------------------------------------- # +class Column(Element): + def __init__(self, layout, background_color = None, size=(None, None), pad=None, scrollable=False, key=None): + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + # self.ParentForm = None + self.TKFrame = None + self.Scrollable = scrollable + bg = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + + self.Layout(layout) + + super().__init__(ELEM_TYPE_COLUMN, background_color=background_color, size=size, pad=pad, key=key) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + try: + del(self.TKFrame) + except: + pass + super().__del__() + + +# ---------------------------------------------------------------------- # +# Calendar # +# ---------------------------------------------------------------------- # +class TKCalendar(ttk.Frame): + """ + This code was shamelessly lifted from moshekaplan's repository - moshekaplan/tkinter_components + """ + # XXX ToDo: cget and configure + + datetime = calendar.datetime.datetime + timedelta = calendar.datetime.timedelta + + def __init__(self, master=None, target_element=None, **kw): + """ + WIDGET-SPECIFIC OPTIONS + + locale, firstweekday, year, month, selectbackground, + selectforeground + """ + self._TargetElement = target_element + # remove custom options from kw before initializating ttk.Frame + fwday = kw.pop('firstweekday', calendar.MONDAY) + year = kw.pop('year', self.datetime.now().year) + month = kw.pop('month', self.datetime.now().month) + locale = kw.pop('locale', None) + sel_bg = kw.pop('selectbackground', '#ecffc4') + sel_fg = kw.pop('selectforeground', '#05640e') + + self._date = self.datetime(year, month, 1) + self._selection = None # no date selected + ttk.Frame.__init__(self, master, **kw) + + # instantiate proper calendar class + if locale is None: + self._cal = calendar.TextCalendar(fwday) + else: + self._cal = calendar.LocaleTextCalendar(fwday, locale) + + self.__setup_styles() # creates custom styles + self.__place_widgets() # pack/grid used widgets + self.__config_calendar() # adjust calendar columns and setup tags + # configure a canvas, and proper bindings, for selecting dates + self.__setup_selection(sel_bg, sel_fg) + + # store items ids, used for insertion later + self._items = [self._calendar.insert('', 'end', values='') + for _ in range(6)] + # insert dates in the currently empty calendar + self._build_calendar() + + def __setitem__(self, item, value): + if item in ('year', 'month'): + raise AttributeError("attribute '%s' is not writeable" % item) + elif item == 'selectbackground': + self._canvas['background'] = value + elif item == 'selectforeground': + self._canvas.itemconfigure(self._canvas.text, item=value) + else: + ttk.Frame.__setitem__(self, item, value) + + def __getitem__(self, item): + if item in ('year', 'month'): + return getattr(self._date, item) + elif item == 'selectbackground': + return self._canvas['background'] + elif item == 'selectforeground': + return self._canvas.itemcget(self._canvas.text, 'fill') + else: + r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)}) + return r[item] + + def __setup_styles(self): + # custom ttk styles + style = ttk.Style(self.master) + arrow_layout = lambda dir: ( + [('Button.focus', {'children': [('Button.%sarrow' % dir, None)]})] + ) + style.layout('L.TButton', arrow_layout('left')) + style.layout('R.TButton', arrow_layout('right')) + + def __place_widgets(self): + # header frame and its widgets + hframe = ttk.Frame(self) + lbtn = ttk.Button(hframe, style='L.TButton', command=self._prev_month) + rbtn = ttk.Button(hframe, style='R.TButton', command=self._next_month) + self._header = ttk.Label(hframe, width=15, anchor='center') + # the calendar + self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7) + + # pack the widgets + hframe.pack(in_=self, side='top', pady=4, anchor='center') + lbtn.grid(in_=hframe) + self._header.grid(in_=hframe, column=1, row=0, padx=12) + rbtn.grid(in_=hframe, column=2, row=0) + self._calendar.pack(in_=self, expand=1, fill='both', side='bottom') + + def __config_calendar(self): + cols = self._cal.formatweekheader(3).split() + self._calendar['columns'] = cols + self._calendar.tag_configure('header', background='grey90') + self._calendar.insert('', 'end', values=cols, tag='header') + # adjust its columns width + font = tkinter.font.Font() + maxwidth = max(font.measure(col) for col in cols) + for col in cols: + self._calendar.column(col, width=maxwidth, minwidth=maxwidth, + anchor='e') + + def __setup_selection(self, sel_bg, sel_fg): + self._font = tkinter.font.Font() + self._canvas = canvas = tk.Canvas(self._calendar, + background=sel_bg, borderwidth=0, highlightthickness=0) + canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='w') + + canvas.bind('', lambda evt: canvas.place_forget()) + self._calendar.bind('', lambda evt: canvas.place_forget()) + self._calendar.bind('', self._pressed) + + def __minsize(self, evt): + width, height = self._calendar.master.geometry().split('x') + height = height[:height.index('+')] + self._calendar.master.minsize(width, height) + + def _build_calendar(self): + year, month = self._date.year, self._date.month + + # update header text (Month, YEAR) + header = self._cal.formatmonthname(year, month, 0) + self._header['text'] = header.title() + + # update calendar shown dates + cal = self._cal.monthdayscalendar(year, month) + for indx, item in enumerate(self._items): + week = cal[indx] if indx < len(cal) else [] + fmt_week = [('%02d' % day) if day else '' for day in week] + self._calendar.item(item, values=fmt_week) + + def _show_selection(self, text, bbox): + """Configure canvas for a new selection.""" + x, y, width, height = bbox + + textw = self._font.measure(text) + + canvas = self._canvas + canvas.configure(width=width, height=height) + canvas.coords(canvas.text, width - textw, height / 2 - 1) + canvas.itemconfigure(canvas.text, text=text) + canvas.place(in_=self._calendar, x=x, y=y) + + # Callbacks + + def _pressed(self, evt): + """Clicked somewhere in the calendar.""" + x, y, widget = evt.x, evt.y, evt.widget + item = widget.identify_row(y) + column = widget.identify_column(x) + + if not column or not item in self._items: + # clicked in the weekdays row or just outside the columns + return + + item_values = widget.item(item)['values'] + if not len(item_values): # row is empty for this month + return + + text = item_values[int(column[1]) - 1] + if not text: # date is empty + return + + bbox = widget.bbox(item, column) + if not bbox: # calendar not visible yet + return + + # update and then show selection + text = '%02d' % text + self._selection = (text, item, column) + self._show_selection(text, bbox) + year, month = self._date.year, self._date.month + try: + self._TargetElement.Update(self.datetime(year, month, int(self._selection[0]))) + except: pass + + def _prev_month(self): + """Updated calendar to show the previous month.""" + self._canvas.place_forget() + + self._date = self._date - self.timedelta(days=1) + self._date = self.datetime(self._date.year, self._date.month, 1) + self._build_calendar() # reconstuct calendar + + def _next_month(self): + """Update calendar to show the next month.""" + self._canvas.place_forget() + + year, month = self._date.year, self._date.month + self._date = self._date + self.timedelta( + days=calendar.monthrange(year, month)[1] + 1) + self._date = self.datetime(self._date.year, self._date.month, 1) + self._build_calendar() # reconstruct calendar + + # Properties + + @property + def selection(self): + """Return a datetime representing the current selected date.""" + if not self._selection: + return None + + year, month = self._date.year, self._date.month + return self.datetime(year, month, int(self._selection[0])) + + +# ---------------------------------------------------------------------- # +# Canvas # +# ---------------------------------------------------------------------- # +class Menu(Element): + def __init__(self, menu_definition, background_color=None, size=(None, None), tearoff=True, pad=None, key=None): + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + self.MenuDefinition = menu_definition + self.TKMenu = None + self.Tearoff = tearoff + + super().__init__(ELEM_TYPE_MENUBAR, background_color=background_color, size=size, pad=pad, key=key) + return + + def MenuItemChosenCallback(self, item_chosen): + # print('IN MENU ITEM CALLBACK', item_chosen) + self.ParentForm.LastButtonClicked = item_chosen + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def __del__(self): + super().__del__() + + + +# ---------------------------------------------------------------------- # +# Table # +# ---------------------------------------------------------------------- # +class Table(Element): + def __init__(self, values, headings=None, visible_column_map=None, col_widths=None, def_col_width=10, auto_size_columns=True, max_col_width=20, select_mode=None, display_row_numbers=False, scrollable=None, font=None, justification='right', text_color=None, background_color=None, size=(None, None), pad=None, key=None, tooltip=None): + self.Values = values + self.ColumnHeadings = headings + self.ColumnsToDisplay = visible_column_map + self.ColumnWidths = col_widths + self.MaxColumnWidth = max_col_width + self.DefaultColumnWidth = def_col_width + self.AutoSizeColumns = auto_size_columns + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + self.TextColor = text_color + self.Justification = justification + self.Scrollable = scrollable + self.InitialState = None + self.SelectMode = select_mode + self.DisplayRowNumbers = display_row_numbers + self.TKTreeview = None + + super().__init__(ELEM_TYPE_TABLE, text_color=text_color, background_color=background_color, font=font, size=size, pad=pad, key=key, tooltip=tooltip) + return + + + def __del__(self): + super().__del__() + + + + + +# ------------------------------------------------------------------------- # +# Window CLASS # +# ------------------------------------------------------------------------- # +class Window: + ''' + Display a user defined for and return the filled in data + ''' + def __init__(self, title, default_element_size=DEFAULT_ELEMENT_SIZE, default_button_element_size = (None, None), auto_size_text=None, auto_size_buttons=None, location=(None, None), button_color=None, font=None, progress_bar_color=(None, None), background_color=None, border_depth=None, auto_close=False, auto_close_duration=DEFAULT_AUTOCLOSE_TIME, icon=DEFAULT_WINDOW_ICON, force_toplevel = False, return_keyboard_events=False, use_default_focus=True, text_justification=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, resizable=True): + self.AutoSizeText = auto_size_text if auto_size_text is not None else DEFAULT_AUTOSIZE_TEXT + self.AutoSizeButtons = auto_size_buttons if auto_size_buttons is not None else DEFAULT_AUTOSIZE_BUTTONS + self.Title = title + self.Rows = [] # a list of ELEMENTS for this row + self.DefaultElementSize = default_element_size + self.DefaultButtonElementSize = default_button_element_size if default_button_element_size != (None, None) else DEFAULT_BUTTON_ELEMENT_SIZE + self.Location = location + self.ButtonColor = button_color if button_color else DEFAULT_BUTTON_COLOR + self.BackgroundColor = background_color if background_color else DEFAULT_BACKGROUND_COLOR + self.ParentWindow = None + self.Font = font if font else DEFAULT_FONT + self.RadioDict = {} + self.BorderDepth = border_depth + self.WindowIcon = icon if icon is not None else _my_windows.user_defined_icon + self.AutoClose = auto_close + self.NonBlocking = False + self.TKroot = None + self.TKrootDestroyed = False + self.FormRemainedOpen = False + self.TKAfterID = None + self.ProgressBarColor = progress_bar_color + self.AutoCloseDuration = auto_close_duration + self.UberParent = None + self.RootNeedsDestroying = False + self.Shown = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.LastButtonClicked = None + self.LastButtonClickedWasRealtime = False + self.UseDictionary = False + self.UseDefaultFocus = use_default_focus + self.ReturnKeyboardEvents = return_keyboard_events + self.LastKeyboardEvent = None + self.TextJustification = text_justification + self.NoTitleBar = no_titlebar + self.GrabAnywhere = grab_anywhere + self.KeepOnTop = keep_on_top + self.ForceTopLevel = force_toplevel + self.Resizable = resizable + + # ------------------------- Add ONE Row to Form ------------------------- # + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + # ------------------------- Add Multiple Rows to Form ------------------------- # + def AddRows(self,rows): + for row in rows: + self.AddRow(*row) + + def Layout(self,rows): + self.AddRows(rows) + return self + + def LayoutAndRead(self,rows, non_blocking=False): + self.AddRows(rows) + self.Show(non_blocking=non_blocking) + return self.ReturnValues + + def LayoutAndShow(self, rows): + raise DeprecationWarning('LayoutAndShow is no longer supported... change your call to LayoutAndRead') + + # ------------------------- ShowForm THIS IS IT! ------------------------- # + def Show(self, non_blocking=False): + self.Shown = True + # Compute num rows & num cols (it'll come in handy debugging) + self.NumRows = len(self.Rows) + self.NumCols = max(len(row) for row in self.Rows) + self.NonBlocking=non_blocking + + # Search through entire form to see if any elements set the focus + # if not, then will set the focus to the first input element + found_focus = False + for row in self.Rows: + for element in row: + try: + if element.Focus: + found_focus = True + except: + pass + try: + if element.Key is not None: + self.UseDictionary = True + except: + pass + + if not found_focus and self.UseDefaultFocus: + self.UseDefaultFocus = True + else: + self.UseDefaultFocus = False + # -=-=-=-=-=-=-=-=- RUN the GUI -=-=-=-=-=-=-=-=- ## + StartupTK(self) + # If a button or keyboard event happened but no results have been built, build the results + if self.LastKeyboardEvent is not None or self.LastButtonClicked is not None: + return BuildResults(self, False, self) + return self.ReturnValues + + # ------------------------- SetIcon - set the window's fav icon ------------------------- # + def SetIcon(self, icon): + self.WindowIcon = icon + try: + self.TKroot.iconbitmap(icon) + except: pass + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + def _GetDefaultElementSize(self): + return self.DefaultElementSize + + def _AutoCloseAlarmCallback(self): + try: + if self.UberParent: + window = self.UberParent + else: + window = self + if window: + window._Close() + self.TKroot.quit() + self.RootNeedsDestroying = True + except: + pass + + def Read(self): + self.NonBlocking = False + if self.TKrootDestroyed: + return None, None + if not self.Shown: + self.Show() + else: + InitializeResults(self) + self.TKroot.mainloop() + if self.RootNeedsDestroying: + self.TKroot.destroy() + _my_windows.Decrement() + # if form was closed with X + if self.LastButtonClicked is None and self.LastKeyboardEvent is None and self.ReturnValues[0] is None: + _my_windows.Decrement() + if self.LastKeyboardEvent is not None or self.LastButtonClicked is not None: + return BuildResults(self, False, self) + else: + return self.ReturnValues + + def ReadNonBlocking(self, Message=''): + if self.TKrootDestroyed: + return None, None + if not self.Shown: + self.Show(non_blocking=True) + if Message: + print(Message) + try: + rc = self.TKroot.update() + except: + self.TKrootDestroyed = True + _my_windows.Decrement() + # return None, None + return BuildResults(self, False, self) + + + def Finalize(self): + if self.TKrootDestroyed: + return self + if not self.Shown: + self.Show(non_blocking=True) + try: + rc = self.TKroot.update() + except: + self.TKrootDestroyed = True + _my_windows.Decrement() + # return None, None + return self + + + + def Refresh(self): + if self.TKrootDestroyed: + return + try: + rc = self.TKroot.update() + except: + pass + + + def Fill(self, values_dict): + FillFormWithValues(self, values_dict) + + + def FindElement(self, key): + element = _FindElementFromKeyInSubForm(self, key) + if element is None: + print('*** WARNING = FindElement did not find the key. Please check your key\'s spelling ***') + return element + + def SaveToDisk(self, filename): + try: + results = BuildResults(self, False, self) + with open(filename, 'wb') as sf: + pickle.dump(results[1], sf) + except: + print('*** Error saving form to disk ***') + + + def LoadFromDisk(self, filename): + try: + with open(filename, 'rb') as df: + self.Fill(pickle.load(df)) + except: + print('*** Error loading form to disk ***') + + + + def GetScreenDimensions(self): + if self.TKrootDestroyed: + return None, None + screen_width = self.TKroot.winfo_screenwidth() # get window info to move to middle of screen + screen_height = self.TKroot.winfo_screenheight() + return screen_width, screen_height + + + def StartMove(self, event): + try: + self.TKroot.x = event.x + self.TKroot.y = event.y + except: pass + + def StopMove(self, event): + try: + self.TKroot.x = None + self.TKroot.y = None + except: pass + + def OnMotion(self, event): + try: + deltax = event.x - self.TKroot.x + deltay = event.y - self.TKroot.y + x = self.TKroot.winfo_x() + deltax + y = self.TKroot.winfo_y() + deltay + self.TKroot.geometry("+%s+%s" % (x, y)) + except: + pass + + + def _KeyboardCallback(self, event ): + self.LastButtonClicked = None + self.FormRemainedOpen = True + if event.char != '': + self.LastKeyboardEvent = event.char + else: + self.LastKeyboardEvent = str(event.keysym) + ':' + str(event.keycode) + if not self.NonBlocking: + BuildResults(self, False, self) + self.TKroot.quit() + + def _MouseWheelCallback(self, event ): + self.LastButtonClicked = None + self.FormRemainedOpen = True + self.LastKeyboardEvent = 'MouseWheel:Down' if event.delta < 0 else 'MouseWheel:Up' + if not self.NonBlocking: + BuildResults(self, False, self) + self.TKroot.quit() + + + def _Close(self): + try: + self.TKroot.update() + except: pass + if not self.NonBlocking: + BuildResults(self, False, self) + if self.TKrootDestroyed: + return None + self.TKrootDestroyed = True + self.RootNeedsDestroying = True + return None + + def CloseNonBlocking(self): + if self.TKrootDestroyed: + return + try: + self.TKroot.destroy() + _my_windows.Decrement() + except: pass + + CloseNonBlockingForm = CloseNonBlocking + + def OnClosingCallback(self): + return + + + def Disable(self): + self.TKroot.grab_set_global() + + def Enable(self): + self.TKroot.grab_release() + + def Hide(self): + self.TKroot.withdraw() + + def UnHide(self): + self.TKroot.deiconify() + + + def __enter__(self): + return self + + def __exit__(self, *a): + self.__del__() + return False + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + # try: + # del(self.TKroot) + # except: + # pass + +FlexForm = Window + + +# ------------------------------------------------------------------------- # +# UberForm CLASS # +# Used to make forms into TABS (it's trick) # +# ------------------------------------------------------------------------- # +class UberForm(): + FormList = None # list of all the forms in this window + FormReturnValues = None + TKroot = None # tk root for the overall window + TKrootDestroyed = False + def __init__(self): + self.FormList = [] + self.FormReturnValues = [] + self.TKroot = None + self.TKrootDestroyed = False + self.FormStayedOpen = False + + def AddForm(self, form): + self.FormList.append(form) + + def _Close(self): + self.FormReturnValues = [] + for form in self.FormList: + form._Close() + self.FormReturnValues.append(form.ReturnValues) + if not self.TKrootDestroyed: + self.TKrootDestroyed = True + self.TKroot.destroy() + _my_windows.Decrement() + + def __del__(self): + return + +# =========================================================================== # +# Button Lazy Functions so the caller doesn't have to define a bunch of stuff # +# =========================================================================== # + + +# ------------------------- FOLDER BROWSE Element lazy function ------------------------- # +def FolderBrowse(button_text='Browse', target=(ThisRow, -1), initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_BROWSE_FOLDER, target=target, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- FILE BROWSE Element lazy function ------------------------- # +def FileBrowse( button_text='Browse',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_BROWSE_FILE, target=target, file_types=file_types,initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- FILES BROWSE Element (Multiple file selection) lazy function ------------------------- # +def FilesBrowse(button_text='Browse',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_BROWSE_FILES, target=target, file_types=file_types, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- FILE BROWSE Element lazy function ------------------------- # +def FileSaveAs(button_text='Save As...',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), initial_folder=None, tooltip=None,size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_SAVEAS_FILE, target=target, file_types=file_types, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- SAVE AS Element lazy function ------------------------- # +def SaveAs(button_text='Save As...',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),),initial_folder=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_SAVEAS_FILE, target=target, file_types=file_types, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- SAVE BUTTON Element lazy function ------------------------- # +def Save(button_text='Save', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- SUBMIT BUTTON Element lazy function ------------------------- # +def Submit(button_text='Submit', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None, focus=False, pad=None, key=None): + return Button( button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- OPEN BUTTON Element lazy function ------------------------- # +def Open(button_text='Open', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- OK BUTTON Element lazy function ------------------------- # +def OK(button_text='OK', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None,focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- YES BUTTON Element lazy function ------------------------- # +def Ok(button_text='Ok', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None,focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- CANCEL BUTTON Element lazy function ------------------------- # +def Cancel(button_text='Cancel', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- QUIT BUTTON Element lazy function ------------------------- # +def Quit(button_text='Quit', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- Exit BUTTON Element lazy function ------------------------- # +def Exit(button_text='Exit', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- YES BUTTON Element lazy function ------------------------- # +def Yes(button_text='Yes', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=True, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- NO BUTTON Element lazy function ------------------------- # +def No(button_text='No', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- NO BUTTON Element lazy function ------------------------- # +def Help(button_text='Help', size=(None, None), auto_size_button=None, button_color=None,font=None,tooltip=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- GENERIC BUTTON Element lazy function ------------------------- # +def SimpleButton(button_text, image_filename=None, image_size=(None, None), image_subsample=None, border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +# ------------------------- GENERIC BUTTON Element lazy function ------------------------- # +def ReadButton(button_text, image_filename=None, image_size=(None, None),image_subsample=None,border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button( button_text=button_text, button_type=BUTTON_TYPE_READ_FORM, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +ReadFormButton = ReadButton +RButton = ReadFormButton + + +# ------------------------- Realtime BUTTON Element lazy function ------------------------- # +def RealtimeButton(button_text, image_filename=None, image_size=(None, None),image_subsample=None,border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button( button_text=button_text,button_type=BUTTON_TYPE_REALTIME, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +# ------------------------- Dummy BUTTON Element lazy function ------------------------- # +def DummyButton(button_text, image_filename=None, image_size=(None, None),image_subsample=None,border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type= BUTTON_TYPE_CLOSES_WIN_ONLY, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +# ------------------------- Calendar Chooser Button lazy function ------------------------- # +def CalendarButton(button_text, target=(None,None), image_filename=None, image_size=(None, None), image_subsample=None,tooltip=None, border_width=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CALENDAR_CHOOSER, target=target, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- Calendar Chooser Button lazy function ------------------------- # +def ColorChooserButton(button_text, target=(None,None), image_filename=None, image_size=(None, None), image_subsample=None,tooltip=None, border_width=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_COLOR_CHOOSER, target=target, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +##################################### ----- RESULTS ------ ################################################## + +def AddToReturnDictionary(form, element, value): + if element.Key is None: + form.ReturnValuesDictionary[form.DictionaryKeyCounter] = value + element.Key = form.DictionaryKeyCounter + form.DictionaryKeyCounter += 1 + else: + form.ReturnValuesDictionary[element.Key] = value + +def AddToReturnList(form, value): + form.ReturnValuesList.append(value) + + +#----------------------------------------------------------------------------# +# ------- FUNCTION InitializeResults. Sets up form results matrix --------# +def InitializeResults(form): + BuildResults(form, True, form) + return + +#===== Radio Button RadVar encoding and decoding =====# +#===== The value is simply the row * 1000 + col =====# +def DecodeRadioRowCol(RadValue): + row = RadValue//1000 + col = RadValue%1000 + return row,col + +def EncodeRadioRowCol(row, col): + RadValue = row * 1000 + col + return RadValue + +# ------- FUNCTION BuildResults. Form exiting so build the results to pass back ------- # +# format of return values is +# (Button Pressed, input_values) +def BuildResults(form, initialize_only, top_level_form): + # Results for elements are: + # TEXT - Nothing + # INPUT - Read value from TK + # Button - Button Text and position as a Tuple + + # Get the initialized results so we don't have to rebuild + form.DictionaryKeyCounter = 0 + form.ReturnValuesDictionary = {} + form.ReturnValuesList = [] + BuildResultsForSubform(form, initialize_only, top_level_form) + if not top_level_form.LastButtonClickedWasRealtime: + top_level_form.LastButtonClicked = None + return form.ReturnValues + +def BuildResultsForSubform(form, initialize_only, top_level_form): + button_pressed_text = top_level_form.LastButtonClicked + for row_num,row in enumerate(form.Rows): + for col_num, element in enumerate(row): + value = None + if element.Type == ELEM_TYPE_COLUMN: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if element.Type == ELEM_TYPE_FRAME: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if element.Type == ELEM_TYPE_TAB_GROUP: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if element.Type == ELEM_TYPE_TAB: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if not initialize_only: + if element.Type == ELEM_TYPE_INPUT_TEXT: + value=element.TKStringVar.get() + if not top_level_form.NonBlocking and not element.do_not_clear and not top_level_form.ReturnKeyboardEvents: + element.TKStringVar.set('') + elif element.Type == ELEM_TYPE_INPUT_CHECKBOX: + value = element.TKIntVar.get() + value = (value != 0) + elif element.Type == ELEM_TYPE_INPUT_RADIO: + RadVar=element.TKIntVar.get() + this_rowcol = EncodeRadioRowCol(row_num,col_num) + value = RadVar == this_rowcol + elif element.Type == ELEM_TYPE_BUTTON: + if top_level_form.LastButtonClicked == element.ButtonText: + button_pressed_text = top_level_form.LastButtonClicked + if element.BType != BUTTON_TYPE_REALTIME: # Do not clear realtime buttons + top_level_form.LastButtonClicked = None + if element.BType == BUTTON_TYPE_CALENDAR_CHOOSER: + try: + value = element.TKCal.selection + except: + value = None + else: + try: + value = element.TKStringVar.get() + except: + value = None + elif element.Type == ELEM_TYPE_INPUT_COMBO: + value=element.TKStringVar.get() + elif element.Type == ELEM_TYPE_INPUT_OPTION_MENU: + value=element.TKStringVar.get() + elif element.Type == ELEM_TYPE_INPUT_LISTBOX: + try: + items=element.TKListbox.curselection() + value = [element.Values[int(item)] for item in items] + except: + value = '' + elif element.Type == ELEM_TYPE_INPUT_SPIN: + try: + value=element.TKStringVar.get() + except: + value = 0 + elif element.Type == ELEM_TYPE_INPUT_SLIDER: + try: + value=element.TKIntVar.get() + except: + value = 0 + elif element.Type == ELEM_TYPE_INPUT_MULTILINE: + try: + value=element.TKText.get(1.0, tk.END) + if not top_level_form.NonBlocking and not element.do_not_clear and not top_level_form.ReturnKeyboardEvents: + element.TKText.delete('1.0', tk.END) + except: + value = None + elif element.Type == ELEM_TYPE_TAB_GROUP: + try: + value=element.TKNotebook.tab(element.TKNotebook.index('current'))['text'] + except: + value = None + else: + value = None + + # if an input type element, update the results + if element.Type != ELEM_TYPE_BUTTON and element.Type != ELEM_TYPE_TEXT and element.Type != ELEM_TYPE_IMAGE and\ + element.Type != ELEM_TYPE_OUTPUT and element.Type != ELEM_TYPE_PROGRESS_BAR and \ + element.Type!= ELEM_TYPE_COLUMN and element.Type != ELEM_TYPE_FRAME \ + and element.Type != ELEM_TYPE_TAB: + AddToReturnList(form, value) + AddToReturnDictionary(top_level_form, element, value) + elif (element.Type == ELEM_TYPE_BUTTON and element.BType == BUTTON_TYPE_CALENDAR_CHOOSER and element.Target == (None,None)) or \ + (element.Type == ELEM_TYPE_BUTTON and element.BType == BUTTON_TYPE_COLOR_CHOOSER and element.Target == (None,None)) or \ + (element.Type == ELEM_TYPE_BUTTON and element.Key is not None and (element.BType in (BUTTON_TYPE_SAVEAS_FILE, BUTTON_TYPE_BROWSE_FILE, BUTTON_TYPE_BROWSE_FILES, BUTTON_TYPE_BROWSE_FOLDER))): + AddToReturnList(form, value) + AddToReturnDictionary(top_level_form, element, value) + + # if this is a column, then will fail so need to wrap with tr + try: + if form.ReturnKeyboardEvents and form.LastKeyboardEvent is not None: + button_pressed_text = form.LastKeyboardEvent + form.LastKeyboardEvent = None + except: pass + + try: + form.ReturnValuesDictionary.pop(None, None) # clean up dictionary include None was included + except: pass + + if not form.UseDictionary: + form.ReturnValues = button_pressed_text, form.ReturnValuesList + else: + form.ReturnValues = button_pressed_text, form.ReturnValuesDictionary + + return form.ReturnValues + +def FillFormWithValues(form, values_dict): + FillSubformWithValues(form, values_dict) + +def FillSubformWithValues(form, values_dict): + for row_num,row in enumerate(form.Rows): + for col_num, element in enumerate(row): + value = None + if element.Type == ELEM_TYPE_COLUMN: + FillSubformWithValues(element, values_dict) + if element.Type == ELEM_TYPE_FRAME: + FillSubformWithValues(element, values_dict) + if element.Type == ELEM_TYPE_TAB_GROUP: + FillSubformWithValues(element, values_dict) + if element.Type == ELEM_TYPE_TAB: + FillSubformWithValues(element, values_dict) + try: + value = values_dict[element.Key] + except: + continue + if element.Type == ELEM_TYPE_INPUT_TEXT: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_CHECKBOX: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_RADIO: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_COMBO: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_OPTION_MENU: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_LISTBOX: + element.SetValue(value) + elif element.Type == ELEM_TYPE_INPUT_SLIDER: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_MULTILINE: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_SPIN: + element.Update(value) + elif element.Type == ELEM_TYPE_BUTTON: + element.Update(value) + +def _FindElementFromKeyInSubForm(form, key): + for row_num, row in enumerate(form.Rows): + for col_num, element in enumerate(row): + if element.Type == ELEM_TYPE_COLUMN: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Type == ELEM_TYPE_FRAME: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Type == ELEM_TYPE_TAB_GROUP: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Type == ELEM_TYPE_TAB: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Key == key: + return element + + +def AddMenuItem(top_menu, sub_menu_info, element, is_sub_menu=False, skip=False): + if type(sub_menu_info) is str: + if not is_sub_menu and not skip: + # print(f'Adding command {sub_menu_info}') + pos = sub_menu_info.find('&') + if pos != -1: + if pos == 0 or sub_menu_info[pos-1] != "\\": + sub_menu_info = sub_menu_info[:pos] + sub_menu_info[pos+1:] + if sub_menu_info == '---': + top_menu.add('separator') + else: + top_menu.add_command(label=sub_menu_info, underline=pos, command=lambda: Menu.MenuItemChosenCallback(element, sub_menu_info)) + else: + i = 0 + while i < (len(sub_menu_info)): + item = sub_menu_info[i] + if i != len(sub_menu_info) - 1: + if type(sub_menu_info[i+1]) == list: + new_menu = tk.Menu(top_menu, tearoff=element.Tearoff) + pos = sub_menu_info[i].find('&') + if pos != -1: + if pos == 0 or sub_menu_info[i][pos-1] != "\\": + sub_menu_info[i] = sub_menu_info[i][:pos] + sub_menu_info[i][pos+1:] + top_menu.add_cascade(label=sub_menu_info[i], menu=new_menu, underline=pos) + AddMenuItem(new_menu, sub_menu_info[i+1], element, is_sub_menu=True) + i += 1 # skip the next one + else: + AddMenuItem(top_menu, item, element) + else: + AddMenuItem(top_menu, item, element) + i += 1 + +# ------------------------------------------------------------------------------------------------------------------ # +# ===================================== TK CODE STARTS HERE ====================================================== # +# ------------------------------------------------------------------------------------------------------------------ # + +def PackFormIntoFrame(form, containing_frame, toplevel_form): + def CharWidthInPixels(): + return tkinter.font.Font().measure('A') # single character width + # only set title on non-tabbed forms + border_depth = toplevel_form.BorderDepth if toplevel_form.BorderDepth is not None else DEFAULT_BORDER_WIDTH + # --------------------------------------------------------------------------- # + # **************** Use FlexForm to build the tkinter window ********** ----- # + # Building is done row by row. # + # --------------------------------------------------------------------------- # + focus_set = False + ######################### LOOP THROUGH ROWS ######################### + # *********** ------- Loop through ROWS ------- ***********# + for row_num, flex_row in enumerate(form.Rows): + ######################### LOOP THROUGH ELEMENTS ON ROW ######################### + # *********** ------- Loop through ELEMENTS ------- ***********# + # *********** Make TK Row ***********# + tk_row_frame = tk.Frame(containing_frame) + for col_num, element in enumerate(flex_row): + element.ParentForm = toplevel_form # save the button's parent form object + if toplevel_form.Font and (element.Font == DEFAULT_FONT or not element.Font): + font = toplevel_form.Font + elif element.Font is not None: + font = element.Font + else: + font = DEFAULT_FONT + # ------- Determine Auto-Size setting on a cascading basis ------- # + if element.AutoSizeText is not None: # if element overide + auto_size_text = element.AutoSizeText + elif toplevel_form.AutoSizeText is not None: # if form override + auto_size_text = toplevel_form.AutoSizeText + else: + auto_size_text = DEFAULT_AUTOSIZE_TEXT + element_type = element.Type + # Set foreground color + text_color = element.TextColor + # Determine Element size + element_size = element.Size + if (element_size == (None, None) and element_type != ELEM_TYPE_BUTTON): # user did not specify a size + element_size = toplevel_form.DefaultElementSize + elif (element_size == (None, None) and element_type == ELEM_TYPE_BUTTON): + element_size = toplevel_form.DefaultButtonElementSize + else: auto_size_text = False # if user has specified a size then it shouldn't autosize + # ------------------------- COLUMN element ------------------------- # + if element_type == ELEM_TYPE_COLUMN: + if element.Scrollable: + col_frame = TkScrollableFrame(tk_row_frame) # do not use yet! not working + PackFormIntoFrame(element, col_frame.TKFrame, toplevel_form) + col_frame.TKFrame.update() + if element.Size == (None, None): # if no size specified, use column width x column height/2 + col_frame.canvas.config(width=col_frame.TKFrame.winfo_reqwidth(),height=col_frame.TKFrame.winfo_reqheight()/2) + else: + col_frame.canvas.config(width=element.Size[0],height=element.Size[1]) + + if not element.BackgroundColor in (None, COLOR_SYSTEM_DEFAULT): + col_frame.canvas.config(background=element.BackgroundColor) + col_frame.TKFrame.config(background=element.BackgroundColor, borderwidth =0, highlightthickness=0) + col_frame.config(background=element.BackgroundColor, borderwidth =0, highlightthickness=0) + else: + col_frame = tk.Frame(tk_row_frame) + PackFormIntoFrame(element, col_frame, toplevel_form) + + col_frame.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + col_frame.configure(background=element.BackgroundColor, highlightbackground=element.BackgroundColor, highlightcolor=element.BackgroundColor) + + # ------------------------- TEXT element ------------------------- # + elif element_type == ELEM_TYPE_TEXT: + # auto_size_text = element.AutoSizeText + display_text = element.DisplayText # text to display + if auto_size_text is False: + width, height=element_size + else: + lines = display_text.split('\n') + max_line_len = max([len(l) for l in lines]) + num_lines = len(lines) + if max_line_len > element_size[0]: # if text exceeds element size, the will have to wrap + width = element_size[0] + else: + width=max_line_len + height=num_lines + # ---===--- LABEL widget create and place --- # + stringvar = tk.StringVar() + element.TKStringVar = stringvar + stringvar.set(display_text) + if auto_size_text: + width = 0 + if element.Justification is not None: + justification = element.Justification + elif toplevel_form.TextJustification is not None: + justification = toplevel_form.TextJustification + else: + justification = DEFAULT_TEXT_JUSTIFICATION + justify = tk.LEFT if justification == 'left' else tk.CENTER if justification == 'center' else tk.RIGHT + anchor = tk.NW if justification == 'left' else tk.N if justification == 'center' else tk.NE + tktext_label = tk.Label(tk_row_frame, textvariable=stringvar, width=width, height=height, justify=justify, bd=border_depth, font=font) + # Set wrap-length for text (in PIXELS) == PAIN IN THE ASS + wraplen = tktext_label.winfo_reqwidth()+40 # width of widget in Pixels + if not auto_size_text and height == 1: + wraplen = 0 + # print("wraplen, width, height", wraplen, width, height) + tktext_label.configure(anchor=anchor, wraplen=wraplen) # set wrap to width of widget + if element.Relief is not None: + tktext_label.configure(relief=element.Relief) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + tktext_label.configure(background=element.BackgroundColor) + if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + tktext_label.configure(fg=element.TextColor) + tktext_label.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1], expand=True) + element.TKText = tktext_label + if element.ClickSubmits: + tktext_label.bind('', element.TextClickedHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKText, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- BUTTON element ------------------------- # + elif element_type == ELEM_TYPE_BUTTON: + stringvar = tk.StringVar() + element.TKStringVar = stringvar + element.Location = (row_num, col_num) + btext = element.ButtonText + btype = element.BType + if element.AutoSizeButton is not None: + auto_size = element.AutoSizeButton + else: auto_size = toplevel_form.AutoSizeButtons + if auto_size is False or element.Size[0] is not None: + width, height = element_size + else: + width = 0 + height= toplevel_form.DefaultButtonElementSize[1] + if element.ButtonColor != (None, None)and element.ButtonColor != DEFAULT_BUTTON_COLOR: + bc = element.ButtonColor + elif toplevel_form.ButtonColor != (None, None) and toplevel_form.ButtonColor != DEFAULT_BUTTON_COLOR: + bc = toplevel_form.ButtonColor + else: + bc = DEFAULT_BUTTON_COLOR + border_depth = element.BorderWidth + if btype != BUTTON_TYPE_REALTIME: + tkbutton = tk.Button(tk_row_frame, text=btext, width=width, height=height,command=element.ButtonCallBack, justify=tk.LEFT, bd=border_depth, font=font) + else: + tkbutton = tk.Button(tk_row_frame, text=btext, width=width, height=height, justify=tk.LEFT, bd=border_depth, font=font) + tkbutton.bind('', element.ButtonReleaseCallBack) + tkbutton.bind('', element.ButtonPressCallBack) + if bc != (None, None) and bc != COLOR_SYSTEM_DEFAULT: + tkbutton.config(foreground=bc[0], background=bc[1], activebackground=bc[1]) + element.TKButton = tkbutton # not used yet but save the TK button in case + wraplen = tkbutton.winfo_reqwidth() # width of widget in Pixels + if element.ImageFilename: # if button has an image on it + tkbutton.config(highlightthickness=0) + photo = tk.PhotoImage(file=element.ImageFilename) + if element.ImageSize != (None, None): + width, height = element.ImageSize + if element.ImageSubsample: + photo = photo.subsample(element.ImageSubsample) + else: + width, height = photo.width(), photo.height() + tkbutton.config(image=photo, width=width, height=height) + tkbutton.image = photo + if width != 0: + tkbutton.configure(wraplength=wraplen+10) # set wrap to width of widget + tkbutton.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.BindReturnKey: + element.TKButton.bind('', element.ReturnKeyHandler) + if element.Focus is True or (toplevel_form.UseDefaultFocus and not focus_set): + focus_set = True + element.TKButton.bind('', element.ReturnKeyHandler) + element.TKButton.focus_set() + toplevel_form.TKroot.focus_force() + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKButton, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT (Single Line) element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_TEXT: + default_text = element.DefaultText + element.TKStringVar = tk.StringVar() + element.TKStringVar.set(default_text) + show = element.PasswordCharacter if element.PasswordCharacter else "" + if element.Justification is not None: + justification = element.Justification + else: + justification = DEFAULT_TEXT_JUSTIFICATION + justify = tk.LEFT if justification == 'left' else tk.CENTER if justification == 'center' else tk.RIGHT + # anchor = tk.NW if justification == 'left' else tk.N if justification == 'center' else tk.NE + element.TKEntry = tk.Entry(tk_row_frame, width=element_size[0], textvariable=element.TKStringVar, bd=border_depth, font=font, show=show, justify=justify) + element.TKEntry.bind('', element.ReturnKeyHandler) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKEntry.configure(background=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKEntry.configure(fg=text_color) + element.TKEntry.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1], expand=True, fill='x') + if element.Focus is True or (toplevel_form.UseDefaultFocus and not focus_set): + focus_set = True + element.TKEntry.focus_set() + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKEntry, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- COMBO BOX (Drop Down) element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_COMBO: + max_line_len = max([len(str(l)) for l in element.Values]) + if auto_size_text is False: width=element_size[0] + else: width = max_line_len + element.TKStringVar = tk.StringVar() + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + combostyle = ttk.Style() + try: + combostyle.theme_create('combostyle', + settings={'TCombobox': + {'configure': + {'selectbackground': element.BackgroundColor, + 'fieldbackground': element.BackgroundColor, + 'foreground': text_color, + 'background': element.BackgroundColor} + }}) + except: + try: + combostyle.theme_settings('combostyle', + settings={'TCombobox': + {'configure': + {'selectbackground': element.BackgroundColor, + 'fieldbackground': element.BackgroundColor, + 'foreground': text_color, + 'background': element.BackgroundColor} + }}) + except: pass + # ATTENTION: this applies the new style 'combostyle' to all ttk.Combobox + combostyle.theme_use('combostyle') + element.TKCombo = ttk.Combobox(tk_row_frame, width=width, textvariable=element.TKStringVar,font=font ) + if element.Size[1] != 1 and element.Size[1] is not None: + element.TKCombo.configure(height=element.Size[1]) + # element.TKCombo['state']='readonly' + element.TKCombo['values'] = element.Values + if element.InitializeAsDisabled: + element.TKCombo['state'] = 'disabled' + # if element.BackgroundColor is not None: + # element.TKCombo.configure(background=element.BackgroundColor) + element.TKCombo.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.DefaultValue: + for i, v in enumerate(element.Values): + if v == element.DefaultValue: + element.TKCombo.current(i) + break + else: + element.TKCombo.current(0) + if element.ChangeSubmits: + element.TKCombo.bind('<>', element.ComboboxSelectHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKCombo, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- OPTION MENU (Like ComboBox but different) element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_OPTION_MENU: + max_line_len = max([len(str(l)) for l in element.Values]) + if auto_size_text is False: width=element_size[0] + else: width = max_line_len + element.TKStringVar = tk.StringVar() + default = element.DefaultValue if element.DefaultValue else element.Values[0] + element.TKStringVar.set(default) + element.TKOptionMenu = tk.OptionMenu(tk_row_frame, element.TKStringVar ,*element.Values) + element.TKOptionMenu.config(highlightthickness=0, font=font, width=width ) + element.TKOptionMenu.config(borderwidth=border_depth) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKOptionMenu.configure(background=element.BackgroundColor) + if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + element.TKOptionMenu.configure(fg=element.TextColor) + element.TKOptionMenu.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKOptionMenu, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- LISTBOX element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_LISTBOX: + max_line_len = max([len(str(l)) for l in element.Values]) + if auto_size_text is False: width=element_size[0] + else: width = max_line_len + listbox_frame = tk.Frame(tk_row_frame) + element.TKStringVar = tk.StringVar() + element.TKListbox= tk.Listbox(listbox_frame, height=element_size[1], width=width, selectmode=element.SelectMode, font=font) + for index, item in enumerate(element.Values): + element.TKListbox.insert(tk.END, item) + if element.DefaultValues is not None and item in element.DefaultValues: + element.TKListbox.selection_set(index) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKListbox.configure(background=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKListbox.configure(fg=text_color) + if element.ChangeSubmits: + element.TKListbox.bind('<>', element.ListboxSelectHandler) + vsb = tk.Scrollbar(listbox_frame, orient="vertical", command=element.TKListbox.yview) + element.TKListbox.configure(yscrollcommand=vsb.set) + element.TKListbox.pack(side=tk.LEFT) + vsb.pack(side=tk.LEFT, fill='y') + listbox_frame.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.BindReturnKey: + element.TKListbox.bind('', element.ReturnKeyHandler) + element.TKListbox.bind('', element.ReturnKeyHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKListbox, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT MULTI LINE element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_MULTILINE: + default_text = element.DefaultText + width, height = element_size + element.TKText = tk.scrolledtext.ScrolledText(tk_row_frame, width=width, height=height, wrap='word', bd=border_depth,font=font) + element.TKText.insert(1.0, default_text) # set the default text + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKText.configure(background=element.BackgroundColor) + element.TKText.vbar.config(troughcolor=DEFAULT_SCROLLBAR_COLOR) + element.TKText.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1], expand=True, fill='both') + if element.EnterSubmits: + element.TKText.bind('', element.ReturnKeyHandler) + if element.Focus is True or (toplevel_form.UseDefaultFocus and not focus_set): + focus_set = True + element.TKText.focus_set() + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKText.configure(fg=text_color) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKText, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT CHECKBOX element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_CHECKBOX: + width = 0 if auto_size_text else element_size[0] + default_value = element.InitialState + element.TKIntVar = tk.IntVar() + element.TKIntVar.set(default_value if default_value is not None else 0) + if element.ChangeSubmits: + element.TKCheckbutton = tk.Checkbutton(tk_row_frame, anchor=tk.NW, text=element.Text, width=width, + variable=element.TKIntVar, bd=border_depth, font=font, + command=element.CheckboxHandler) + else: + element.TKCheckbutton = tk.Checkbutton(tk_row_frame, anchor=tk.NW, text=element.Text, width=width, + variable=element.TKIntVar, bd=border_depth, font=font) + if default_value is None: + element.TKCheckbutton.configure(state='disable') + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKCheckbutton.configure(background=element.BackgroundColor) + element.TKCheckbutton.configure(selectcolor=element.BackgroundColor) + element.TKCheckbutton.configure(activebackground=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKCheckbutton.configure(fg=text_color) + element.TKCheckbutton.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKCheckbutton, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- PROGRESS BAR element ------------------------- # + elif element_type == ELEM_TYPE_PROGRESS_BAR: + # save this form because it must be 'updated' (refreshed) solely for the purpose of updating bar + width = element_size[0] + fnt = tkinter.font.Font() + char_width = fnt.measure('A') # single character width + progress_length = width*char_width + progress_width = element_size[1] + direction = element.Orientation + if element.BarColor != (None, None): # if element has a bar color, use it + bar_color = element.BarColor + else: + bar_color = DEFAULT_PROGRESS_BAR_COLOR + element.TKProgressBar = TKProgressBar(tk_row_frame, element.MaxValue, progress_length, progress_width, orientation=direction, BarColor=bar_color, border_width=element.BorderWidth, relief=element.Relief, style=element.BarStyle ) + element.TKProgressBar.TKProgressBarForReal.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + # ------------------------- INPUT RADIO BUTTON element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_RADIO: + width = 0 if auto_size_text else element_size[0] + default_value = element.InitialState + ID = element.GroupID + # see if ID has already been placed + value = EncodeRadioRowCol(row_num, col_num) # value to set intvar to if this radio is selected + if ID in toplevel_form.RadioDict: + RadVar = toplevel_form.RadioDict[ID] + else: + RadVar = tk.IntVar() + toplevel_form.RadioDict[ID] = RadVar + element.TKIntVar = RadVar # store the RadVar in Radio object + if default_value: # if this radio is the one selected, set RadVar to match + element.TKIntVar.set(value) + element.TKRadio = tk.Radiobutton(tk_row_frame, anchor=tk.NW, text=element.Text, width=width, + variable=element.TKIntVar, value=value, bd=border_depth, font=font) + if not element.BackgroundColor in (None, COLOR_SYSTEM_DEFAULT): + element.TKRadio.configure(background=element.BackgroundColor) + element.TKRadio.configure(selectcolor=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKRadio.configure(fg=text_color) + element.TKRadio.pack(side=tk.LEFT, padx=element.Pad[0],pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKRadio, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT SPIN Box element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_SPIN: + width, height = element_size + width = 0 if auto_size_text else element_size[0] + element.TKStringVar = tk.StringVar() + element.TKSpinBox = tk.Spinbox(tk_row_frame, values=element.Values, textvariable=element.TKStringVar, width=width, bd=border_depth) + element.TKStringVar.set(element.DefaultValue) + element.TKSpinBox.configure(font=font) # set wrap to width of widget + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKSpinBox.configure(background=element.BackgroundColor) + element.TKSpinBox.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKSpinBox.configure(fg=text_color) + if element.ChangeSubmits: + element.TKSpinBox.bind('', element.SpinChangedHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKSpinBox, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- OUTPUT element ------------------------- # + elif element_type == ELEM_TYPE_OUTPUT: + width, height = element_size + element._TKOut = TKOutput(tk_row_frame, width=width, height=height, bd=border_depth, background_color=element.BackgroundColor, text_color=text_color, font=font, pad=element.Pad) + element._TKOut.pack(side=tk.LEFT, expand=True, fill='both') + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element._TKOut, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- IMAGE Box element ------------------------- # + elif element_type == ELEM_TYPE_IMAGE: + if element.Filename is not None: + photo = tk.PhotoImage(file=element.Filename) + elif element.Data is not None: + photo = tk.PhotoImage(data=element.Data) + else: + photo = None + print('*ERROR laying out form.... Image Element has no image specified*') + + if photo is not None: + if element_size == (None, None) or element_size == None or element_size == toplevel_form.DefaultElementSize: + width, height = photo.width(), photo.height() + else: + width, height = element_size + if photo is not None: + element.tktext_label = tk.Label(tk_row_frame, image=photo, width=width, height=height, bd=border_depth) + else: + element.tktext_label = tk.Label(tk_row_frame, width=width, height=height, bd=border_depth) + element.tktext_label.image = photo + # tktext_label.configure(anchor=tk.NW, image=photo) + element.tktext_label.pack(side=tk.LEFT, padx=element.Pad[0],pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.tktext_label, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- Canvas element ------------------------- # + elif element_type == ELEM_TYPE_CANVAS: + width, height = element_size + if element._TKCanvas is None: + element._TKCanvas = tk.Canvas(tk_row_frame, width=width, height=height, bd=border_depth) + else: + element._TKCanvas.master = tk_row_frame + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element._TKCanvas.configure(background=element.BackgroundColor, highlightthickness=0) + element._TKCanvas.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element._TKCanvas, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- Graph element ------------------------- # + elif element_type == ELEM_TYPE_GRAPH: + width, height = element_size + if element._TKCanvas is None: + element._TKCanvas = tk.Canvas(tk_row_frame, width=width, height=height, bd=border_depth) + else: + element._TKCanvas.master = tk_row_frame + element._TKCanvas2 = tk.Canvas(element._TKCanvas, width=width, height=height, bd=border_depth) + element._TKCanvas2.pack(side=tk.LEFT) + element._TKCanvas2.addtag_all('mytag') + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element._TKCanvas2.configure(background=element.BackgroundColor, highlightthickness=0) + element._TKCanvas.configure(background=element.BackgroundColor, highlightthickness=0) + element._TKCanvas.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element._TKCanvas, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- MENUBAR element ------------------------- # + elif element_type == ELEM_TYPE_MENUBAR: + menu_def = element.MenuDefinition + element.TKMenu = tk.Menu(toplevel_form.TKroot, tearoff=element.Tearoff) # create the menubar + menubar = element.TKMenu + for menu_entry in menu_def: + # print(f'Adding a Menubar ENTRY {menu_entry}') + baritem = tk.Menu(menubar, tearoff=element.Tearoff) + pos = menu_entry[0].find('&') + # print(pos) + if pos != -1: + if pos == 0 or menu_entry[0][pos-1] != "\\": + menu_entry[0] = menu_entry[0][:pos] + menu_entry[0][pos+1:] + menubar.add_cascade(label=menu_entry[0], menu=baritem, underline = pos) + if len(menu_entry) > 1: + AddMenuItem(baritem, menu_entry[1], element) + toplevel_form.TKroot.configure(menu=element.TKMenu) + # ------------------------- Frame element ------------------------- # + elif element_type == ELEM_TYPE_FRAME: + labeled_frame = tk.LabelFrame(tk_row_frame, text=element.Title, relief=element.Relief) + PackFormIntoFrame(element, labeled_frame, toplevel_form) + labeled_frame.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + labeled_frame.configure(background=element.BackgroundColor, highlightbackground=element.BackgroundColor, highlightcolor=element.BackgroundColor) + if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + labeled_frame.configure(foreground=element.TextColor) + if font is not None: + labeled_frame.configure(font=font) + if element.TitleLocation is not None: + labeled_frame.configure(labelanchor=element.TitleLocation) + if element.BorderWidth is not None: + labeled_frame.configure(borderwidth=element.BorderWidth) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(labeled_frame, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- Tab element ------------------------- # + elif element_type == ELEM_TYPE_TAB: + element.TKFrame = tk.Frame(form.TKNotebook) + PackFormIntoFrame(element, element.TKFrame, toplevel_form) + form.TKNotebook.add(element.TKFrame, text=element.Title) + form.TKNotebook.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + + if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + element.TKFrame.configure(background=element.BackgroundColor, + highlightbackground=element.BackgroundColor, + highlightcolor=element.BackgroundColor) + # if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + # element.TKFrame.configure(foreground=element.TextColor) + if element.BorderWidth is not None: + element.TKFrame.configure(borderwidth=element.BorderWidth) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKFrame, text=element.Tooltip, + timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- TabGroup element ------------------------- # + elif element_type == ELEM_TYPE_TAB_GROUP: + element.TKNotebook = ttk.Notebook(tk_row_frame) + PackFormIntoFrame(element, toplevel_form.TKroot, toplevel_form) + + # element.TKNotebook.pack(side=tk.LEFT) + # if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + # element.TKNotebook.configure(background=element.BackgroundColor, + # highlightbackground=element.BackgroundColor, + # highlightcolor=element.BackgroundColor) + # if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + # element.TKNotebook.configure(foreground=element.TextColor) + if element.ChangeSubmits: + element.TKNotebook.bind('<>', element.TabGroupSelectHandler) + if element.BorderWidth is not None: + element.TKNotebook.configure(borderwidth=element.BorderWidth) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKNotebook, text=element.Tooltip, + timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- SLIDER Box element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_SLIDER: + slider_length = element_size[0] * CharWidthInPixels() + slider_width = element_size[1] + element.TKIntVar = tk.IntVar() + element.TKIntVar.set(element.DefaultValue) + if element.Orientation[0] == 'v': + range_from = element.Range[1] + range_to = element.Range[0] + slider_length += DEFAULT_MARGINS[1]*(element_size[0]*2) # add in the padding + else: + range_from = element.Range[0] + range_to = element.Range[1] + if element.ChangeSubmits: + tkscale = tk.Scale(tk_row_frame, orient=element.Orientation, variable=element.TKIntVar, from_=range_from, to_=range_to, resolution = element.Resolution, length=slider_length, width=slider_width , bd=element.BorderWidth, relief=element.Relief, font=font, command=element.SliderChangedHandler) + else: + tkscale = tk.Scale(tk_row_frame, orient=element.Orientation, variable=element.TKIntVar, from_=range_from, to_=range_to, resolution = element.Resolution, length=slider_length, width=slider_width , bd=element.BorderWidth, relief=element.Relief, font=font) + tkscale.config(highlightthickness=0) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + tkscale.configure(background=element.BackgroundColor) + if DEFAULT_SCROLLBAR_COLOR != COLOR_SYSTEM_DEFAULT: + tkscale.config(troughcolor=DEFAULT_SCROLLBAR_COLOR) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + tkscale.configure(fg=text_color) + tkscale.pack(side=tk.LEFT, padx=element.Pad[0],pady=element.Pad[1]) + element.TKScale = tkscale + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKScale, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- TABLE element ------------------------- # + elif element_type == ELEM_TYPE_TABLE: + width, height = element_size + if element.Justification == 'left': + anchor = tk.W + elif element.Justification == 'right': + anchor = tk.E + else: + anchor = tk.CENTER + column_widths = {} + for row in element.Values: + for i,col in enumerate(row): + col_width = min(len(str(col)), element.MaxColumnWidth) + try: + if col_width > column_widths[i]: + column_widths[i] = col_width + except: + column_widths[i] = col_width + if element.ColumnsToDisplay is None: + displaycolumns = element.ColumnHeadings + else: + displaycolumns = [] + for i, should_display in enumerate(element.ColumnsToDisplay): + if should_display: + displaycolumns.append(element.ColumnHeadings[i]) + column_headings= element.ColumnHeadings + if element.DisplayRowNumbers: # if display row number, tack on the numbers to front of columns + displaycolumns = ['Row',] + displaycolumns + column_headings = ['Row',] + element.ColumnHeadings + element.TKTreeview = ttk.Treeview(tk_row_frame, columns=column_headings, + displaycolumns=displaycolumns, show='headings', height=height, selectmode=element.SelectMode) + treeview = element.TKTreeview + if element.DisplayRowNumbers: + treeview.heading('Row', text='Row') # make a dummy heading + treeview.column('Row', width=50, anchor=anchor) + for i, heading in enumerate(element.ColumnHeadings): + treeview.heading(heading, text=heading) + if element.AutoSizeColumns: + width = max(column_widths[i], len(heading)) + else: + try: + width = element.ColumnWidths[i] + except: + width = element.DefaultColumnWidth + + treeview.column(heading, width=width*CharWidthInPixels(), anchor=anchor) + for i, value in enumerate(element.Values): + if element.DisplayRowNumbers: + value = [i] + value + id = treeview.insert('', 'end', text=value, values=value) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKTreeview.configure(background=element.BackgroundColor) + # scrollable_frame.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1], expand=True, fill='both') + element.TKTreeview.pack(side=tk.LEFT,expand=True, padx=0, pady=0, fill='both') + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKTreeview, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + #............................DONE WITH ROW pack the row of widgets ..........................# + # done with row, pack the row of widgets + # tk_row_frame.grid(row=row_num+2, sticky=tk.NW, padx=DEFAULT_MARGINS[0]) + tk_row_frame.pack(side=tk.TOP, anchor='nw', padx=DEFAULT_MARGINS[0], expand=True) + if form.BackgroundColor is not None and form.BackgroundColor != COLOR_SYSTEM_DEFAULT: + tk_row_frame.configure(background=form.BackgroundColor) + toplevel_form.TKroot.configure(padx=DEFAULT_MARGINS[0], pady=DEFAULT_MARGINS[1]) + return + + +def ConvertFlexToTK(MyFlexForm): + master = MyFlexForm.TKroot + # only set title on non-tabbed forms + master.title(MyFlexForm.Title) + InitializeResults(MyFlexForm) + try: + if MyFlexForm.NoTitleBar: + MyFlexForm.TKroot.wm_overrideredirect(True) + except: + pass + PackFormIntoFrame(MyFlexForm, master, MyFlexForm) + #....................................... DONE creating and laying out window ..........................# + screen_width = master.winfo_screenwidth() # get window info to move to middle of screen + screen_height = master.winfo_screenheight() + if MyFlexForm.Location != (None, None): + x,y = MyFlexForm.Location + elif DEFAULT_WINDOW_LOCATION != (None, None): + x,y = DEFAULT_WINDOW_LOCATION + else: + master.update_idletasks() # don't forget to do updates or values are bad + win_width = master.winfo_width() + win_height = master.winfo_height() + x = screen_width/2 -win_width/2 + y = screen_height/2 - win_height/2 + if y+win_height > screen_height: + y = screen_height-win_height + if x+win_width > screen_width: + x = screen_width-win_width + + move_string = '+%i+%i'%(int(x),int(y)) + master.geometry(move_string) + + master.update_idletasks() # don't forget + + return + + + +# ----====----====----====----====----==== STARTUP TK ====----====----====----====----====----# +def StartupTK(my_flex_form): + global _my_windows + + ow = _my_windows.NumOpenWindows + + # print('Starting TK open Windows = {}'.format(ow)) + if not ow and not my_flex_form.ForceTopLevel: + root = tk.Tk() + else: + root = tk.Toplevel() + + try: + root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint' + except: + pass + # root.wm_overrideredirect(True) + if my_flex_form.BackgroundColor is not None and my_flex_form.BackgroundColor != COLOR_SYSTEM_DEFAULT: + root.configure(background=my_flex_form.BackgroundColor) + _my_windows.Increment() + + my_flex_form.TKroot = root + # Make moveable window + if (my_flex_form.GrabAnywhere is not False and not (my_flex_form.NonBlocking and my_flex_form.GrabAnywhere is not True)): + root.bind("", my_flex_form.StartMove) + root.bind("", my_flex_form.StopMove) + root.bind("", my_flex_form.OnMotion) + + if my_flex_form.KeepOnTop: + root.wm_attributes("-topmost", 1) + + # root.protocol("WM_DELETE_WINDOW", MyFlexForm.DestroyedCallback()) + # root.bind('', MyFlexForm.DestroyedCallback()) + ConvertFlexToTK(my_flex_form) + + my_flex_form.SetIcon(my_flex_form.WindowIcon) + + try: + root.attributes('-alpha', 255) # hide window while building it. makes for smoother 'paint' + except: + pass + + if not my_flex_form.Resizable: + my_flex_form.TKroot.resizable(False, False) #prevent user from resizing the window with dragging + + if my_flex_form.ReturnKeyboardEvents and not my_flex_form.NonBlocking: + root.bind("", my_flex_form._KeyboardCallback) + root.bind("", my_flex_form._MouseWheelCallback) + elif my_flex_form.ReturnKeyboardEvents: + root.bind("", my_flex_form._KeyboardCallback) + root.bind("", my_flex_form._MouseWheelCallback) + + if my_flex_form.AutoClose: + duration = DEFAULT_AUTOCLOSE_TIME if my_flex_form.AutoCloseDuration is None else my_flex_form.AutoCloseDuration + my_flex_form.TKAfterID = root.after(duration * 1000, my_flex_form._AutoCloseAlarmCallback) + if my_flex_form.NonBlocking: + my_flex_form.TKroot.protocol("WM_WINDOW_DESTROYED", my_flex_form.OnClosingCallback()) + else: # it's a blocking form + # print('..... CALLING MainLoop') + my_flex_form.TKroot.mainloop() + # print('..... BACK from MainLoop') + if not my_flex_form.FormRemainedOpen: + _my_windows.Decrement() + if my_flex_form.RootNeedsDestroying: + my_flex_form.TKroot.destroy() + my_flex_form.RootNeedsDestroying = False + return + +# ==============================_GetNumLinesNeeded ==# +# Helper function for determining how to wrap text # +# ===================================================# +def _GetNumLinesNeeded(text, max_line_width): + if max_line_width == 0: + return 1 + lines = text.split('\n') + num_lines = len(lines) # number of original lines of text + max_line_len = max([len(l) for l in lines]) # longest line + lines_used = [] + for L in lines: + lines_used.append(len(L)//max_line_width + (len(L) % max_line_width > 0)) # fancy math to round up + total_lines_needed = sum(lines_used) + return total_lines_needed + +# ============================== PROGRESS METER ========================================== # + +def ConvertArgsToSingleString(*args): + max_line_total, width_used , total_lines, = 0,0,0 + single_line_message = '' + # loop through args and built a SINGLE string from them + for message in args: + # fancy code to check if string and convert if not is not need. Just always convert to string :-) + # if not isinstance(message, str): message = str(message) + message = str(message) + longest_line_len = max([len(l) for l in message.split('\n')]) + width_used = max(longest_line_len, width_used) + max_line_total = max(max_line_total, width_used) + lines_needed = _GetNumLinesNeeded(message, width_used) + total_lines += lines_needed + single_line_message += message + '\n' + return single_line_message, width_used, total_lines + + +# ============================== ProgressMeter =====# +# ===================================================# +def _ProgressMeter(title, max_value, *args, orientation=None, bar_color=(None,None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, grab_anywhere=False): + ''' + Create and show a form on tbe caller's behalf. + :param title: + :param max_value: + :param args: ANY number of arguments the caller wants to display + :param orientation: + :param bar_color: + :param size: + :param Style: + :param StyleOffset: + :return: ProgressBar object that is in the form + ''' + local_orientation = DEFAULT_METER_ORIENTATION if orientation is None else orientation + local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if border_width is None else border_width + bar2 = ProgressBar(max_value, orientation=local_orientation, size=size, bar_color=bar_color, border_width=local_border_width, relief=DEFAULT_PROGRESS_BAR_RELIEF) + form = Window(title, auto_size_text=True, grab_anywhere=grab_anywhere) + + # Form using a horizontal bar + if local_orientation[0].lower() == 'h': + single_line_message, width, height = ConvertArgsToSingleString(*args) + bar2.TextToDisplay = single_line_message + bar2.MaxValue = max_value + bar2.CurrentValue = 0 + bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True) + form.AddRow(bar_text) + form.AddRow((bar2)) + form.AddRow((Cancel(button_color=button_color))) + else: + single_line_message, width, height = ConvertArgsToSingleString(*args) + bar2.TextToDisplay = single_line_message + bar2.MaxValue = max_value + bar2.CurrentValue = 0 + bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True) + form.AddRow(bar2, bar_text) + form.AddRow((Cancel(button_color=button_color))) + + form.NonBlocking = True + form.Show(non_blocking= True) + return bar2, bar_text + +# ============================== ProgressMeterUpdate =====# +def _ProgressMeterUpdate(bar, value, text_elem, *args): + ''' + Update the progress meter for a form + :param form: class ProgressBar + :param value: int + :return: True if not cancelled, OK....False if Error + ''' + global _my_windows + if bar == None: return False + if bar.BarExpired: return False + message, w, h = ConvertArgsToSingleString(*args) + text_elem.Update(message) + # bar.TextToDisplay = message + bar.CurrentValue = value + rc = bar.UpdateBar(value) + if value >= bar.MaxValue or not rc: + bar.BarExpired = True + bar.ParentForm._Close() + if rc: # if update was OK but bar expired, decrement num windows + _my_windows.Decrement() + if bar.ParentForm.RootNeedsDestroying: + try: + bar.ParentForm.TKroot.destroy() + # _my_windows.Decrement() + except: pass + bar.ParentForm.RootNeedsDestroying = False + bar.ParentForm.__del__() + return False + + return rc + +# ============================== EASY PROGRESS METER ========================================== # +# class to hold the easy meter info (a global variable essentialy) +class EasyProgressMeterDataClass(): + def __init__(self, title='', current_value=1, max_value=10, start_time=None, stat_messages=()): + self.Title = title + self.CurrentValue = current_value + self.MaxValue = max_value + self.StartTime = start_time + self.StatMessages = stat_messages + self.ParentForm = None + self.MeterID = None + self.MeterText = None + + # =========================== COMPUTE PROGRESS STATS ======================# + def ComputeProgressStats(self): + utc = datetime.datetime.utcnow() + time_delta = utc - self.StartTime + total_seconds = time_delta.total_seconds() + if not total_seconds: + total_seconds = 1 + try: + time_per_item = total_seconds / self.CurrentValue + except: + time_per_item = 1 + seconds_remaining = (self.MaxValue - self.CurrentValue) * time_per_item + time_remaining = str(datetime.timedelta(seconds=seconds_remaining)) + time_remaining_short = (time_remaining).split(".")[0] + time_delta_short = str(time_delta).split(".")[0] + total_time = time_delta + datetime.timedelta(seconds=seconds_remaining) + total_time_short = str(total_time).split(".")[0] + self.StatMessages = [ + '{} of {}'.format(self.CurrentValue, self.MaxValue), + '{} %'.format(100*self.CurrentValue//self.MaxValue), + '', + ' {:6.2f} Iterations per Second'.format(self.CurrentValue/total_seconds), + ' {:6.2f} Seconds per Iteration'.format(total_seconds/(self.CurrentValue if self.CurrentValue else 1)), + '', + '{} Elapsed Time'.format(time_delta_short), + '{} Time Remaining'.format(time_remaining_short), + '{} Estimated Total Time'.format(total_time_short)] + return + + +# ============================== EasyProgressMeter =====# +def EasyProgressMeter(title, current_value, max_value, *args, orientation=None, bar_color=(None,None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None): + ''' + A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second + function call before your loop. You've got enough code to write! + :param title: Title will be shown on the window + :param current_value: Current count of your items + :param max_value: Max value your count will ever reach. This indicates it should be closed + :param args: VARIABLE number of arguements... you request it, we'll print it no matter what the item! + :param orientation: + :param bar_color: + :param size: + :param Style: + :param StyleOffset: + :return: False if should stop the meter + ''' + local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if not border_width else border_width + # STATIC VARIABLE! + # This is a very clever form of static variable using a function attribute + # If the variable doesn't yet exist, then it will create it and initialize with the 3rd parameter + EasyProgressMeter.Data = getattr(EasyProgressMeter, 'Data', EasyProgressMeterDataClass()) + # if no meter currently running + if EasyProgressMeter.Data.MeterID is None: # Starting a new meter + print("Please change your call of EasyProgressMeter to use OneLineProgressMeter. EasyProgressMeter will be removed soon") + if int(current_value) >= int(max_value): + return False + del(EasyProgressMeter.Data) + EasyProgressMeter.Data = EasyProgressMeterDataClass(title, 1, int(max_value), datetime.datetime.utcnow(), []) + EasyProgressMeter.Data.ComputeProgressStats() + message = "\n".join([line for line in EasyProgressMeter.Data.StatMessages]) + EasyProgressMeter.Data.MeterID, EasyProgressMeter.Data.MeterText= _ProgressMeter(title, int(max_value), message, *args, orientation=orientation, bar_color=bar_color, size=size, button_color=button_color, border_width=local_border_width) + EasyProgressMeter.Data.ParentForm = EasyProgressMeter.Data.MeterID.ParentForm + return True + # if exactly the same values as before, then ignore. + if EasyProgressMeter.Data.MaxValue == max_value and EasyProgressMeter.Data.CurrentValue == current_value: + return True + if EasyProgressMeter.Data.MaxValue != int(max_value): + EasyProgressMeter.Data.MeterID = None + EasyProgressMeter.Data.ParentForm = None + del(EasyProgressMeter.Data) + EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter + return True # HAVE to return TRUE or else the new meter will thing IT is failing when it hasn't + EasyProgressMeter.Data.CurrentValue = int(current_value) + EasyProgressMeter.Data.MaxValue = int(max_value) + EasyProgressMeter.Data.ComputeProgressStats() + message = '' + for line in EasyProgressMeter.Data.StatMessages: + message = message + str(line) + '\n' + message = "\n".join(EasyProgressMeter.Data.StatMessages) + args= args + (message,) + rc = _ProgressMeterUpdate(EasyProgressMeter.Data.MeterID, current_value, + EasyProgressMeter.Data.MeterText, *args) + # if counter >= max then the progress meter is all done. Indicate none running + if current_value >= EasyProgressMeter.Data.MaxValue or not rc: + EasyProgressMeter.Data.MeterID = None + del(EasyProgressMeter.Data) + EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter + return False # even though at the end, return True so don't cause error with the app + return rc # return whatever the update told us + + +def EasyProgressMeterCancel(title, *args): + EasyProgressMeter.EasyProgressMeterData = getattr(EasyProgressMeter, 'EasyProgressMeterData', EasyProgressMeterDataClass()) + if EasyProgressMeter.EasyProgressMeterData.MeterID is not None: + # tell the normal meter update that we're at max value which will close the meter + rc = EasyProgressMeter(title, EasyProgressMeter.EasyProgressMeterData.MaxValue, EasyProgressMeter.EasyProgressMeterData.MaxValue, ' *** CANCELLING ***', 'Caller requested a cancel', *args) + return rc + return True + + +# global variable containing dictionary will all currently running one-line progress meters. +_one_line_progress_meters = {} + +# ============================== OneLineProgressMeter =====# +def OneLineProgressMeter(title, current_value, max_value, key, *args, orientation=None, bar_color=(None,None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, grab_anywhere=False): + + global _one_line_progress_meters + + local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if border_width is not None else border_width + try: + meter_data = _one_line_progress_meters[key] + except: # a new meater is starting + if int(current_value) >= int(max_value): # if already expired then it's an old meter, ignore + return False + meter_data = EasyProgressMeterDataClass(title, 1, int(max_value), datetime.datetime.utcnow(), []) + _one_line_progress_meters[key] = meter_data + meter_data.ComputeProgressStats() + message = "\n".join([line for line in meter_data.StatMessages]) + meter_data.MeterID, meter_data.MeterText= _ProgressMeter(title, int(max_value), message, *args, orientation=orientation, bar_color=bar_color, size=size, button_color=button_color, border_width=local_border_width, grab_anywhere=grab_anywhere) + meter_data.ParentForm = meter_data.MeterID.ParentForm + return True + + # if exactly the same values as before, then ignore, return success. + if meter_data.MaxValue == max_value and meter_data.CurrentValue == current_value: + return True + meter_data.CurrentValue = int(current_value) + meter_data.MaxValue = int(max_value) + meter_data.ComputeProgressStats() + message = '' + for line in meter_data.StatMessages: + message = message + str(line) + '\n' + message = "\n".join(meter_data.StatMessages) + args= args + (message,) + rc = _ProgressMeterUpdate(meter_data.MeterID, current_value, + meter_data.MeterText, *args) + # if counter >= max then the progress meter is all done. Indicate none running + if current_value >= meter_data.MaxValue or not rc: + del _one_line_progress_meters[key] + return False + return rc # return whatever the update told us + + +def OneLineProgressMeterCancel(key): + global _one_line_progress_meters + + try: + meter_data = _one_line_progress_meters[key] + except: # meter is already deleted + return + OneLineProgressMeter('', meter_data.MaxValue, meter_data.MaxValue, key=key) + + + + +# input is #RRGGBB +# output is #RRGGBB +def GetComplimentaryHex(color): + # strip the # from the beginning + color = color[1:] + # convert the string into hex + color = int(color, 16) + # invert the three bytes + # as good as substracting each of RGB component by 255(FF) + comp_color = 0xFFFFFF ^ color + # convert the color back to hex by prefixing a # + comp_color = "#%06X" % comp_color + return comp_color + + + +# ======================== EasyPrint =====# +# ===================================================# +_easy_print_data = None # global variable... I'm cheating + +class DebugWin(): + def __init__(self, size=(None, None)): + # Show a form that's a running counter + win_size = size if size !=(None, None) else DEFAULT_DEBUG_WINDOW_SIZE + self.form = Window('Debug Window', auto_size_text=True, font=('Courier New', 12)) + self.output_element = Output(size=win_size) + self.form_rows = [[Text('EasyPrint Output')], + [self.output_element], + [Quit()]] + self.form.AddRows(self.form_rows) + self.form.Show(non_blocking=True) # Show a ;non-blocking form, returns immediately + return + + def Print(self, *args, end=None, sep=None): + sepchar = sep if sep is not None else ' ' + endchar = end if end is not None else '\n' + print(*args, sep=sepchar, end=endchar) + # for a in args: + # msg = str(a) + # print(msg, end="", sep=sepchar) + # print(1, 2, 3, sep='-') + # if end is None: + # print("") + self.form.ReadNonBlocking() + + def Close(self): + self.form.CloseNonBlockingForm() + self.form.__del__() + +def Print(*args, size=(None,None), end=None, sep=None): + EasyPrint(*args, size=size, end=end, sep=sep) + +def PrintClose(): + EasyPrintClose() + +def eprint(*args, size=(None,None), end=None, sep=None): + EasyPrint(*args, size=size, end=end, sep=sep) + +def EasyPrint(*args, size=(None,None), end=None, sep=None): + global _easy_print_data + + if _easy_print_data is None: + _easy_print_data = DebugWin(size=size) + _easy_print_data.Print(*args, end=end, sep=sep) + + + +def EasyPrintold(*args, size=(None,None), end=None, sep=None): + if 'easy_print_data' not in EasyPrint.__dict__: # use a function property to save DebugWin object (static variable) + EasyPrint.easy_print_data = DebugWin(size=size) + if EasyPrint.easy_print_data is None: + EasyPrint.easy_print_data = DebugWin(size=size) + EasyPrint.easy_print_data.Print(*args, end=end, sep=sep) + +def EasyPrintClose(): + if 'easy_print_data' in EasyPrint.__dict__: + if EasyPrint.easy_print_data is not None: + EasyPrint.easy_print_data._Close() + EasyPrint.easy_print_data = None + # del EasyPrint.easy_print_data + +# ======================== Scrolled Text Box =====# +# ===================================================# +def ScrolledTextBox(*args, button_color=None, yes_no=False, auto_close=False, auto_close_duration=None, size=(None, None)): + if not args: return + width, height = size + width = width if width else MESSAGE_BOX_LINE_WIDTH + form = Window(args[0], auto_size_text=True, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration) + max_line_total, max_line_width, total_lines, height_computed = 0,0,0,0 + complete_output = '' + for message in args: + # fancy code to check if string and convert if not is not need. Just always convert to string :-) + # if not isinstance(message, str): message = str(message) + message = str(message) + longest_line_len = max([len(l) for l in message.split('\n')]) + width_used = min(longest_line_len, width) + max_line_total = max(max_line_total, width_used) + max_line_width = width + lines_needed = _GetNumLinesNeeded(message, width_used) + height_computed += lines_needed + complete_output += message + '\n' + total_lines += lines_needed + height_computed = MAX_SCROLLED_TEXT_BOX_HEIGHT if height_computed > MAX_SCROLLED_TEXT_BOX_HEIGHT else height_computed + if height: + height_computed = height + form.AddRow(Multiline(complete_output, size=(max_line_width, height_computed))) + pad = max_line_total-15 if max_line_total > 15 else 1 + # show either an OK or Yes/No depending on paramater + if yes_no: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False), Yes(), No()) + button, values = form.Read() + return button + else: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False), Button('OK', size=(5, 1), button_color=button_color)) + button, values = form.Read() + return button + + +PopupScrolled = ScrolledTextBox + +# ---------------------------------------------------------------------- # +# GetPathBox # +# Pre-made dialog that looks like this roughly # +# MESSAGE # +# __________________________ # +# |__________________________| (BROWSE) # +# (SUBMIT) (CANCEL) # +# RETURNS two values: # +# True/False, path # +# (True if Submit was pressed, false otherwise) # +# ---------------------------------------------------------------------- # + +def PopupGetFolder(message, default_path='', no_window=False, size=(None,None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None)): + """ + Display popup with text entry field and browse button. Browse for folder + :param message: + :param default_path: + :param no_window: + :param size: + :param button_color: + :param background_color: + :param text_color: + :param icon: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: Contents of text field. None if closed using X + """ + if no_window: + root = tk.Tk() + try: + root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint' + except: + pass + folder_name = tk.filedialog.askdirectory() # show the 'get folder' dialog box + root.destroy() + return folder_name + + layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)], + [InputText(default_text=default_path, size=size), FolderBrowse()], + [Ok(), Cancel()]] + + window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, background_color=background_color, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + + (button, input_values) = window.LayoutAndRead(layout) + + if button != 'Ok': + return None + else: + path = input_values[0] + return path + +##################################### +# PopupGetFile # +##################################### +def PopupGetFile(message, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*.*"),), no_window=False, size=(None,None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Display popup with text entry field and browse button. Browse for file + + :param message: + :param default_path: + :param save_as: + :param file_types: + :param no_window: + :param size: + :param button_color: + :param background_color: + :param text_color: + :param icon: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + if no_window: + root = tk.Tk() + try: + root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint' + except: + pass + if save_as: + filename = tk.filedialog.asksaveasfilename(filetypes=file_types, defaultextension=default_extension) # show the 'get file' dialog box + else: + filename = tk.filedialog.askopenfilename(filetypes=file_types, defaultextension=default_extension) # show the 'get file' dialog box + root.destroy() + return filename + + browse_button = SaveAs(file_types=file_types) if save_as else FileBrowse(file_types=file_types) + + layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)], + [InputText(default_text=default_path, size=size), browse_button], + [Ok(), Cancel()]] + + window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, font=font, background_color=background_color, + no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + + (button, input_values) = window.Layout(layout).Read() + if button != 'Ok': + return None + else: + path = input_values[0] + return path + +##################################### +# PopupGetText # +##################################### +def PopupGetText(message, default_text='', password_char='', size=(None,None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Display Popup with text entry field + :param message: + :param default_text: + :param password_char: + :param size: + :param button_color: + :param background_color: + :param text_color: + :param icon: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: Text entered or None if window was closed + """ + + layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color, font=font)], + [InputText(default_text=default_text, size=size, password_char=password_char)], + [Ok(), Cancel()]] + + window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, no_titlebar=no_titlebar, + background_color=background_color, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + + (button, input_values) = window.Layout(layout).Read() + + if button != 'Ok': + return None + else: + return input_values[0] + + +# ============================== SetGlobalIcon ======# +# Sets the icon to be used by default # +# ===================================================# +def SetGlobalIcon(icon): + global _my_windows + + try: + with open(icon, 'r') as icon_file: + pass + except: + raise FileNotFoundError + _my_windows.user_defined_icon = icon + return True + + +# ============================== SetOptions =========# +# Sets the icon to be used by default # +# ===================================================# +def SetOptions(icon=None, button_color=None, element_size=(None,None), button_element_size=(None, None), margins=(None,None), + element_padding=(None,None),auto_size_text=None, auto_size_buttons=None, font=None, border_width=None, + slider_border_width=None, slider_relief=None, slider_orientation=None, + autoclose_time=None, message_box_line_width=None, + progress_meter_border_depth=None, progress_meter_style=None, + progress_meter_relief=None, progress_meter_color=None, progress_meter_size=None, + text_justification=None, background_color=None, element_background_color=None, + text_element_background_color=None, input_elements_background_color=None, input_text_color=None, + scrollbar_color=None, text_color=None, element_text_color = None, debug_win_size=(None,None), window_location=(None,None), + tooltip_time=None): + + global DEFAULT_ELEMENT_SIZE + global DEFAULT_BUTTON_ELEMENT_SIZE + global DEFAULT_MARGINS # Margins for each LEFT/RIGHT margin is first term + global DEFAULT_ELEMENT_PADDING # Padding between elements (row, col) in pixels + global DEFAULT_AUTOSIZE_TEXT + global DEFAULT_AUTOSIZE_BUTTONS + global DEFAULT_FONT + global DEFAULT_BORDER_WIDTH + global DEFAULT_AUTOCLOSE_TIME + global DEFAULT_BUTTON_COLOR + global MESSAGE_BOX_LINE_WIDTH + global DEFAULT_PROGRESS_BAR_BORDER_WIDTH + global DEFAULT_PROGRESS_BAR_STYLE + global DEFAULT_PROGRESS_BAR_RELIEF + global DEFAULT_PROGRESS_BAR_COLOR + global DEFAULT_PROGRESS_BAR_SIZE + global DEFAULT_TEXT_JUSTIFICATION + global DEFAULT_DEBUG_WINDOW_SIZE + global DEFAULT_SLIDER_BORDER_WIDTH + global DEFAULT_SLIDER_RELIEF + global DEFAULT_SLIDER_ORIENTATION + global DEFAULT_BACKGROUND_COLOR + global DEFAULT_INPUT_ELEMENTS_COLOR + global DEFAULT_ELEMENT_BACKGROUND_COLOR + global DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR + global DEFAULT_SCROLLBAR_COLOR + global DEFAULT_TEXT_COLOR + global DEFAULT_WINDOW_LOCATION + global DEFAULT_ELEMENT_TEXT_COLOR + global DEFAULT_INPUT_TEXT_COLOR + global DEFAULT_TOOLTIP_TIME + global _my_windows + + if icon: + try: + with open(icon, 'r') as icon_file: + pass + except: + raise FileNotFoundError + _my_windows.user_defined_icon = icon + + if button_color != None: + DEFAULT_BUTTON_COLOR = button_color + + if element_size != (None,None): + DEFAULT_ELEMENT_SIZE = element_size + + if button_element_size != (None,None): + DEFAULT_BUTTON_ELEMENT_SIZE = button_element_size + + if margins != (None,None): + DEFAULT_MARGINS = margins + + if element_padding != (None,None): + DEFAULT_ELEMENT_PADDING = element_padding + + if auto_size_text != None: + DEFAULT_AUTOSIZE_TEXT = auto_size_text + + if auto_size_buttons != None: + DEFAULT_AUTOSIZE_BUTTONS = auto_size_buttons + + if font !=None: + DEFAULT_FONT = font + + if border_width != None: + DEFAULT_BORDER_WIDTH = border_width + + if autoclose_time != None: + DEFAULT_AUTOCLOSE_TIME = autoclose_time + + if message_box_line_width != None: + MESSAGE_BOX_LINE_WIDTH = message_box_line_width + + if progress_meter_border_depth != None: + DEFAULT_PROGRESS_BAR_BORDER_WIDTH = progress_meter_border_depth + + if progress_meter_style != None: + DEFAULT_PROGRESS_BAR_STYLE = progress_meter_style + + if progress_meter_relief != None: + DEFAULT_PROGRESS_BAR_RELIEF = progress_meter_relief + + if progress_meter_color != None: + DEFAULT_PROGRESS_BAR_COLOR = progress_meter_color + + if progress_meter_size != None: + DEFAULT_PROGRESS_BAR_SIZE = progress_meter_size + + if slider_border_width != None: + DEFAULT_SLIDER_BORDER_WIDTH = slider_border_width + + if slider_orientation != None: + DEFAULT_SLIDER_ORIENTATION = slider_orientation + + if slider_relief != None: + DEFAULT_SLIDER_RELIEF = slider_relief + + if text_justification != None: + DEFAULT_TEXT_JUSTIFICATION = text_justification + + if background_color != None: + DEFAULT_BACKGROUND_COLOR = background_color + + if text_element_background_color != None: + DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR = text_element_background_color + + if input_elements_background_color != None: + DEFAULT_INPUT_ELEMENTS_COLOR = input_elements_background_color + + if element_background_color != None: + DEFAULT_ELEMENT_BACKGROUND_COLOR = element_background_color + + if window_location != (None,None): + DEFAULT_WINDOW_LOCATION = window_location + + if debug_win_size != (None,None): + DEFAULT_DEBUG_WINDOW_SIZE = debug_win_size + + if text_color != None: + DEFAULT_TEXT_COLOR = text_color + + if scrollbar_color != None: + DEFAULT_SCROLLBAR_COLOR = scrollbar_color + + if element_text_color != None: + DEFAULT_ELEMENT_TEXT_COLOR = element_text_color + + if input_text_color is not None: + DEFAULT_INPUT_TEXT_COLOR = input_text_color + + if tooltip_time is not None: + DEFAULT_TOOLTIP_TIME = tooltip_time + + return True + + +#################### ChangeLookAndFeel ####################### +# Predefined settings that will change the colors and styles # +# of the elements. # +############################################################## +def ChangeLookAndFeel(index): + if sys.platform == 'darwin': + print('*** Changing look and feel is not supported on Mac platform ***') + return + + # look and feel table + look_and_feel = {'SystemDefault': {'BACKGROUND' : COLOR_SYSTEM_DEFAULT, 'TEXT': COLOR_SYSTEM_DEFAULT, 'INPUT': COLOR_SYSTEM_DEFAULT,'TEXT_INPUT' : COLOR_SYSTEM_DEFAULT, 'SCROLL': COLOR_SYSTEM_DEFAULT, 'BUTTON': OFFICIAL_PYSIMPLEGUI_BUTTON_COLOR, 'PROGRESS': COLOR_SYSTEM_DEFAULT, 'BORDER': 1,'SLIDER_DEPTH':1, 'PROGRESS_DEPTH':0}, + + 'GreenTan': {'BACKGROUND' : '#9FB8AD', 'TEXT': COLOR_SYSTEM_DEFAULT, 'INPUT':'#F7F3EC','TEXT_INPUT' : 'black','SCROLL': '#F7F3EC', 'BUTTON': ('white', '#475841'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'Dark': {'BACKGROUND': 'gray25', 'TEXT': 'white', 'INPUT': 'gray30', + 'TEXT_INPUT': 'white', 'SCROLL': 'gray44', 'BUTTON': ('white', '#004F00'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Dark2': {'BACKGROUND': 'gray25', 'TEXT': 'white', 'INPUT': 'white', + 'TEXT_INPUT': 'black', 'SCROLL': 'gray44', 'BUTTON': ('white', '#004F00'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Black': {'BACKGROUND': 'black', 'TEXT': 'white', 'INPUT': 'gray30', + 'TEXT_INPUT': 'white', 'SCROLL': 'gray44', 'BUTTON': ('black', 'white'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Tan': {'BACKGROUND': '#fdf6e3', 'TEXT': '#268bd1', 'INPUT': '#eee8d5', + 'TEXT_INPUT': '#6c71c3', 'SCROLL': '#eee8d5', 'BUTTON': ('white', '#063542'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'TanBlue': {'BACKGROUND': '#e5dece', 'TEXT': '#063289', 'INPUT': '#f9f8f4', + 'TEXT_INPUT': '#242834', 'SCROLL': '#eee8d5', 'BUTTON': ('white', '#063289'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'DarkTanBlue': {'BACKGROUND': '#242834', 'TEXT': '#dfe6f8', 'INPUT': '#97755c', + 'TEXT_INPUT': 'white', 'SCROLL': '#a9afbb', 'BUTTON': ('white', '#063289'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'DarkAmber': {'BACKGROUND': '#2c2825', 'TEXT': '#fdcb52', 'INPUT': '#705e52', + 'TEXT_INPUT': '#fdcb52', 'SCROLL': '#705e52', 'BUTTON': ('black', '#fdcb52'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'DarkBlue': {'BACKGROUND': '#1a2835', 'TEXT': '#d1ecff', 'INPUT': '#335267', + 'TEXT_INPUT': '#acc2d0', 'SCROLL': '#1b6497', 'BUTTON': ('black', '#fafaf8'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Reds': {'BACKGROUND': '#280001', 'TEXT': 'white', 'INPUT': '#d8d584', + 'TEXT_INPUT': 'black', 'SCROLL': '#763e00', 'BUTTON': ('black', '#daad28'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Green': {'BACKGROUND': '#82a459', 'TEXT': 'black', 'INPUT': '#d8d584', + 'TEXT_INPUT': 'black', 'SCROLL': '#e3ecf3', 'BUTTON': ('white', '#517239'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'LightGreen' :{'BACKGROUND' : '#B7CECE', 'TEXT': 'black', 'INPUT':'#FDFFF7','TEXT_INPUT' : 'black', 'SCROLL': '#FDFFF7','BUTTON': ('white', '#658268'), 'PROGRESS':DEFAULT_PROGRESS_BAR_COLOR, 'BORDER':1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BluePurple': {'BACKGROUND' : '#A5CADD', 'TEXT': '#6E266E', 'INPUT':'#E0F5FF','TEXT_INPUT' : 'black', 'SCROLL': '#E0F5FF','BUTTON': ('white', '#303952'),'PROGRESS':DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'Purple': {'BACKGROUND': '#B0AAC2', 'TEXT': 'black', 'INPUT': '#F2EFE8','SCROLL': '#F2EFE8','TEXT_INPUT' : 'black', + 'BUTTON': ('black', '#C2D4D8'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BlueMono': {'BACKGROUND': '#AAB6D3', 'TEXT': 'black', 'INPUT': '#F1F4FC','SCROLL': '#F1F4FC','TEXT_INPUT' : 'black', + 'BUTTON': ('white', '#7186C7'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'GreenMono': {'BACKGROUND': '#A8C1B4', 'TEXT': 'black', 'INPUT': '#DDE0DE', 'SCROLL': '#E3E3E3','TEXT_INPUT' : 'black', + 'BUTTON': ('white', '#6D9F85'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BrownBlue': {'BACKGROUND': '#64778d', 'TEXT': 'white', 'INPUT': '#f0f3f7', 'SCROLL': '#A6B2BE','TEXT_INPUT' : 'black', 'BUTTON': ('white', '#283b5b'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BrightColors': {'BACKGROUND': '#b4ffb4', 'TEXT': 'black', 'INPUT': '#ffff64','SCROLL': '#ffb482','TEXT_INPUT' : 'black', 'BUTTON': ('black', '#ffa0dc'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'NeutralBlue': {'BACKGROUND': '#92aa9d', 'TEXT': 'black', 'INPUT': '#fcfff6', + 'SCROLL': '#fcfff6', 'TEXT_INPUT': 'black', 'BUTTON': ('black', '#d0dbbd'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'Kayak': {'BACKGROUND': '#a7ad7f', 'TEXT': 'black', 'INPUT': '#e6d3a8', + 'SCROLL': '#e6d3a8', 'TEXT_INPUT': 'black', 'BUTTON': ('white', '#5d907d'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'SandyBeach': {'BACKGROUND': '#efeccb', 'TEXT': '#012f2f', 'INPUT': '#e6d3a8', + 'SCROLL': '#e6d3a8', 'TEXT_INPUT': '#012f2f', 'BUTTON': ('white', '#046380'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'TealMono': {'BACKGROUND': '#a8cfdd', 'TEXT': 'black', 'INPUT': '#dfedf2','SCROLL': '#dfedf2', 'TEXT_INPUT' : 'black', 'BUTTON': ('white', '#183440'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0} + } + try: + colors = look_and_feel[index] + + SetOptions(background_color=colors['BACKGROUND'], + text_element_background_color=colors['BACKGROUND'], + element_background_color=colors['BACKGROUND'], + text_color=colors['TEXT'], + input_elements_background_color=colors['INPUT'], + button_color=colors['BUTTON'], + progress_meter_color=colors['PROGRESS'], + border_width=colors['BORDER'], + slider_border_width=colors['SLIDER_DEPTH'], + progress_meter_border_depth=colors['PROGRESS_DEPTH'], + scrollbar_color=(colors['SCROLL']), + element_text_color=colors['TEXT'], + input_text_color=colors['TEXT_INPUT']) + except: # most likely an index out of range + pass + + + + +# ============================== sprint ======# +# Is identical to the Scrolled Text Box # +# Provides a crude 'print' mechanism but in a # +# GUI environment # +# ============================================# +sprint=ScrolledTextBox + +# Converts an object's contents into a nice printable string. Great for dumping debug data +def ObjToStringSingleObj(obj): + if obj is None: + return 'None' + return str(obj.__class__) + '\n' + '\n'.join( + (repr(item) + ' = ' + repr(obj.__dict__[item]) for item in sorted(obj.__dict__))) + +def ObjToString(obj, extra=' '): + if obj is None: + return 'None' + return str(obj.__class__) + '\n' + '\n'.join( + (extra + (str(item) + ' = ' + + (ObjToString(obj.__dict__[item], extra + ' ') if hasattr(obj.__dict__[item], '__dict__') else str( + obj.__dict__[item]))) + for item in sorted(obj.__dict__))) + + +# ------------------------------------------------------------------------------------------------------------------ # +# ===================================== Upper PySimpleGUI ======================================================== # +# Pre-built dialog boxes for all your needs These are the "high level API calls # +# ------------------------------------------------------------------------------------------------------------------ # + +# ----------------------------------- The mighty Popup! ------------------------------------------------------------ # + +def Popup(*args, button_color=None, background_color=None, text_color=None, button_type=POPUP_BUTTONS_OK, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Popup - Display a popup box with as many parms as you wish to include + :param args: + :param button_color: + :param background_color: + :param text_color: + :param button_type: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + if not args: + args_to_print = [''] + else: + args_to_print = args + if line_width != None: + local_line_width = line_width + else: + local_line_width = MESSAGE_BOX_LINE_WIDTH + title = args_to_print[0] if args_to_print[0] is not None else 'None' + form = Window(title, auto_size_text=True, background_color=background_color, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, icon=icon, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + max_line_total, total_lines = 0,0 + for message in args_to_print: + # fancy code to check if string and convert if not is not need. Just always convert to string :-) + # if not isinstance(message, str): message = str(message) + message = str(message) + if message.count('\n'): + message_wrapped = message + else: + message_wrapped = textwrap.fill(message, local_line_width) + message_wrapped_lines = message_wrapped.count('\n')+1 + longest_line_len = max([len(l) for l in message.split('\n')]) + width_used = min(longest_line_len, local_line_width) + max_line_total = max(max_line_total, width_used) + # height = _GetNumLinesNeeded(message, width_used) + height = message_wrapped_lines + form.AddRow(Text(message_wrapped, auto_size_text=True, text_color=text_color, background_color=background_color)) + total_lines += height + + pad = max_line_total-15 if max_line_total > 15 else 1 + pad =1 + if non_blocking: + PopupButton = DummyButton + else: + PopupButton = SimpleButton + # show either an OK or Yes/No depending on paramater + if button_type is POPUP_BUTTONS_YES_NO: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('Yes', button_color=button_color, focus=True, bind_return_key=True), PopupButton('No', button_color=button_color)) + elif button_type is POPUP_BUTTONS_CANCELLED: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('Cancelled', button_color=button_color, focus=True, bind_return_key=True)) + elif button_type is POPUP_BUTTONS_ERROR: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('Error', size=(6, 1), button_color=button_color, focus=True, bind_return_key=True)) + elif button_type is POPUP_BUTTONS_OK_CANCEL: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('OK', size=(5, 1), button_color=button_color, focus=True, bind_return_key=True), + PopupButton('Cancel', size=(5, 1), button_color=button_color)) + elif button_type is POPUP_BUTTONS_NO_BUTTONS: + pass + else: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, background_color=background_color), PopupButton('OK', size=(5, 1), button_color=button_color, focus=True, bind_return_key=True)) + + if non_blocking: + button, values = form.ReadNonBlocking() + else: + button, values = form.Show() + + return button + + + +# ============================== MsgBox============# +# Lazy function. Same as calling Popup with parms # +# This function WILL Disappear perhaps today # +# ==================================================# +# MsgBox is the legacy call and should not be used any longer +def MsgBox(*args): + raise DeprecationWarning('MsgBox is no longer supported... change your call to Popup') + + +# --------------------------- PopupNoButtons --------------------------- +def PopupNoButtons(*args, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Show a Popup but without any buttons + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + Popup(*args, button_color=button_color, background_color=background_color, text_color=text_color, button_type=POPUP_BUTTONS_NO_BUTTONS, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + + +# --------------------------- PopupNonBlocking --------------------------- +def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Show Popup box and immediately return (does not block) + :param args: + :param button_type: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + Popup(*args, button_color=button_color, background_color=background_color, text_color=text_color, button_type=button_type, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + + +PopupNoWait = PopupNonBlocking + + +# --------------------------- PopupNoTitlebar --------------------------- +def PopupNoTitlebar(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, grab_anywhere=True, keep_on_top=False, location=(None,None)): + """ + Display a Popup without a titlebar. Enables grab anywhere so you can move it + :param args: + :param button_type: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + Popup(*args, button_color=button_color, background_color=background_color, text_color=text_color, button_type=button_type, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=True, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + +PopupNoFrame = PopupNoTitlebar +PopupNoBorder = PopupNoTitlebar +PopupAnnoying = PopupNoTitlebar + + +# --------------------------- PopupAutoClose --------------------------- +def PopupAutoClose(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=True, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None,no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Popup that closes itself after some time period + :param args: + :param button_type: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + Popup(*args, button_color=button_color, background_color=background_color, text_color=text_color, button_type=button_type, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + +PopupTimed = PopupAutoClose + +# --------------------------- PopupError --------------------------- +def PopupError(*args, button_color=DEFAULT_ERROR_BUTTON_COLOR, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Popup with colored button and 'Error' as button text + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + Popup(*args, button_type=POPUP_BUTTONS_ERROR, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + + +# --------------------------- PopupCancel --------------------------- +def PopupCancel(*args, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Display Popup with "cancelled" button text + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + Popup(*args, button_type=POPUP_BUTTONS_CANCELLED, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + +# --------------------------- PopupOK --------------------------- +def PopupOK(*args, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Display Popup with OK button only + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + Popup(*args, button_type=POPUP_BUTTONS_OK, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + +# --------------------------- PopupOKCancel --------------------------- +def PopupOKCancel(*args, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Display popup with OK and Cancel buttons + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: OK, Cancel or None + """ + return Popup(*args, button_type=POPUP_BUTTONS_OK_CANCEL, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + +# --------------------------- PopupYesNo --------------------------- +def PopupYesNo(*args, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None,None)): + """ + Display Popup with Yes and No buttons + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: Yes, No or None + """ + return Popup(*args, button_type=POPUP_BUTTONS_YES_NO, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + + +def main(): + window = Window('Demo window..') + window_rows = [[Text('You are running the PySimpleGUI.py file itself')], + [Text('You should be importing it rather than running it', size=(50,2))], + [Text('Here is your sample input window....')], + [Text('Source Folder', size=(15, 1), justification='right'), InputText('Source', focus=True),FolderBrowse()], + [Text('Destination Folder', size=(15, 1), justification='right'), InputText('Dest'), FolderBrowse()], + [Ok(), Cancel()]] + + button, (source, dest) = window.LayoutAndRead(window_rows) + + +if __name__ == '__main__': + main() + exit(69) \ No newline at end of file diff --git a/PySimpleGUI27.py b/PySimpleGUI27.py new file mode 100644 index 000000000..56b00151f --- /dev/null +++ b/PySimpleGUI27.py @@ -0,0 +1,4912 @@ +#!/usr/bin/python3 +import Tkinter as tk +# import tkinter as tk +import tkFileDialog +import ttk +import tkColorChooser +import tkFont +import ScrolledText +# from Tkinter import ttk +# import Tkinter.scrolledtext as tkst +# import Tkinter.font +import datetime +import sys +import textwrap +import pickle +import calendar + +import platform + +sVsn = platform.python_version()[0] + +if sVsn == '2': + __metaclass__ = type # required for Python v.2.X + +def fSuprArgs(self): + return () if sVsn != '2' else (self.__class__, self) + +# place *(fSuprArgs(self)) as parameter in every call to super(*(fSuprArgs(self))) + +g_time_start = 0 +g_time_end = 0 +g_time_delta = 0 + +import time +def TimerStart(): + global g_time_start + + g_time_start = time.time() + +def TimerStop(): + global g_time_delta, g_time_end + + g_time_end = time.time() + g_time_delta = g_time_end - g_time_start + print(g_time_delta) + +# ----====----====----==== Constants the user CAN safely change ====----====----====----# +DEFAULT_WINDOW_ICON = 'default_icon.ico' +DEFAULT_ELEMENT_SIZE = (45,1) # In CHARACTERS +DEFAULT_BUTTON_ELEMENT_SIZE = (10,1) # In CHARACTERS +DEFAULT_MARGINS = (10,5) # Margins for each LEFT/RIGHT margin is first term +DEFAULT_ELEMENT_PADDING = (5,3) # Padding between elements (row, col) in pixels +DEFAULT_AUTOSIZE_TEXT = True +DEFAULT_AUTOSIZE_BUTTONS = True +DEFAULT_FONT = ("Helvetica", 10) +DEFAULT_TEXT_JUSTIFICATION = 'left' +DEFAULT_BORDER_WIDTH = 1 +DEFAULT_AUTOCLOSE_TIME = 3 # time in seconds to show an autoclose form +DEFAULT_DEBUG_WINDOW_SIZE = (80,20) +DEFAULT_WINDOW_LOCATION = (None,None) +MAX_SCROLLED_TEXT_BOX_HEIGHT = 50 +DEFAULT_TOOLTIP_TIME = 400 +#################### COLOR STUFF #################### +BLUES = ("#082567","#0A37A3","#00345B") +PURPLES = ("#480656","#4F2398","#380474") +GREENS = ("#01826B","#40A860","#96D2AB", "#00A949","#003532") +YELLOWS = ("#F3FB62", "#F0F595") +TANS = ("#FFF9D5","#F4EFCF","#DDD8BA") +NICE_BUTTON_COLORS = ((GREENS[3], TANS[0]), ('#000000','#FFFFFF'),('#FFFFFF', '#000000'), (YELLOWS[0], PURPLES[1]), + (YELLOWS[0], GREENS[3]), (YELLOWS[0], BLUES[2])) + +COLOR_SYSTEM_DEFAULT = '1234567890' # Colors should never be this long +if sys.platform == 'darwin': + DEFAULT_BUTTON_COLOR = COLOR_SYSTEM_DEFAULT # Foreground, Background (None, None) == System Default + OFFICIAL_PYSIMPLEGUI_BUTTON_COLOR = COLOR_SYSTEM_DEFAULT # Colors should never be this long +else: + DEFAULT_BUTTON_COLOR = ('white', BLUES[0]) # Foreground, Background (None, None) == System Default + OFFICIAL_PYSIMPLEGUI_BUTTON_COLOR = ('white', BLUES[0]) # Colors should never be this long + +DEFAULT_ERROR_BUTTON_COLOR =("#FFFFFF", "#FF0000") +DEFAULT_BACKGROUND_COLOR = None +DEFAULT_ELEMENT_BACKGROUND_COLOR = None +DEFAULT_ELEMENT_TEXT_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR = None +DEFAULT_TEXT_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_INPUT_ELEMENTS_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_INPUT_TEXT_COLOR = COLOR_SYSTEM_DEFAULT +DEFAULT_SCROLLBAR_COLOR = None +# DEFAULT_BUTTON_COLOR = (YELLOWS[0], PURPLES[0]) # (Text, Background) or (Color "on", Color) as a way to remember +# DEFAULT_BUTTON_COLOR = (GREENS[3], TANS[0]) # Foreground, Background (None, None) == System Default +# DEFAULT_BUTTON_COLOR = (YELLOWS[0], GREENS[4]) # Foreground, Background (None, None) == System Default +# DEFAULT_BUTTON_COLOR = ('white', 'black') # Foreground, Background (None, None) == System Default +# DEFAULT_BUTTON_COLOR = (YELLOWS[0], PURPLES[2]) # Foreground, Background (None, None) == System Default +# DEFAULT_PROGRESS_BAR_COLOR = (GREENS[2], GREENS[0]) # a nice green progress bar +# DEFAULT_PROGRESS_BAR_COLOR = (BLUES[1], BLUES[1]) # a nice green progress bar +# DEFAULT_PROGRESS_BAR_COLOR = (BLUES[0], BLUES[0]) # a nice green progress bar +# DEFAULT_PROGRESS_BAR_COLOR = (PURPLES[1],PURPLES[0]) # a nice purple progress bar + +# A transparent button is simply one that matches the background +TRANSPARENT_BUTTON = ('#F0F0F0', '#F0F0F0') +#-------------------------------------------------------------------------------- +# Progress Bar Relief Choices +RELIEF_RAISED = 'raised' +RELIEF_SUNKEN = 'sunken' +RELIEF_FLAT = 'flat' +RELIEF_RIDGE = 'ridge' +RELIEF_GROOVE = 'groove' +RELIEF_SOLID = 'solid' + +DEFAULT_PROGRESS_BAR_COLOR = (GREENS[0], '#D0D0D0') # a nice green progress bar +DEFAULT_PROGRESS_BAR_SIZE = (25,20) # Size of Progress Bar (characters for length, pixels for width) +DEFAULT_PROGRESS_BAR_BORDER_WIDTH=1 +DEFAULT_PROGRESS_BAR_RELIEF = RELIEF_GROOVE +PROGRESS_BAR_STYLES = ('default','winnative', 'clam', 'alt', 'classic', 'vista', 'xpnative') +DEFAULT_PROGRESS_BAR_STYLE = 'default' +DEFAULT_METER_ORIENTATION = 'Horizontal' +DEFAULT_SLIDER_ORIENTATION = 'vertical' +DEFAULT_SLIDER_BORDER_WIDTH=1 +DEFAULT_SLIDER_RELIEF = tk.FLAT +DEFAULT_FRAME_RELIEF = tk.GROOVE + +DEFAULT_LISTBOX_SELECT_MODE = tk.SINGLE +SELECT_MODE_MULTIPLE = tk.MULTIPLE +LISTBOX_SELECT_MODE_MULTIPLE = 'multiple' +SELECT_MODE_BROWSE = tk.BROWSE +LISTBOX_SELECT_MODE_BROWSE = 'browse' +SELECT_MODE_EXTENDED = tk.EXTENDED +LISTBOX_SELECT_MODE_EXTENDED = 'extended' +SELECT_MODE_SINGLE = tk.SINGLE +LISTBOX_SELECT_MODE_SINGLE = 'single' + +TABLE_SELECT_MODE_NONE = tk.NONE +TABLE_SELECT_MODE_BROWSE = tk.BROWSE +TABLE_SELECT_MODE_EXTENDED = tk.EXTENDED +DEFAULT_TABLE_SECECT_MODE = TABLE_SELECT_MODE_EXTENDED + +TITLE_LOCATION_TOP = tk.N +TITLE_LOCATION_BOTTOM = tk.S +TITLE_LOCATION_LEFT = tk.W +TITLE_LOCATION_RIGHT = tk.E +TITLE_LOCATION_TOP_LEFT = tk.NW +TITLE_LOCATION_TOP_RIGHT = tk.NE +TITLE_LOCATION_BOTTOM_LEFT = tk.SW +TITLE_LOCATION_BOTTOM_RIGHT = tk.SE + + + + + +# DEFAULT_METER_ORIENTATION = 'Vertical' +# ----====----====----==== Constants the user should NOT f-with ====----====----====----# +ThisRow = 555666777 # magic number + + +# DEFAULT_WINDOW_ICON = '' +MESSAGE_BOX_LINE_WIDTH = 60 + +# a shameful global variable. This represents the top-level window information. Needed because opening a second window is different than opening the first. +class MyWindows(): + def __init__(self): + self.NumOpenWindows = 0 + self.user_defined_icon = None + + def Decrement(self): + self.NumOpenWindows -= 1 * (self.NumOpenWindows != 0) # decrement if not 0 + # print('---- DECREMENTING Num Open Windows = {} ---'.format(self.NumOpenWindows)) + + def Increment(self): + self.NumOpenWindows += 1 + # print('++++ INCREMENTING Num Open Windows = {} ++++'.format(self.NumOpenWindows)) + +_my_windows = MyWindows() # terrible hack using globals... means need a class for collecing windows + +# ====================================================================== # +# One-liner functions that are handy as f_ck # +# ====================================================================== # +def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue) + +# ====================================================================== # +# Enums for types # +# ====================================================================== # +# ------------------------- Button types ------------------------- # +#todo Consider removing the Submit, Cancel types... they are just 'RETURN' type in reality +#uncomment this line and indent to go back to using Enums +# class ButtonType(Enum): +BUTTON_TYPE_BROWSE_FOLDER = 1 +BUTTON_TYPE_BROWSE_FILE = 2 +BUTTON_TYPE_BROWSE_FILES = 21 +BUTTON_TYPE_SAVEAS_FILE = 3 +BUTTON_TYPE_CLOSES_WIN = 5 +BUTTON_TYPE_CLOSES_WIN_ONLY = 6 +BUTTON_TYPE_READ_FORM = 7 +BUTTON_TYPE_REALTIME = 9 +BUTTON_TYPE_CALENDAR_CHOOSER = 30 +BUTTON_TYPE_COLOR_CHOOSER = 40 + +# ------------------------- Element types ------------------------- # +# class ElementType(Enum): +ELEM_TYPE_TEXT = 1 +ELEM_TYPE_INPUT_TEXT = 20 +ELEM_TYPE_INPUT_COMBO = 21 +ELEM_TYPE_INPUT_OPTION_MENU = 22 +ELEM_TYPE_INPUT_RADIO = 5 +ELEM_TYPE_INPUT_MULTILINE = 7 +ELEM_TYPE_INPUT_CHECKBOX = 8 +ELEM_TYPE_INPUT_SPIN = 9 +ELEM_TYPE_BUTTON = 3 +ELEM_TYPE_IMAGE = 30 +ELEM_TYPE_CANVAS = 40 +ELEM_TYPE_FRAME = 41 +ELEM_TYPE_GRAPH = 42 +ELEM_TYPE_TAB = 50 +ELEM_TYPE_TAB_GROUP = 51 +ELEM_TYPE_INPUT_SLIDER = 10 +ELEM_TYPE_INPUT_LISTBOX = 11 +ELEM_TYPE_OUTPUT = 300 +ELEM_TYPE_COLUMN = 555 +ELEM_TYPE_MENUBAR = 600 +ELEM_TYPE_PROGRESS_BAR = 200 +ELEM_TYPE_BLANK = 100 +ELEM_TYPE_TABLE = 700 + +# ------------------------- Popup Buttons Types ------------------------- # +POPUP_BUTTONS_YES_NO = 1 +POPUP_BUTTONS_CANCELLED = 2 +POPUP_BUTTONS_ERROR = 3 +POPUP_BUTTONS_OK_CANCEL = 4 +POPUP_BUTTONS_OK = 0 +POPUP_BUTTONS_NO_BUTTONS = 5 + + +# ------------------------------------------------------------------------- # +# ToolTip used by the Elements # +# ------------------------------------------------------------------------- # + +class ToolTip: + """ Create a tooltip for a given widget + + (inspired by https://stackoverflow.com/a/36221216) + """ + + def __init__(self, widget, text, timeout=1000): + self.widget = widget + self.text = text + self.timeout = timeout + #self.wraplength = wraplength if wraplength else widget.winfo_screenwidth() // 2 + self.tipwindow = None + self.id = None + self.x = self.y = 0 + self.widget.bind("", self.enter) + self.widget.bind("", self.leave) + self.widget.bind("", self.leave) + + def enter(self, event=None): + self.schedule() + + def leave(self, event=None): + self.unschedule() + self.hidetip() + + def schedule(self): + self.unschedule() + self.id = self.widget.after(self.timeout, self.showtip) + + def unschedule(self): + if self.id: + self.widget.after_cancel(self.id) + self.id = None + + def showtip(self): + if self.tipwindow: + return + x = self.widget.winfo_rootx() + 20 + y = self.widget.winfo_rooty() + self.widget.winfo_height() + 1 + self.tipwindow = tk.Toplevel(self.widget) + self.tipwindow.wm_overrideredirect(True) + self.tipwindow.wm_geometry("+%d+%d" % (x, y)) + label = ttk.Label(self.tipwindow, text=self.text, justify=tk.LEFT, + background="#ffffe0", relief=tk.SOLID, borderwidth=1) + label.pack() + + def hidetip(self): + if self.tipwindow: + self.tipwindow.destroy() + self.tipwindow = None + + +# ---------------------------------------------------------------------- # +# Cascading structure.... Objects get larger # +# Button # +# Element # +# Row # +# Form # +# ---------------------------------------------------------------------- # +# ------------------------------------------------------------------------- # +# Element CLASS # +# ------------------------------------------------------------------------- # +class Element(): + def __init__(self, type, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + self.Size = size + self.Type = type + self.AutoSizeText = auto_size_text + self.Pad = DEFAULT_ELEMENT_PADDING if pad is None else pad + self.Font = font + + self.TKStringVar = None + self.TKIntVar = None + self.TKText = None + self.TKEntry = None + self.TKImage = None + + self.ParentForm=None + self.ParentContainer=None # will be a Form, Column, or Frame element + self.TextInputDefault = None + self.Position = (0,0) # Default position Row 0, Col 0 + self.BackgroundColor = background_color if background_color is not None else DEFAULT_ELEMENT_BACKGROUND_COLOR + self.TextColor = text_color if text_color is not None else DEFAULT_ELEMENT_TEXT_COLOR + self.Key = key # dictionary key for return values + self.Tooltip = tooltip + self.TooltipObject = None + + def FindReturnKeyBoundButton(self, form): + for row in form.Rows: + for element in row: + if element.Type == ELEM_TYPE_BUTTON: + if element.BindReturnKey: + return element + if element.Type == ELEM_TYPE_COLUMN: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + if element.Type == ELEM_TYPE_FRAME: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + if element.Type == ELEM_TYPE_TAB_GROUP: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + if element.Type == ELEM_TYPE_TAB: + rc = self.FindReturnKeyBoundButton(element) + if rc is not None: + return rc + return None + + def TextClickedHandler(self, event): + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.DisplayText + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + + def ReturnKeyHandler(self, event): + MyForm = self.ParentForm + button_element = self.FindReturnKeyBoundButton(MyForm) + if button_element is not None: + button_element.ButtonCallBack() + + + def ListboxSelectHandler(self, event): + MyForm = self.ParentForm + # first, get the results table built + # modify the Results table in the parent FlexForm object + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def ComboboxSelectHandler(self, event): + MyForm = self.ParentForm + # first, get the results table built + # modify the Results table in the parent FlexForm object + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def __del__(self): + try: + self.TKStringVar.__del__() + except: + pass + try: + self.TKIntVar.__del__() + except: + pass + try: + self.TKText.__del__() + except: + pass + try: + self.TKEntry.__del__() + except: + pass + +# ---------------------------------------------------------------------- # +# Input Class # +# ---------------------------------------------------------------------- # +class InputText(Element): + def __init__(self, default_text ='', size=(None, None), auto_size_text=None, password_char='', + justification=None, background_color=None, text_color=None, font=None, tooltip=None, do_not_clear=False, key=None, focus=False, pad=None): + ''' + Input a line of text Element + :param default_text: Default value to display + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param password_char: If non-blank, will display this character for every character typed + :param background_color: Color for Element. Text or RGB Hex + ''' + self.DefaultText = default_text + self.PasswordCharacter = password_char + bg = background_color if background_color is not None else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + self.Focus = focus + self.do_not_clear = do_not_clear + self.Justification = justification + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_TEXT, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad,font=font, tooltip=tooltip) + + + def Update(self, value=None, disabled=None): + if disabled is True: + self.TKEntry['state'] = 'disabled' + elif disabled is False: + self.TKEntry['state'] = 'normal' + if value is not None: + try: + self.TKStringVar.set(value) + except: pass + self.DefaultText = value + + def Get(self): + return self.TKStringVar.get() + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + +# ------------------------- INPUT TEXT Element lazy functions ------------------------- # +In = InputText +Input = InputText + +# ---------------------------------------------------------------------- # +# Combo # +# ---------------------------------------------------------------------- # +class InputCombo(Element): + def __init__(self, values, default_value=None, size=(None, None), auto_size_text=None, background_color=None, text_color=None, change_submits=False, disabled=False, key=None, pad=None, tooltip=None): + ''' + Input Combo Box Element (also called Dropdown box) + :param values: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + ''' + self.Values = values + self.DefaultValue = default_value + self.ChangeSubmits = change_submits + self.TKCombo = None + self.InitializeAsDisabled = disabled + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_COMBO, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + + def Update(self, value=None, values=None, disabled=None): + if values is not None: + try: + self.TKCombo['values'] = values + self.TKCombo.current(0) + except: pass + self.Values = values + for index, v in enumerate(self.Values): + if v == value: + try: + self.TKCombo.current(index) + except: pass + self.DefaultValue = value + break + if disabled == True: + self.TKCombo['state'] = 'disable' + elif disabled == False: + self.TKCombo['state'] = 'enable' + + + def __del__(self): + try: + self.TKCombo.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + +# ------------------------- INPUT COMBO Element lazy functions ------------------------- # +Combo = InputCombo +DropDown = InputCombo +Drop = InputCombo + +# ---------------------------------------------------------------------- # +# Option Menu # +# ---------------------------------------------------------------------- # +class InputOptionMenu(Element): + def __init__(self, values, default_value=None, size=(None, None), auto_size_text=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Input Combo Box Element (also called Dropdown box) + :param values: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + ''' + self.Values = values + self.DefaultValue = default_value + self.TKOptionMenu = None + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_OPTION_MENU, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + + def Update(self, value=None, values=None, disabled=None): + if values is not None: + self.Values = values + if self.Values is not None: + for index, v in enumerate(self.Values): + if v == value: + try: + self.TKStringVar.set(value) + except: pass + self.DefaultValue = value + break + if disabled == True: + self.TKOptionMenu['state'] = 'disabled' + elif disabled == False: + self.TKOptionMenu['state'] = 'normal' + + + def __del__(self): + try: + self.TKOptionMenu.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + + +# ------------------------- OPTION MENU Element lazy functions ------------------------- # +OptionMenu = InputOptionMenu + +# ---------------------------------------------------------------------- # +# Listbox # +# ---------------------------------------------------------------------- # +class Listbox(Element): + def __init__(self, values, default_values=None, select_mode=None, change_submits=False, bind_return_key=False, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Listbox Element + :param values: + :param select_mode: SELECT_MODE_BROWSE, SELECT_MODE_EXTENDED, SELECT_MODE_MULTIPLE, SELECT_MODE_SINGLE + :param font: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex ''' + self.Values = values + self.DefaultValues = default_values + self.TKListbox = None + self.ChangeSubmits = change_submits + self.BindReturnKey = bind_return_key + if select_mode == LISTBOX_SELECT_MODE_BROWSE: + self.SelectMode = SELECT_MODE_BROWSE + elif select_mode == LISTBOX_SELECT_MODE_EXTENDED: + self.SelectMode = SELECT_MODE_EXTENDED + elif select_mode == LISTBOX_SELECT_MODE_MULTIPLE: + self.SelectMode = SELECT_MODE_MULTIPLE + elif select_mode == LISTBOX_SELECT_MODE_SINGLE: + self.SelectMode = SELECT_MODE_SINGLE + else: + self.SelectMode = DEFAULT_LISTBOX_SELECT_MODE + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_LISTBOX, size=size, auto_size_text=auto_size_text, font=font, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + + def Update(self, values=None, disabled=None): + if disabled == True: + self.TKListbox.configure(state='disabled') + elif disabled == False: + self.TKListbox.configure(state='normal') + if values is not None: + self.TKListbox.delete(0, 'end') + for item in values: + self.TKListbox.insert(tk.END, item) + self.TKListbox.selection_set(0, 0) + self.Values = values + + + + def SetValue(self, values): + for index, item in enumerate(self.Values): + try: + if item in values: + self.TKListbox.selection_set(index) + else: + self.TKListbox.selection_clear(index) + except: pass + self.DefaultValues = values + + def __del__(self): + try: + self.TKListBox.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + + + +# ---------------------------------------------------------------------- # +# Radio # +# ---------------------------------------------------------------------- # +class Radio(Element): + def __init__(self, text, group_id, default=False, size=(None, None), auto_size_text=None, background_color=None, text_color=None, font=None, key=None, pad=None, tooltip=None): + ''' + Radio Button Element + :param text: + :param group_id: + :param default: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + :param font: + ''' + self.InitialState = default + self.Text = text + self.TKRadio = None + self.GroupID = group_id + self.Value = None + self.TextColor = text_color if text_color else DEFAULT_TEXT_COLOR + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_RADIO, size=size, auto_size_text=auto_size_text, font=font, background_color=background_color, text_color=self.TextColor, key=key, pad=pad, tooltip=tooltip) + + def Update(self, value=None, disabled=None): + location = EncodeRadioRowCol(self.Position[0], self.Position[1]) + if value is not None: + try: + self.TKIntVar.set(location) + except: pass + self.InitialState = value + if disabled == True: + self.TKRadio['state'] = 'disabled' + elif disabled == False: + self.TKRadio['state'] = 'normal' + + def __del__(self): + try: + self.TKRadio.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + +# ---------------------------------------------------------------------- # +# Checkbox # +# ---------------------------------------------------------------------- # +class Checkbox(Element): + def __init__(self, text, default=False, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Check Box Element + :param text: + :param default: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + :param font: + ''' + self.Text = text + self.InitialState = default + self.Value = None + self.TKCheckbutton = None + self.TextColor = text_color if text_color else DEFAULT_TEXT_COLOR + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_CHECKBOX, size=size, auto_size_text=auto_size_text, font=font, + background_color=background_color, text_color=self.TextColor, key=key, pad=pad, tooltip=tooltip) + + def Get(self): + return self.TKIntVar.get() + + def Update(self, value=None, disabled=None): + if value is not None: + try: + self.TKIntVar.set(value) + self.InitialState = value + except: pass + if disabled == True: + self.TKCheckbutton.configure(state='disabled') + elif disabled == False: + self.TKCheckbutton.configure(state='normal') + + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + +# ------------------------- CHECKBOX Element lazy functions ------------------------- # +CB = Checkbox +CBox = Checkbox +Check = Checkbox + + +# ---------------------------------------------------------------------- # +# Spin # +# ---------------------------------------------------------------------- # + +class Spin(Element): + # Values = None + # TKSpinBox = None + def __init__(self, values, initial_value=None, change_submits=False, size=(None, None), auto_size_text=None, font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Spin Box Element + :param values: + :param initial_value: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + :param font: + ''' + self.Values = values + self.DefaultValue = initial_value + self.ChangeSubmits = change_submits + self.TKSpinBox = None + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_SPIN, size, auto_size_text, font=font,background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + return + + def Update(self, value=None, values=None, disabled=None): + if values != None: + old_value = self.TKStringVar.get() + self.Values = values + self.TKSpinBox.configure(values=values) + self.TKStringVar.set(old_value) + if value is not None: + try: + self.TKStringVar.set(value) + except: pass + self.DefaultValue = value + if disabled == True: + self.TKSpinBox.configure(state='disabled') + elif disabled == False: + self.TKSpinBox.configure(state='normal') + + + def SpinChangedHandler(self, event): + # first, get the results table built + # modify the Results table in the parent FlexForm object + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def __del__(self): + try: + self.TKSpinBox.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + +# ---------------------------------------------------------------------- # +# Multiline # +# ---------------------------------------------------------------------- # +class Multiline(Element): + def __init__(self, default_text='', enter_submits = False, autoscroll=False, size=(None, None), auto_size_text=None, background_color=None, text_color=None, do_not_clear=False, key=None, focus=False, pad=None, tooltip=None): + ''' + Input Multi-line Element + :param default_text: + :param enter_submits: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param background_color: Color for Element. Text or RGB Hex + ''' + self.DefaultText = default_text + self.EnterSubmits = enter_submits + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + self.Focus = focus + self.do_not_clear = do_not_clear + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + self.Autoscroll = autoscroll + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_MULTILINE, size=size, auto_size_text=auto_size_text, background_color=bg, text_color=fg, key=key, pad=pad, tooltip=tooltip) + return + + def Update(self, value=None, disabled=None, append=False): + if value is not None: + try: + if not append: + self.TKText.delete('1.0', tk.END) + self.TKText.insert(tk.END, value) + except: pass + self.DefaultText = value + if self.Autoscroll: + self.TKText.see(tk.END) + if disabled == True: + self.TKText.configure(state='disabled') + elif disabled == False: + self.TKText.configure(state='normal') + + def Get(self): + return self.TKText.get(1.0, tk.END) + + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + +# ---------------------------------------------------------------------- # +# Text # +# ---------------------------------------------------------------------- # +class Text(Element): + def __init__(self, text, size=(None, None), auto_size_text=None, click_submits=None, relief=None, font=None, text_color=None, background_color=None,justification=None, pad=None, key=None, tooltip=None): + ''' + Text Element - Displays text in your form. Can be updated in non-blocking forms + :param text: The text to display + :param size: Size of Element in Characters + :param auto_size_text: True if the field should shrink to fit the text + :param font: Font name and size ("name", size) + :param text_color: Text Color name or RGB hex value '#RRGGBB' + :param background_color: Background color for text (name or RGB Hex) + :param justification: 'left', 'right', 'center' + ''' + self.DisplayText = text + self.TextColor = text_color if text_color else DEFAULT_TEXT_COLOR + self.Justification = justification + self.Relief = relief + self.ClickSubmits = click_submits + if background_color is None: + bg = DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR + else: + bg = background_color + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_TEXT, size, auto_size_text, background_color=bg, font=font if font else DEFAULT_FONT, text_color=self.TextColor, pad=pad, key=key, tooltip=tooltip) + return + + def Update(self, value = None, background_color=None, text_color=None, font=None): + if value is not None: + self.DisplayText=value + stringvar = self.TKStringVar + stringvar.set(value) + if background_color is not None: + self.TKText.configure(background=background_color) + if text_color is not None: + self.TKText.configure(fg=text_color) + if font is not None: + self.TKText.configure(font=font) + + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + +# ------------------------- Text Element lazy functions ------------------------- # +Txt = Text +T = Text + + +# ---------------------------------------------------------------------- # +# TKProgressBar # +# Emulate the TK ProgressBar using canvas and rectangles +# ---------------------------------------------------------------------- # + +class TKProgressBar(): + def __init__(self, root, max, length=400, width=DEFAULT_PROGRESS_BAR_SIZE[1], style=DEFAULT_PROGRESS_BAR_STYLE, relief=DEFAULT_PROGRESS_BAR_RELIEF, border_width=DEFAULT_PROGRESS_BAR_BORDER_WIDTH, orientation='horizontal', BarColor=(None,None)): + self.Length = length + self.Width = width + self.Max = max + self.Orientation = orientation + self.Count = None + self.PriorCount = 0 + + if orientation[0].lower() == 'h': + s = ttk.Style() + s.theme_use(style) + if BarColor != COLOR_SYSTEM_DEFAULT: + s.configure(str(length)+str(width)+"my.Horizontal.TProgressbar", background=BarColor[0], troughcolor=BarColor[1], troughrelief=relief, borderwidth=border_width, thickness=width) + else: + s.configure(str(length)+str(width)+"my.Horizontal.TProgressbar", troughrelief=relief, borderwidth=border_width, thickness=width) + + self.TKProgressBarForReal = ttk.Progressbar(root, maximum=self.Max, style=str(length)+str(width)+'my.Horizontal.TProgressbar', length=length, orient=tk.HORIZONTAL, mode='determinate') + else: + s = ttk.Style() + s.theme_use(style) + if BarColor != COLOR_SYSTEM_DEFAULT: + s.configure(str(length)+str(width)+"my.Vertical.TProgressbar", background=BarColor[0], troughcolor=BarColor[1], troughrelief=relief, borderwidth=border_width, thickness=width) + else: + s.configure(str(length)+str(width)+"my.Vertical.TProgressbar", troughrelief=relief, borderwidth=border_width, thickness=width) + self.TKProgressBarForReal = ttk.Progressbar(root, maximum=self.Max, style=str(length)+str(width)+'my.Vertical.TProgressbar', length=length, orient=tk.VERTICAL, mode='determinate') + + def Update(self, count=None, max=None): + if max is not None: + self.Max = max + try: + self.TKProgressBarForReal.config(maximum=max) + except: + return False + if count is not None and count > self.Max: return False + if count is not None: + try: + self.TKProgressBarForReal['value'] = count + except: return False + return True + + def __del__(self): + try: + self.TKProgressBarForReal.__del__() + except: + pass + +# ---------------------------------------------------------------------- # +# TKOutput # +# New Type of TK Widget that's a Text Widget in disguise # +# Note that it's inherited from the TKFrame class so that the # +# Scroll bar will span the length of the frame # +# ---------------------------------------------------------------------- # +class TKOutput(tk.Frame): + def __init__(self, parent, width, height, bd, background_color=None, text_color=None, font=None, pad=None): + frame = tk.Frame(parent) + tk.Frame.__init__(self, frame) + self.output = tk.Text(frame, width=width, height=height, bd=bd, font=font) + if background_color and background_color != COLOR_SYSTEM_DEFAULT: + self.output.configure(background=background_color) + frame.configure(background=background_color) + if text_color and text_color != COLOR_SYSTEM_DEFAULT: + self.output.configure(fg=text_color) + self.vsb = tk.Scrollbar(frame, orient="vertical", command=self.output.yview) + self.output.configure(yscrollcommand=self.vsb.set) + self.output.pack(side="left", fill="both", expand=True) + self.vsb.pack(side="left", fill="y", expand=False) + frame.pack(side="left", padx=pad[0], pady=pad[1], expand=True, fill='y') + self.previous_stdout = sys.stdout + self.previous_stderr = sys.stderr + + sys.stdout = self + sys.stderr = self + self.pack() + + def write(self, txt): + try: + self.output.insert(tk.END, str(txt)) + self.output.see(tk.END) + except: + pass + + def Close(self): + sys.stdout = self.previous_stdout + sys.stderr = self.previous_stderr + + def flush(self): + sys.stdout = self.previous_stdout + sys.stderr = self.previous_stderr + + def __del__(self): + sys.stdout = self.previous_stdout + sys.stderr = self.previous_stderr + +# ---------------------------------------------------------------------- # +# Output # +# Routes stdout, stderr to a scrolled window # +# ---------------------------------------------------------------------- # +class Output(Element): + def __init__(self, size=(None, None), background_color=None, text_color=None, pad=None, font=None, tooltip=None, key=None): + ''' + Output Element - reroutes stdout, stderr to this window + :param size: Size of field in characters + :param background_color: Color for Element. Text or RGB Hex + ''' + self.TKOut = None + bg = background_color if background_color else DEFAULT_INPUT_ELEMENTS_COLOR + fg = text_color if text_color is not None else DEFAULT_INPUT_TEXT_COLOR + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_OUTPUT, size=size, background_color=bg, text_color=fg, pad=pad, font=font, tooltip=tooltip, key=key) + + def __del__(self): + try: + self.TKOut.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + +# ---------------------------------------------------------------------- # +# Button Class # +# ---------------------------------------------------------------------- # +class Button(Element): + def __init__(self, button_text='', button_type=BUTTON_TYPE_CLOSES_WIN, target=(None, None), tooltip=None, file_types=(("ALL Files", "*.*"),), initial_folder=None, image_filename=None, image_size=(None, None), image_subsample=None, border_width=None, size=(None, None), auto_size_button=None, button_color=None, default_value = None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + ''' + Button Element - Specifies all types of buttons + :param button_type: + :param target: + :param button_text: + :param file_types: + :param image_filename: + :param image_size: + :param image_subsample: + :param border_width: + :param size: Size of field in characters + :param auto_size_button: + :param button_color: + :param font: + ''' + self.AutoSizeButton = auto_size_button + self.BType = button_type + self.FileTypes = file_types + self.TKButton = None + self.Target = target + self.ButtonText = button_text + self.ButtonColor = button_color if button_color else DEFAULT_BUTTON_COLOR + self.ImageFilename = image_filename + self.ImageSize = image_size + self.ImageSubsample = image_subsample + self.UserData = None + self.BorderWidth = border_width if border_width is not None else DEFAULT_BORDER_WIDTH + self.BindReturnKey = bind_return_key + self.Focus = focus + self.TKCal = None + self.DefaultValue = default_value + self.InitialFolder = initial_folder + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_BUTTON, size=size, font=font, pad=pad, key=key, tooltip=tooltip) + return + + # Realtime button release callback + def ButtonReleaseCallBack(self, parm): + self.LastButtonClickedWasRealtime = False + self.ParentForm.LastButtonClicked = None + + # Realtime button callback + def ButtonPressCallBack(self, parm): + self.ParentForm.LastButtonClickedWasRealtime = True + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.ButtonText + + # ------- Button Callback ------- # + def ButtonCallBack(self): + global _my_windows + # print(f'Parent = {self.ParentForm} Position = {self.Position}') + # Buttons modify targets or return from the form + # If modifying target, get the element object at the target and modify its StrVar + target = self.Target + target_element = None + if target[0] == ThisRow: + target = [self.Position[0], target[1]] + if target[1] < 0: + target[1] = self.Position[1] + target[1] + strvar = None + if target == (None, None): + strvar = self.TKStringVar + else: + if not isinstance(target, str): + if target[0] < 0: + target = [self.Position[0] + target[0], target[1]] + target_element = self.ParentContainer._GetElementAtLocation(target) + else: + target_element = self.ParentForm.FindElement(target) + try: + strvar = target_element.TKStringVar + except: pass + filetypes = [] if self.FileTypes is None else self.FileTypes + if self.BType == BUTTON_TYPE_BROWSE_FOLDER: + folder_name = tkFileDialog.askdirectory(initialdir=self.InitialFolder) # show the 'get folder' dialog box + if folder_name != '': + try: + strvar.set(folder_name) + self.TKStringVar.set(folder_name) + except: pass + elif self.BType == BUTTON_TYPE_BROWSE_FILE: + file_name = tkFileDialog.askopenfilename(filetypes=filetypes, initialdir=self.InitialFolder) # show the 'get file' dialog box + if file_name != '': + strvar.set(file_name) + self.TKStringVar.set(file_name) + elif self.BType == BUTTON_TYPE_COLOR_CHOOSER: + color = tkColorChooser.askcolor() # show the 'get file' dialog box + color = color[1] # save only the #RRGGBB portion + strvar.set(color) + self.TKStringVar.set(color) + elif self.BType == BUTTON_TYPE_BROWSE_FILES: + file_name = tkFileDialog.askopenfilenames(filetypes=filetypes, initialdir=self.InitialFolder) + if file_name != '': + file_name = ';'.join(file_name) + strvar.set(file_name) + self.TKStringVar.set(file_name) + elif self.BType == BUTTON_TYPE_SAVEAS_FILE: + file_name = tkFileDialog.asksaveasfilename(filetypes=filetypes, initialdir=self.InitialFolder) # show the 'get file' dialog box + if file_name != '': + strvar.set(file_name) + self.TKStringVar.set(file_name) + elif self.BType == BUTTON_TYPE_CLOSES_WIN: # this is a return type button so GET RESULTS and destroy window + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.ButtonText + self.ParentForm.FormRemainedOpen = False + # if the form is tabbed, must collect all form's results and destroy all forms + if self.ParentForm.IsTabbedForm: + self.ParentForm.UberParent._Close() + else: + self.ParentForm._Close() + self.ParentForm.TKroot.quit() + if self.ParentForm.NonBlocking: + self.ParentForm.TKroot.destroy() + _my_windows.Decrement() + elif self.BType == BUTTON_TYPE_READ_FORM: # LEAVE THE WINDOW OPEN!! DO NOT CLOSE + # first, get the results table built + # modify the Results table in the parent FlexForm object + if self.Key is not None: + self.ParentForm.LastButtonClicked = self.Key + else: + self.ParentForm.LastButtonClicked = self.ButtonText + self.ParentForm.FormRemainedOpen = True + if self.ParentForm.IsTabbedForm: + self.ParentForm.UberParent.FormStayedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + elif self.BType == BUTTON_TYPE_CLOSES_WIN_ONLY: # this is a return type button so GET RESULTS and destroy window + # if the form is tabbed, must collect all form's results and destroy all forms + if self.ParentForm.IsTabbedForm: + self.ParentForm.UberParent._Close() + else: + self.ParentForm._Close() + if self.ParentForm.NonBlocking: + self.ParentForm.TKroot.destroy() + _my_windows.Decrement() + elif self.BType == BUTTON_TYPE_CALENDAR_CHOOSER: # this is a return type button so GET RESULTS and destroy window + root = tk.Toplevel() + root.title('Calendar Chooser') + self.TKCal = TKCalendar(master=root, firstweekday=calendar.SUNDAY, target_element=target_element) + self.TKCal.pack(expand=1, fill='both') + # self.ParentForm.TKRroot.mainloop() + root.update() + # root.mainloop() + # root.update() + # strvar.set(ttkcal.selection) + + return + + def Update(self, value=None, text=None, button_color=(None, None), disabled=None): + try: + if text is not None: + self.TKButton.configure(text=text) + self.ButtonText = text + if button_color != (None, None): + self.TKButton.config(foreground=button_color[0], background=button_color[1]) + except: + return + if value is not None: + self.DefaultValue = value + if disabled == True: + self.TKButton['state'] = 'disabled' + elif disabled == False: + self.TKButton['state'] = 'normal' + + def GetText(self): + return self.ButtonText + + def __del__(self): + try: + self.TKButton.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + + +# ---------------------------------------------------------------------- # +# ProgreessBar # +# ---------------------------------------------------------------------- # +class ProgressBar(Element): + def __init__(self, max_value, orientation=None, size=(None, None), auto_size_text=None, bar_color=(None, None), style=None, border_width=None, relief=None, key=None, pad=None): + ''' + Progress Bar Element + :param max_value: + :param orientation: + :param size: Size of field in characters + :param auto_size_text: True if should shrink field to fit the default text + :param bar_color: + :param style: + :param border_width: + :param relief: + ''' + self.MaxValue = max_value + self.TKProgressBar = None + self.Cancelled = False + self.NotRunning = True + self.Orientation = orientation if orientation else DEFAULT_METER_ORIENTATION + self.BarColor = bar_color + self.BarStyle = style if style else DEFAULT_PROGRESS_BAR_STYLE + self.BorderWidth = border_width if border_width else DEFAULT_PROGRESS_BAR_BORDER_WIDTH + self.Relief = relief if relief else DEFAULT_PROGRESS_BAR_RELIEF + self.BarExpired = False + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_PROGRESS_BAR, size=size, auto_size_text=auto_size_text, key=key, pad=pad) + return + + # returns False if update failed + def UpdateBar(self, current_count, max=None): + if self.ParentForm.TKrootDestroyed: + return False + self.TKProgressBar.Update(current_count, max=max) + try: + self.ParentForm.TKroot.update() + except: + _my_windows.Decrement() + return False + return True + + def __del__(self): + try: + self.TKProgressBar.__del__() + except: + pass + super(*(fSuprArgs(self))).__del__() + +# ---------------------------------------------------------------------- # +# Image # +# ---------------------------------------------------------------------- # +class Image(Element): + def __init__(self, filename=None, data=None, size=(None, None), pad=None, key=None, tooltip=None): + ''' + Image Element + :param filename: + :param size: Size of field in characters + ''' + self.Filename = filename + self.Data = data + self.tktext_label = None + if data is None and filename is None: + print('* Warning... no image specified in Image Element! *') + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_IMAGE, size=size, pad=pad, key=key, tooltip=tooltip) + return + + def Update(self, filename=None, data=None): + if filename is not None: + image = tk.PhotoImage(file=filename) + elif data is not None: + if type(data) is bytes: + image = tk.PhotoImage(data=data) + else: + image = data + else: return + width, height = image.width(), image.height() + self.tktext_label.configure(image=image, width=width, height=height) + # self.tktext_label.configure(image=image) + self.tktext_label.image = image + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + +# ---------------------------------------------------------------------- # +# Canvas # +# ---------------------------------------------------------------------- # +class Canvas(Element): + def __init__(self, canvas=None, background_color=None, size=(None, None), pad=None, key=None, tooltip=None): + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + self._TKCanvas = canvas + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_CANVAS, background_color=background_color, size=size, pad=pad, key=key, tooltip=tooltip) + return + + @property + def TKCanvas(self): + if self._TKCanvas is None: + print('*** Did you forget to call Finalize()? Your code should look something like: ***') + print('*** form = sg.Window("My Form").Layout(layout).Finalize() ***') + return self._TKCanvas + + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + + + +# ---------------------------------------------------------------------- # +# Graph # +# ---------------------------------------------------------------------- # +class Graph(Element): + def __init__(self, canvas_size, graph_bottom_left, graph_top_right, background_color=None, pad=None, key=None, tooltip=None): + + self.CanvasSize = canvas_size + self.BottomLeft = graph_bottom_left + self.TopRight = graph_top_right + self._TKCanvas = None + self._TKCanvas2 = None + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_GRAPH, background_color=background_color, size=canvas_size, pad=pad, key=key, tooltip=tooltip) + return + + def _convert_xy_to_canvas_xy(self, x_in, y_in): + scale_x = (self.CanvasSize[0] - 0) / (self.TopRight[0] - self.BottomLeft[0]) + scale_y = (0 - self.CanvasSize[1]) / (self.TopRight[1] - self.BottomLeft[1]) + new_x = 0 + scale_x * (x_in - self.BottomLeft[0]) + new_y = self.CanvasSize[1] + scale_y * (y_in - self.BottomLeft[1]) + return new_x, new_y + + def DrawLine(self, point_from, point_to, color='black', width=1): + converted_point_from = self._convert_xy_to_canvas_xy(point_from[0], point_from[1]) + converted_point_to = self._convert_xy_to_canvas_xy(point_to[0], point_to[1]) + return self._TKCanvas2.create_line(converted_point_from, converted_point_to, width=width, fill=color) + + def DrawPoint(self, point, size=2, color='black'): + converted_point = self._convert_xy_to_canvas_xy(point[0], point[1]) + return self._TKCanvas2.create_oval(converted_point[0]-size, converted_point[1]-size, converted_point[0]+size, converted_point[1]+size, fill=color, outline=color ) + + def DrawCircle(self, center_location, radius, fill_color=None, line_color='black'): + converted_point = self._convert_xy_to_canvas_xy(center_location[0], center_location[1]) + return self._TKCanvas2.create_oval(converted_point[0]-radius, converted_point[1]-radius, converted_point[0]+radius, converted_point[1]+radius, fill=fill_color, outline=line_color) + + def DrawOval(self, top_left, bottom_right, fill_color=None, line_color=None): + converted_top_left = self._convert_xy_to_canvas_xy(top_left[0], top_left[1]) + converted_bottom_right = self._convert_xy_to_canvas_xy(bottom_right[0],bottom_right[1]) + return self._TKCanvas2.create_oval(converted_top_left[0], converted_top_left[1], converted_bottom_right[0], converted_bottom_right[1], fill=fill_color, outline=line_color) + + + def DrawRectangle(self, top_left, bottom_right, fill_color=None, line_color=None): + converted_top_left = self._convert_xy_to_canvas_xy(top_left[0], top_left[1] ) + converted_bottom_right = self._convert_xy_to_canvas_xy(bottom_right[0], bottom_right[1]) + return self._TKCanvas2.create_rectangle(converted_top_left[0], converted_top_left[1], converted_bottom_right[0], converted_bottom_right[1], fill=fill_color, outline=line_color) + + + + def DrawText(self, text, location, color='black', font=None): + converted_point = self._convert_xy_to_canvas_xy(location[0], location[1]) + return self._TKCanvas2.create_text(converted_point[0], converted_point[1], text=text, font=font, fill=color) + + + def Erase(self): + self._TKCanvas2.delete('all') + + def Update(self, background_color): + self._TKCanvas2.configure(background=background_color) + + def Move(self, x_direction, y_direction): + zero_converted = self._convert_xy_to_canvas_xy(0,0) + shift_converted = self._convert_xy_to_canvas_xy(x_direction, y_direction) + shift_amount = (shift_converted[0]-zero_converted[0], shift_converted[1]-zero_converted[1]) + self._TKCanvas2.move('all', shift_amount[0], shift_amount[1]) + + def MoveFigure(self, figure, x_direction, y_direction): + zero_converted = self._convert_xy_to_canvas_xy(0,0) + shift_converted = self._convert_xy_to_canvas_xy(x_direction, y_direction) + shift_amount = (shift_converted[0]-zero_converted[0], shift_converted[1]-zero_converted[1]) + self._TKCanvas2.move(figure, shift_amount[0], shift_amount[1]) + + @property + def TKCanvas(self): + if self._TKCanvas2 is None: + print('*** Did you forget to call Finalize()? Your code should look something like: ***') + print('*** form = sg.Window("My Form").Layout(layout).Finalize() ***') + return self._TKCanvas2 + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + +# ---------------------------------------------------------------------- # +# Frame # +# ---------------------------------------------------------------------- # +class Frame(Element): + def __init__(self, title, layout, title_color=None, background_color=None, title_location=None , relief=DEFAULT_FRAME_RELIEF, size=(None, None), font=None, pad=None, border_width=None, key=None, tooltip=None): + + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + # self.ParentForm = None + self.TKFrame = None + self.Title = title + self.Relief = relief + self.TitleLocation = title_location + self.BorderWidth = border_width + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + + self.Layout(layout) + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_FRAME, background_color=background_color, text_color=title_color, size=size, font=font, pad=pad, key=key, tooltip=tooltip) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + super(*(fSuprArgs(self))).__del__() + + + +# ---------------------------------------------------------------------- # +# Tab # +# ---------------------------------------------------------------------- # +class Tab(Element): + def __init__(self, title, layout, title_color=None, background_color=None, font=None, pad=None, border_width=None, key=None, tooltip=None): + + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + self.TKFrame = None + self.Title = title + self.BorderWidth = border_width + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + + self.Layout(layout) + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_TAB, background_color=background_color, text_color=title_color, font=font, pad=pad, key=key, tooltip=tooltip) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + super(*(fSuprArgs(self))).__del__() + + + +# ---------------------------------------------------------------------- # +# TabGroup # +# ---------------------------------------------------------------------- # +class TabGroup(Element): + def __init__(self, layout, title_color=None, background_color=None, font=None, pad=None, border_width=None, key=None, tooltip=None): + + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + self.TKNotebook = None + self.BorderWidth = border_width + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + + self.Layout(layout) + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_TAB_GROUP, background_color=background_color, text_color=title_color, font=font, pad=pad, key=key, tooltip=tooltip) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + super(*(fSuprArgs(self))).__del__() + + + + +# ---------------------------------------------------------------------- # +# Slider # +# ---------------------------------------------------------------------- # +class Slider(Element): + def __init__(self, range=(None,None), default_value=None, resolution=None, orientation=None, border_width=None, relief=None, change_submits=False, size=(None, None), font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None): + ''' + Slider + :param range: + :param default_value: + :param resolution: + :param orientation: + :param border_width: + :param relief: + :param change_submits: + :param scale: + :param size: + :param font: + :param background_color: + :param text_color: + :param key: + :param pad: + ''' + self.TKScale = None + self.Range = (1,10) if range == (None, None) else range + self.DefaultValue = self.Range[0] if default_value is None else default_value + self.Orientation = orientation if orientation else DEFAULT_SLIDER_ORIENTATION + self.BorderWidth = border_width if border_width else DEFAULT_SLIDER_BORDER_WIDTH + self.Relief = relief if relief else DEFAULT_SLIDER_RELIEF + self.Resolution = 1 if resolution is None else resolution + self.ChangeSubmits = change_submits + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_INPUT_SLIDER, size=size, font=font, background_color=background_color, text_color=text_color, key=key, pad=pad, tooltip=tooltip) + return + + def Update(self, value=None, range=(None, None), disabled=None): + if value is not None: + try: + self.TKIntVar.set(value) + if range != (None, None): + self.TKScale.config(from_ = range[0], to_ = range[1]) + except: pass + self.DefaultValue = value + if disabled == True: + self.TKScale['state'] = 'disabled' + elif disabled == False: + self.TKScale['state'] = 'normal' + + def SliderChangedHandler(self, event): + # first, get the results table built + # modify the Results table in the parent FlexForm object + self.ParentForm.LastButtonClicked = '' + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + +# ---------------------------------------------------------------------- # +# TkScrollableFrame (Used by Column) # +# ---------------------------------------------------------------------- # +class TkScrollableFrame(tk.Frame): + def __init__(self, master, **kwargs): + tk.Frame.__init__(self, master, **kwargs) + + # create a canvas object and a vertical scrollbar for scrolling it + self.vscrollbar = tk.Scrollbar(self, orient=tk.VERTICAL) + self.vscrollbar.pack(side='right', fill="y", expand="false") + + self.hscrollbar = tk.Scrollbar(self, orient=tk.HORIZONTAL) + self.hscrollbar.pack(side='bottom', fill="x", expand="false") + + self.canvas = tk.Canvas(self, yscrollcommand=self.vscrollbar.set, xscrollcommand=self.hscrollbar.set) + self.canvas.pack(side="left", fill="both", expand=True) + + self.vscrollbar.config(command=self.canvas.yview) + self.hscrollbar.config(command=self.canvas.xview) + + # reset the view + self.canvas.xview_moveto(0) + self.canvas.yview_moveto(0) + + # create a frame inside the canvas which will be scrolled with it + self.TKFrame = tk.Frame(self.canvas, **kwargs) + self.frame_id = self.canvas.create_window(0, 0, window=self.TKFrame, anchor="nw") + self.canvas.config(borderwidth=0, highlightthickness=0) + self.TKFrame.config(borderwidth=0, highlightthickness=0) + self.config(borderwidth=0, highlightthickness=0) + + self.bind('', self.set_scrollregion) + + self.bind_mouse_scroll(self.canvas, self.yscroll) + self.bind_mouse_scroll(self.hscrollbar, self.xscroll) + self.bind_mouse_scroll(self.vscrollbar, self.yscroll) + + def resize_frame(self, e): + self.canvas.itemconfig(self.frame_id, height=e.height, width=e.width) + + def yscroll(self, event): + if event.num == 5 or event.delta < 0: + self.canvas.yview_scroll(1, "unit") + elif event.num == 4 or event.delta > 0: + self.canvas.yview_scroll(-1, "unit") + + def xscroll(self, event): + if event.num == 5 or event.delta < 0: + self.canvas.xview_scroll(1, "unit") + elif event.num == 4 or event.delta > 0: + self.canvas.xview_scroll(-1, "unit") + + def bind_mouse_scroll(self, parent, mode): + # ~~ Windows only + parent.bind("", mode) + # ~~ Unix only + parent.bind("", mode) + parent.bind("", mode) + + def set_scrollregion(self, event=None): + """ Set the scroll region on the canvas""" + self.canvas.configure(scrollregion=self.canvas.bbox('all')) + + +# ---------------------------------------------------------------------- # +# Column # +# ---------------------------------------------------------------------- # +class Column(Element): + def __init__(self, layout, background_color = None, size=(None, None), pad=None, scrollable=False, key=None): + self.UseDictionary = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.ParentWindow = None + self.Rows = [] + # self.ParentForm = None + self.TKFrame = None + self.Scrollable = scrollable + bg = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + + self.Layout(layout) + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_COLUMN, background_color=background_color, size=size, pad=pad, key=key) + return + + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + if element.Key is not None: + self.UseDictionary = True + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + def Layout(self, rows): + for row in rows: + self.AddRow(*row) + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + try: + del(self.TKFrame) + except: + pass + super(*(fSuprArgs(self))).__del__() + + +# ---------------------------------------------------------------------- # +# Calendar # +# ---------------------------------------------------------------------- # +class TKCalendar(ttk.Frame): + """ + This code was shamelessly lifted from moshekaplan's repository - moshekaplan/tkinter_components + """ + # XXX ToDo: cget and configure + + datetime = calendar.datetime.datetime + timedelta = calendar.datetime.timedelta + + def __init__(self, master=None, target_element=None, **kw): + """ + WIDGET-SPECIFIC OPTIONS + + locale, firstweekday, year, month, selectbackground, + selectforeground + """ + self._TargetElement = target_element + # remove custom options from kw before initializating ttk.Frame + fwday = kw.pop('firstweekday', calendar.MONDAY) + year = kw.pop('year', self.datetime.now().year) + month = kw.pop('month', self.datetime.now().month) + locale = kw.pop('locale', None) + sel_bg = kw.pop('selectbackground', '#ecffc4') + sel_fg = kw.pop('selectforeground', '#05640e') + + self._date = self.datetime(year, month, 1) + self._selection = None # no date selected + ttk.Frame.__init__(self, master, **kw) + + # instantiate proper calendar class + if locale is None: + self._cal = calendar.TextCalendar(fwday) + else: + self._cal = calendar.LocaleTextCalendar(fwday, locale) + + self.__setup_styles() # creates custom styles + self.__place_widgets() # pack/grid used widgets + self.__config_calendar() # adjust calendar columns and setup tags + # configure a canvas, and proper bindings, for selecting dates + self.__setup_selection(sel_bg, sel_fg) + + # store items ids, used for insertion later + self._items = [self._calendar.insert('', 'end', values='') + for _ in range(6)] + # insert dates in the currently empty calendar + self._build_calendar() + + def __setitem__(self, item, value): + if item in ('year', 'month'): + raise AttributeError("attribute '%s' is not writeable" % item) + elif item == 'selectbackground': + self._canvas['background'] = value + elif item == 'selectforeground': + self._canvas.itemconfigure(self._canvas.text, item=value) + else: + ttk.Frame.__setitem__(self, item, value) + + def __getitem__(self, item): + if item in ('year', 'month'): + return getattr(self._date, item) + elif item == 'selectbackground': + return self._canvas['background'] + elif item == 'selectforeground': + return self._canvas.itemcget(self._canvas.text, 'fill') + else: + r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)}) + return r[item] + + def __setup_styles(self): + # custom ttk styles + style = ttk.Style(self.master) + arrow_layout = lambda dir: ( + [('Button.focus', {'children': [('Button.%sarrow' % dir, None)]})] + ) + style.layout('L.TButton', arrow_layout('left')) + style.layout('R.TButton', arrow_layout('right')) + + def __place_widgets(self): + # header frame and its widgets + hframe = ttk.Frame(self) + lbtn = ttk.Button(hframe, style='L.TButton', command=self._prev_month) + rbtn = ttk.Button(hframe, style='R.TButton', command=self._next_month) + self._header = ttk.Label(hframe, width=15, anchor='center') + # the calendar + self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7) + + # pack the widgets + hframe.pack(in_=self, side='top', pady=4, anchor='center') + lbtn.grid(in_=hframe) + self._header.grid(in_=hframe, column=1, row=0, padx=12) + rbtn.grid(in_=hframe, column=2, row=0) + self._calendar.pack(in_=self, expand=1, fill='both', side='bottom') + + def __config_calendar(self): + cols = self._cal.formatweekheader(3).split() + self._calendar['columns'] = cols + self._calendar.tag_configure('header', background='grey90') + self._calendar.insert('', 'end', values=cols, tag='header') + # adjust its columns width + font = tkFont.Font() + maxwidth = max(font.measure(col) for col in cols) + for col in cols: + self._calendar.column(col, width=maxwidth, minwidth=maxwidth, + anchor='e') + + def __setup_selection(self, sel_bg, sel_fg): + self._font = tkFont.Font() + self._canvas = canvas = tk.Canvas(self._calendar, + background=sel_bg, borderwidth=0, highlightthickness=0) + canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='w') + + canvas.bind('', lambda evt: canvas.place_forget()) + self._calendar.bind('', lambda evt: canvas.place_forget()) + self._calendar.bind('', self._pressed) + + def __minsize(self, evt): + width, height = self._calendar.master.geometry().split('x') + height = height[:height.index('+')] + self._calendar.master.minsize(width, height) + + def _build_calendar(self): + year, month = self._date.year, self._date.month + + # update header text (Month, YEAR) + header = self._cal.formatmonthname(year, month, 0) + self._header['text'] = header.title() + + # update calendar shown dates + cal = self._cal.monthdayscalendar(year, month) + for indx, item in enumerate(self._items): + week = cal[indx] if indx < len(cal) else [] + fmt_week = [('%02d' % day) if day else '' for day in week] + self._calendar.item(item, values=fmt_week) + + def _show_selection(self, text, bbox): + """Configure canvas for a new selection.""" + x, y, width, height = bbox + + textw = self._font.measure(text) + + canvas = self._canvas + canvas.configure(width=width, height=height) + canvas.coords(canvas.text, width - textw, height / 2 - 1) + canvas.itemconfigure(canvas.text, text=text) + canvas.place(in_=self._calendar, x=x, y=y) + + # Callbacks + + def _pressed(self, evt): + """Clicked somewhere in the calendar.""" + x, y, widget = evt.x, evt.y, evt.widget + item = widget.identify_row(y) + column = widget.identify_column(x) + + if not column or not item in self._items: + # clicked in the weekdays row or just outside the columns + return + + item_values = widget.item(item)['values'] + if not len(item_values): # row is empty for this month + return + + text = item_values[int(column[1]) - 1] + if not text: # date is empty + return + + bbox = widget.bbox(item, column) + if not bbox: # calendar not visible yet + return + + # update and then show selection + text = '%02d' % text + self._selection = (text, item, column) + self._show_selection(text, bbox) + year, month = self._date.year, self._date.month + try: + self._TargetElement.Update(self.datetime(year, month, int(self._selection[0]))) + except: pass + + def _prev_month(self): + """Updated calendar to show the previous month.""" + self._canvas.place_forget() + + self._date = self._date - self.timedelta(days=1) + self._date = self.datetime(self._date.year, self._date.month, 1) + self._build_calendar() # reconstuct calendar + + def _next_month(self): + """Update calendar to show the next month.""" + self._canvas.place_forget() + + year, month = self._date.year, self._date.month + self._date = self._date + self.timedelta( + days=calendar.monthrange(year, month)[1] + 1) + self._date = self.datetime(self._date.year, self._date.month, 1) + self._build_calendar() # reconstruct calendar + + # Properties + + @property + def selection(self): + """Return a datetime representing the current selected date.""" + if not self._selection: + return None + + year, month = self._date.year, self._date.month + return self.datetime(year, month, int(self._selection[0])) + + +# ---------------------------------------------------------------------- # +# Canvas # +# ---------------------------------------------------------------------- # +class Menu(Element): + def __init__(self, menu_definition, background_color=None, size=(None, None), tearoff=True, pad=None, key=None): + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + self.MenuDefinition = menu_definition + self.TKMenu = None + self.Tearoff = tearoff + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_MENUBAR, background_color=background_color, size=size, pad=pad, key=key) + return + + def MenuItemChosenCallback(self, item_chosen): + # print('IN MENU ITEM CALLBACK', item_chosen) + self.ParentForm.LastButtonClicked = item_chosen + self.ParentForm.FormRemainedOpen = True + self.ParentForm.TKroot.quit() # kick the users out of the mainloop + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + + +# ---------------------------------------------------------------------- # +# Table # +# ---------------------------------------------------------------------- # +class Table(Element): + def __init__(self, values, headings=None, visible_column_map=None, col_widths=None, def_col_width=10, auto_size_columns=True, max_col_width=20, select_mode=None, display_row_numbers=False, scrollable=None, font=None, justification='right', text_color=None, background_color=None, size=(None, None), pad=None, key=None, tooltip=None): + self.Values = values + self.ColumnHeadings = headings + self.ColumnsToDisplay = visible_column_map + self.ColumnWidths = col_widths + self.MaxColumnWidth = max_col_width + self.DefaultColumnWidth = def_col_width + self.AutoSizeColumns = auto_size_columns + self.BackgroundColor = background_color if background_color is not None else DEFAULT_BACKGROUND_COLOR + self.TextColor = text_color + self.Justification = justification + self.Scrollable = scrollable + self.InitialState = None + self.SelectMode = select_mode + self.DisplayRowNumbers = display_row_numbers + self.TKTreeview = None + + super(*(fSuprArgs(self))).__init__(ELEM_TYPE_TABLE, text_color=text_color, background_color=background_color, font=font, size=size, pad=pad, key=key, tooltip=tooltip) + return + + + def __del__(self): + super(*(fSuprArgs(self))).__del__() + + + + + +# ------------------------------------------------------------------------- # +# Window CLASS # +# ------------------------------------------------------------------------- # +class Window: + ''' + Display a user defined for and return the filled in data + ''' + def __init__(self, title, default_element_size=DEFAULT_ELEMENT_SIZE, default_button_element_size = (None, None), auto_size_text=None, auto_size_buttons=None, location=(None, None), button_color=None, font=None, progress_bar_color=(None, None), background_color=None, is_tabbed_form=False, border_depth=None, auto_close=False, auto_close_duration=DEFAULT_AUTOCLOSE_TIME, icon=DEFAULT_WINDOW_ICON, return_keyboard_events=False, use_default_focus=True, text_justification=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False): + self.AutoSizeText = auto_size_text if auto_size_text is not None else DEFAULT_AUTOSIZE_TEXT + self.AutoSizeButtons = auto_size_buttons if auto_size_buttons is not None else DEFAULT_AUTOSIZE_BUTTONS + self.Title = title + self.Rows = [] # a list of ELEMENTS for this row + self.DefaultElementSize = default_element_size + self.DefaultButtonElementSize = default_button_element_size if default_button_element_size != (None, None) else DEFAULT_BUTTON_ELEMENT_SIZE + self.Location = location + self.ButtonColor = button_color if button_color else DEFAULT_BUTTON_COLOR + self.BackgroundColor = background_color if background_color else DEFAULT_BACKGROUND_COLOR + self.IsTabbedForm = is_tabbed_form + self.ParentWindow = None + self.Font = font if font else DEFAULT_FONT + self.RadioDict = {} + self.BorderDepth = border_depth + self.WindowIcon = icon if icon is not None else _my_windows.user_defined_icon + self.AutoClose = auto_close + self.NonBlocking = False + self.TKroot = None + self.TKrootDestroyed = False + self.FormRemainedOpen = False + self.TKAfterID = None + self.ProgressBarColor = progress_bar_color + self.AutoCloseDuration = auto_close_duration + self.UberParent = None + self.RootNeedsDestroying = False + self.Shown = False + self.ReturnValues = None + self.ReturnValuesList = [] + self.ReturnValuesDictionary = {} + self.DictionaryKeyCounter = 0 + self.LastButtonClicked = None + self.LastButtonClickedWasRealtime = False + self.UseDictionary = False + self.UseDefaultFocus = use_default_focus + self.ReturnKeyboardEvents = return_keyboard_events + self.LastKeyboardEvent = None + self.TextJustification = text_justification + self.NoTitleBar = no_titlebar + self.GrabAnywhere = grab_anywhere + self.KeepOnTop = keep_on_top + + # ------------------------- Add ONE Row to Form ------------------------- # + def AddRow(self, *args): + ''' Parms are a variable number of Elements ''' + NumRows = len(self.Rows) # number of existing rows is our row number + CurrentRowNumber = NumRows # this row's number + CurrentRow = [] # start with a blank row and build up + # ------------------------- Add the elements to a row ------------------------- # + for i, element in enumerate(args): # Loop through list of elements and add them to the row + element.Position = (CurrentRowNumber, i) + element.ParentContainer = self + CurrentRow.append(element) + # ------------------------- Append the row to list of Rows ------------------------- # + self.Rows.append(CurrentRow) + + # ------------------------- Add Multiple Rows to Form ------------------------- # + def AddRows(self,rows): + for row in rows: + self.AddRow(*row) + + def Layout(self,rows): + self.AddRows(rows) + return self + + def LayoutAndRead(self,rows, non_blocking=False): + self.AddRows(rows) + self.Show(non_blocking=non_blocking) + return self.ReturnValues + + def LayoutAndShow(self, rows): + raise DeprecationWarning('LayoutAndShow is no longer supported... change your call to LayoutAndRead') + + # ------------------------- ShowForm THIS IS IT! ------------------------- # + def Show(self, non_blocking=False): + self.Shown = True + # Compute num rows & num cols (it'll come in handy debugging) + self.NumRows = len(self.Rows) + self.NumCols = max(len(row) for row in self.Rows) + self.NonBlocking=non_blocking + + # Search through entire form to see if any elements set the focus + # if not, then will set the focus to the first input element + found_focus = False + for row in self.Rows: + for element in row: + try: + if element.Focus: + found_focus = True + except: + pass + try: + if element.Key is not None: + self.UseDictionary = True + except: + pass + + if not found_focus and self.UseDefaultFocus: + self.UseDefaultFocus = True + else: + self.UseDefaultFocus = False + # -=-=-=-=-=-=-=-=- RUN the GUI -=-=-=-=-=-=-=-=- ## + StartupTK(self) + # If a button or keyboard event happened but no results have been built, build the results + if self.LastKeyboardEvent is not None or self.LastButtonClicked is not None: + return BuildResults(self, False, self) + return self.ReturnValues + + # ------------------------- SetIcon - set the window's fav icon ------------------------- # + def SetIcon(self, icon): + self.WindowIcon = icon + try: + self.TKroot.iconbitmap(icon) + except: pass + + def _GetElementAtLocation(self, location): + (row_num,col_num) = location + row = self.Rows[row_num] + element = row[col_num] + return element + + def _GetDefaultElementSize(self): + return self.DefaultElementSize + + def _AutoCloseAlarmCallback(self): + try: + if self.UberParent: + window = self.UberParent + else: + window = self + if window: + window._Close() + self.TKroot.quit() + self.RootNeedsDestroying = True + except: + pass + + def Read(self): + self.NonBlocking = False + if self.TKrootDestroyed: + return None, None + if not self.Shown: + self.Show() + else: + InitializeResults(self) + self.TKroot.mainloop() + if self.RootNeedsDestroying: + self.TKroot.destroy() + _my_windows.Decrement() + # if form was closed with X + if self.LastButtonClicked is None and self.LastKeyboardEvent is None and self.ReturnValues[0] is None: + _my_windows.Decrement() + if self.LastKeyboardEvent is not None or self.LastButtonClicked is not None: + return BuildResults(self, False, self) + else: + return self.ReturnValues + + def ReadNonBlocking(self, Message=''): + if self.TKrootDestroyed: + return None, None + if not self.Shown: + self.Show(non_blocking=True) + if Message: + print(Message) + try: + rc = self.TKroot.update() + except: + self.TKrootDestroyed = True + _my_windows.Decrement() + # return None, None + return BuildResults(self, False, self) + + + def Finalize(self): + if self.TKrootDestroyed: + return self + if not self.Shown: + self.Show(non_blocking=True) + try: + rc = self.TKroot.update() + except: + self.TKrootDestroyed = True + _my_windows.Decrement() + # return None, None + return self + + + + def Refresh(self): + if self.TKrootDestroyed: + return + try: + rc = self.TKroot.update() + except: + pass + + + def Fill(self, values_dict): + FillFormWithValues(self, values_dict) + + + def FindElement(self, key): + element = _FindElementFromKeyInSubForm(self, key) + if element is None: + print('*** WARNING = FindElement did not find the key. Please check your key\'s spelling ***') + return element + + def SaveToDisk(self, filename): + try: + results = BuildResults(self, False, self) + with open(filename, 'wb') as sf: + pickle.dump(results[1], sf) + except: + print('*** Error saving form to disk ***') + + + def LoadFromDisk(self, filename): + try: + with open(filename, 'rb') as df: + self.Fill(pickle.load(df)) + except: + print('*** Error loading form to disk ***') + + + + def GetScreenDimensions(self): + if self.TKrootDestroyed: + return None, None + screen_width = self.TKroot.winfo_screenwidth() # get window info to move to middle of screen + screen_height = self.TKroot.winfo_screenheight() + return screen_width, screen_height + + + def StartMove(self, event): + try: + self.TKroot.x = event.x + self.TKroot.y = event.y + except: pass + + def StopMove(self, event): + try: + self.TKroot.x = None + self.TKroot.y = None + except: pass + + def OnMotion(self, event): + try: + deltax = event.x - self.TKroot.x + deltay = event.y - self.TKroot.y + x = self.TKroot.winfo_x() + deltax + y = self.TKroot.winfo_y() + deltay + self.TKroot.geometry("+%s+%s" % (x, y)) + except: + pass + + + def _KeyboardCallback(self, event ): + self.LastButtonClicked = None + self.FormRemainedOpen = True + if event.char != '': + self.LastKeyboardEvent = event.char + else: + self.LastKeyboardEvent = str(event.keysym) + ':' + str(event.keycode) + if not self.NonBlocking: + BuildResults(self, False, self) + self.TKroot.quit() + + def _MouseWheelCallback(self, event ): + self.LastButtonClicked = None + self.FormRemainedOpen = True + self.LastKeyboardEvent = 'MouseWheel:Down' if event.delta < 0 else 'MouseWheel:Up' + if not self.NonBlocking: + BuildResults(self, False, self) + self.TKroot.quit() + + + def _Close(self): + try: + self.TKroot.update() + except: pass + if not self.NonBlocking: + BuildResults(self, False, self) + if self.TKrootDestroyed: + return None + self.TKrootDestroyed = True + self.RootNeedsDestroying = True + return None + + def CloseNonBlocking(self): + if self.TKrootDestroyed: + return + try: + self.TKroot.destroy() + _my_windows.Decrement() + except: pass + + CloseNonBlockingForm = CloseNonBlocking + + def OnClosingCallback(self): + return + + def __enter__(self): + return self + + def __exit__(self, *a): + self.__del__() + return False + + def __del__(self): + for row in self.Rows: + for element in row: + element.__del__() + # try: + # del(self.TKroot) + # except: + # pass + +FlexForm = Window + + +# ------------------------------------------------------------------------- # +# UberForm CLASS # +# Used to make forms into TABS (it's trick) # +# ------------------------------------------------------------------------- # +class UberForm(): + FormList = None # list of all the forms in this window + FormReturnValues = None + TKroot = None # tk root for the overall window + TKrootDestroyed = False + def __init__(self): + self.FormList = [] + self.FormReturnValues = [] + self.TKroot = None + self.TKrootDestroyed = False + self.FormStayedOpen = False + + def AddForm(self, form): + self.FormList.append(form) + + def _Close(self): + self.FormReturnValues = [] + for form in self.FormList: + form._Close() + self.FormReturnValues.append(form.ReturnValues) + if not self.TKrootDestroyed: + self.TKrootDestroyed = True + self.TKroot.destroy() + _my_windows.Decrement() + + def __del__(self): + return + +# =========================================================================== # +# Button Lazy Functions so the caller doesn't have to define a bunch of stuff # +# =========================================================================== # + + +# ------------------------- FOLDER BROWSE Element lazy function ------------------------- # +def FolderBrowse(button_text='Browse', target=(ThisRow, -1), initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_BROWSE_FOLDER, target=target, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- FILE BROWSE Element lazy function ------------------------- # +def FileBrowse( button_text='Browse',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_BROWSE_FILE, target=target, file_types=file_types,initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- FILES BROWSE Element (Multiple file selection) lazy function ------------------------- # +def FilesBrowse(button_text='Browse',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_BROWSE_FILES, target=target, file_types=file_types, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- FILE BROWSE Element lazy function ------------------------- # +def FileSaveAs(button_text='Save As...',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), initial_folder=None, tooltip=None,size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_SAVEAS_FILE, target=target, file_types=file_types, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- SAVE AS Element lazy function ------------------------- # +def SaveAs(button_text='Save As...',target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),),initial_folder=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_SAVEAS_FILE, target=target, file_types=file_types, initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, pad=pad, key=key) + +# ------------------------- SAVE BUTTON Element lazy function ------------------------- # +def Save(button_text='Save', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- SUBMIT BUTTON Element lazy function ------------------------- # +def Submit(button_text='Submit', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None, focus=False, pad=None, key=None): + return Button( button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- OPEN BUTTON Element lazy function ------------------------- # +def Open(button_text='Open', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- OK BUTTON Element lazy function ------------------------- # +def OK(button_text='OK', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None,focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color,font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- YES BUTTON Element lazy function ------------------------- # +def Ok(button_text='Ok', size=(None, None), auto_size_button=None, button_color=None, bind_return_key=True, tooltip=None, font=None,focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- CANCEL BUTTON Element lazy function ------------------------- # +def Cancel(button_text='Cancel', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- QUIT BUTTON Element lazy function ------------------------- # +def Quit(button_text='Quit', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- Exit BUTTON Element lazy function ------------------------- # +def Exit(button_text='Exit', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- YES BUTTON Element lazy function ------------------------- # +def Yes(button_text='Yes', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=True, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- NO BUTTON Element lazy function ------------------------- # +def No(button_text='No', size=(None, None), auto_size_button=None, button_color=None, tooltip=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- NO BUTTON Element lazy function ------------------------- # +def Help(button_text='Help', size=(None, None), auto_size_button=None, button_color=None,font=None,tooltip=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- GENERIC BUTTON Element lazy function ------------------------- # +def SimpleButton(button_text, image_filename=None, image_size=(None, None), image_subsample=None, border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_CLOSES_WIN, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +# ------------------------- GENERIC BUTTON Element lazy function ------------------------- # +def ReadButton(button_text, image_filename=None, image_size=(None, None),image_subsample=None,border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button( button_text=button_text, button_type=BUTTON_TYPE_READ_FORM, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +ReadFormButton = ReadButton +RButton = ReadFormButton + + +# ------------------------- Realtime BUTTON Element lazy function ------------------------- # +def RealtimeButton(button_text, image_filename=None, image_size=(None, None),image_subsample=None,border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button( button_text=button_text,button_type=BUTTON_TYPE_REALTIME, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +# ------------------------- Dummy BUTTON Element lazy function ------------------------- # +def DummyButton(button_text, image_filename=None, image_size=(None, None),image_subsample=None,border_width=None,tooltip=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type= BUTTON_TYPE_CLOSES_WIN_ONLY, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +# ------------------------- Calendar Chooser Button lazy function ------------------------- # +def CalendarButton(button_text, target=(None,None), image_filename=None, image_size=(None, None), image_subsample=None,tooltip=None, border_width=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text, button_type=BUTTON_TYPE_CALENDAR_CHOOSER, target=target, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) + +# ------------------------- Calendar Chooser Button lazy function ------------------------- # +def ColorChooserButton(button_text, target=(None,None), image_filename=None, image_size=(None, None), image_subsample=None,tooltip=None, border_width=None, size=(None, None), auto_size_button=None, button_color=None, font=None, bind_return_key=False, focus=False, pad=None, key=None): + return Button(button_text=button_text,button_type=BUTTON_TYPE_COLOR_CHOOSER, target=target, image_filename=image_filename, image_size=image_size, image_subsample=image_subsample, border_width=border_width, tooltip=tooltip, size=size, auto_size_button=auto_size_button, button_color=button_color, font=font, bind_return_key=bind_return_key, focus=focus, pad=pad, key=key) +##################################### ----- RESULTS ------ ################################################## + +def AddToReturnDictionary(form, element, value): + if element.Key is None: + form.ReturnValuesDictionary[form.DictionaryKeyCounter] = value + element.Key = form.DictionaryKeyCounter + form.DictionaryKeyCounter += 1 + else: + form.ReturnValuesDictionary[element.Key] = value + +def AddToReturnList(form, value): + form.ReturnValuesList.append(value) + + +#----------------------------------------------------------------------------# +# ------- FUNCTION InitializeResults. Sets up form results matrix --------# +def InitializeResults(form): + BuildResults(form, True, form) + return + +#===== Radio Button RadVar encoding and decoding =====# +#===== The value is simply the row * 1000 + col =====# +def DecodeRadioRowCol(RadValue): + row = RadValue//1000 + col = RadValue%1000 + return row,col + +def EncodeRadioRowCol(row, col): + RadValue = row * 1000 + col + return RadValue + +# ------- FUNCTION BuildResults. Form exiting so build the results to pass back ------- # +# format of return values is +# (Button Pressed, input_values) +def BuildResults(form, initialize_only, top_level_form): + # Results for elements are: + # TEXT - Nothing + # INPUT - Read value from TK + # Button - Button Text and position as a Tuple + + # Get the initialized results so we don't have to rebuild + form.DictionaryKeyCounter = 0 + form.ReturnValuesDictionary = {} + form.ReturnValuesList = [] + BuildResultsForSubform(form, initialize_only, top_level_form) + if not top_level_form.LastButtonClickedWasRealtime: + top_level_form.LastButtonClicked = None + return form.ReturnValues + +def BuildResultsForSubform(form, initialize_only, top_level_form): + button_pressed_text = top_level_form.LastButtonClicked + for row_num,row in enumerate(form.Rows): + for col_num, element in enumerate(row): + value = None + if element.Type == ELEM_TYPE_COLUMN: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if element.Type == ELEM_TYPE_FRAME: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if element.Type == ELEM_TYPE_TAB_GROUP: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if element.Type == ELEM_TYPE_TAB: + element.DictionaryKeyCounter = top_level_form.DictionaryKeyCounter + element.ReturnValuesList = [] + element.ReturnValuesDictionary = {} + BuildResultsForSubform(element, initialize_only, top_level_form) + for item in element.ReturnValuesList: + AddToReturnList(top_level_form, item) + if element.UseDictionary: + top_level_form.UseDictionary = True + if element.ReturnValues[0] is not None: # if a button was clicked + button_pressed_text = element.ReturnValues[0] + + if not initialize_only: + if element.Type == ELEM_TYPE_INPUT_TEXT: + value=element.TKStringVar.get() + if not top_level_form.NonBlocking and not element.do_not_clear and not top_level_form.ReturnKeyboardEvents: + element.TKStringVar.set('') + elif element.Type == ELEM_TYPE_INPUT_CHECKBOX: + value = element.TKIntVar.get() + value = (value != 0) + elif element.Type == ELEM_TYPE_INPUT_RADIO: + RadVar=element.TKIntVar.get() + this_rowcol = EncodeRadioRowCol(row_num,col_num) + value = RadVar == this_rowcol + elif element.Type == ELEM_TYPE_BUTTON: + if top_level_form.LastButtonClicked == element.ButtonText: + button_pressed_text = top_level_form.LastButtonClicked + if element.BType != BUTTON_TYPE_REALTIME: # Do not clear realtime buttons + top_level_form.LastButtonClicked = None + if element.BType == BUTTON_TYPE_CALENDAR_CHOOSER: + try: + value = element.TKCal.selection + except: + value = None + else: + try: + value = element.TKStringVar.get() + except: + value = None + elif element.Type == ELEM_TYPE_INPUT_COMBO: + value=element.TKStringVar.get() + elif element.Type == ELEM_TYPE_INPUT_OPTION_MENU: + value=element.TKStringVar.get() + elif element.Type == ELEM_TYPE_INPUT_LISTBOX: + try: + items=element.TKListbox.curselection() + value = [element.Values[int(item)] for item in items] + except: + value = '' + elif element.Type == ELEM_TYPE_INPUT_SPIN: + try: + value=element.TKStringVar.get() + except: + value = 0 + elif element.Type == ELEM_TYPE_INPUT_SLIDER: + try: + value=element.TKIntVar.get() + except: + value = 0 + elif element.Type == ELEM_TYPE_INPUT_MULTILINE: + try: + value=element.TKText.get(1.0, tk.END) + if not top_level_form.NonBlocking and not element.do_not_clear and not top_level_form.ReturnKeyboardEvents: + element.TKText.delete('1.0', tk.END) + except: + value = None + else: + value = None + + # if an input type element, update the results + if element.Type != ELEM_TYPE_BUTTON and element.Type != ELEM_TYPE_TEXT and element.Type != ELEM_TYPE_IMAGE and\ + element.Type != ELEM_TYPE_OUTPUT and element.Type != ELEM_TYPE_PROGRESS_BAR and \ + element.Type!= ELEM_TYPE_COLUMN and element.Type != ELEM_TYPE_FRAME and element.Type != ELEM_TYPE_TAB_GROUP \ + and element.Type != ELEM_TYPE_TAB: + AddToReturnList(form, value) + AddToReturnDictionary(top_level_form, element, value) + elif (element.Type == ELEM_TYPE_BUTTON and element.BType == BUTTON_TYPE_CALENDAR_CHOOSER and element.Target == (None,None)) or \ + (element.Type == ELEM_TYPE_BUTTON and element.BType == BUTTON_TYPE_COLOR_CHOOSER and element.Target == (None,None)) or \ + (element.Type == ELEM_TYPE_BUTTON and element.Key is not None and (element.BType in (BUTTON_TYPE_SAVEAS_FILE, BUTTON_TYPE_BROWSE_FILE, BUTTON_TYPE_BROWSE_FILES, BUTTON_TYPE_BROWSE_FOLDER))): + AddToReturnList(form, value) + AddToReturnDictionary(top_level_form, element, value) + + # if this is a column, then will fail so need to wrap with tr + try: + if form.ReturnKeyboardEvents and form.LastKeyboardEvent is not None: + button_pressed_text = form.LastKeyboardEvent + form.LastKeyboardEvent = None + except: pass + + try: + form.ReturnValuesDictionary.pop(None, None) # clean up dictionary include None was included + except: pass + + if not form.UseDictionary: + form.ReturnValues = button_pressed_text, form.ReturnValuesList + else: + form.ReturnValues = button_pressed_text, form.ReturnValuesDictionary + + return form.ReturnValues + +def FillFormWithValues(form, values_dict): + FillSubformWithValues(form, values_dict) + +def FillSubformWithValues(form, values_dict): + for row_num,row in enumerate(form.Rows): + for col_num, element in enumerate(row): + value = None + if element.Type == ELEM_TYPE_COLUMN: + FillSubformWithValues(element, values_dict) + if element.Type == ELEM_TYPE_FRAME: + FillSubformWithValues(element, values_dict) + if element.Type == ELEM_TYPE_TAB_GROUP: + FillSubformWithValues(element, values_dict) + if element.Type == ELEM_TYPE_TAB: + FillSubformWithValues(element, values_dict) + try: + value = values_dict[element.Key] + except: + continue + if element.Type == ELEM_TYPE_INPUT_TEXT: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_CHECKBOX: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_RADIO: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_COMBO: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_OPTION_MENU: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_LISTBOX: + element.SetValue(value) + elif element.Type == ELEM_TYPE_INPUT_SLIDER: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_MULTILINE: + element.Update(value) + elif element.Type == ELEM_TYPE_INPUT_SPIN: + element.Update(value) + elif element.Type == ELEM_TYPE_BUTTON: + element.Update(value) + +def _FindElementFromKeyInSubForm(form, key): + for row_num, row in enumerate(form.Rows): + for col_num, element in enumerate(row): + if element.Type == ELEM_TYPE_COLUMN: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Type == ELEM_TYPE_FRAME: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Type == ELEM_TYPE_TAB_GROUP: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Type == ELEM_TYPE_TAB: + matching_elem = _FindElementFromKeyInSubForm(element, key) + if matching_elem is not None: + return matching_elem + if element.Key == key: + return element + + +def AddMenuItem(top_menu, sub_menu_info, element, is_sub_menu=False, skip=False): + if type(sub_menu_info) is str: + if not is_sub_menu and not skip: + # print(f'Adding command {sub_menu_info}') + top_menu.add_command(label=sub_menu_info, command=lambda: Menu.MenuItemChosenCallback(element, sub_menu_info)) + else: + i = 0 + while i < (len(sub_menu_info)): + item = sub_menu_info[i] + if i != len(sub_menu_info) - 1: + if type(sub_menu_info[i+1]) == list: + new_menu = tk.Menu(top_menu, tearoff=element.Tearoff) + top_menu.add_cascade(label=sub_menu_info[i], menu=new_menu) + AddMenuItem(new_menu, sub_menu_info[i+1], element, is_sub_menu=True) + i += 1 # skip the next one + else: + AddMenuItem(top_menu, item, element) + else: + AddMenuItem(top_menu, item, element) + i += 1 + +# ------------------------------------------------------------------------------------------------------------------ # +# ===================================== TK CODE STARTS HERE ====================================================== # +# ------------------------------------------------------------------------------------------------------------------ # + +def PackFormIntoFrame(form, containing_frame, toplevel_form): + def CharWidthInPixels(): + return tkFont.Font().measure('A') # single character width + # only set title on non-tabbed forms + border_depth = toplevel_form.BorderDepth if toplevel_form.BorderDepth is not None else DEFAULT_BORDER_WIDTH + # --------------------------------------------------------------------------- # + # **************** Use FlexForm to build the tkinter window ********** ----- # + # Building is done row by row. # + # --------------------------------------------------------------------------- # + focus_set = False + ######################### LOOP THROUGH ROWS ######################### + # *********** ------- Loop through ROWS ------- ***********# + for row_num, flex_row in enumerate(form.Rows): + ######################### LOOP THROUGH ELEMENTS ON ROW ######################### + # *********** ------- Loop through ELEMENTS ------- ***********# + # *********** Make TK Row ***********# + tk_row_frame = tk.Frame(containing_frame) + for col_num, element in enumerate(flex_row): + element.ParentForm = toplevel_form # save the button's parent form object + if toplevel_form.Font and (element.Font == DEFAULT_FONT or not element.Font): + font = toplevel_form.Font + elif element.Font is not None: + font = element.Font + else: + font = DEFAULT_FONT + # ------- Determine Auto-Size setting on a cascading basis ------- # + if element.AutoSizeText is not None: # if element overide + auto_size_text = element.AutoSizeText + elif toplevel_form.AutoSizeText is not None: # if form override + auto_size_text = toplevel_form.AutoSizeText + else: + auto_size_text = DEFAULT_AUTOSIZE_TEXT + element_type = element.Type + # Set foreground color + text_color = element.TextColor + # Determine Element size + element_size = element.Size + if (element_size == (None, None) and element_type != ELEM_TYPE_BUTTON): # user did not specify a size + element_size = toplevel_form.DefaultElementSize + elif (element_size == (None, None) and element_type == ELEM_TYPE_BUTTON): + element_size = toplevel_form.DefaultButtonElementSize + else: auto_size_text = False # if user has specified a size then it shouldn't autosize + # ------------------------- COLUMN element ------------------------- # + if element_type == ELEM_TYPE_COLUMN: + if element.Scrollable: + col_frame = TkScrollableFrame(tk_row_frame) # do not use yet! not working + PackFormIntoFrame(element, col_frame.TKFrame, toplevel_form) + col_frame.TKFrame.update() + if element.Size == (None, None): # if no size specified, use column width x column height/2 + col_frame.canvas.config(width=col_frame.TKFrame.winfo_reqwidth(),height=col_frame.TKFrame.winfo_reqheight()/2) + else: + col_frame.canvas.config(width=element.Size[0],height=element.Size[1]) + + if not element.BackgroundColor in (None, COLOR_SYSTEM_DEFAULT): + col_frame.canvas.config(background=element.BackgroundColor) + col_frame.TKFrame.config(background=element.BackgroundColor, borderwidth =0, highlightthickness=0) + col_frame.config(background=element.BackgroundColor, borderwidth =0, highlightthickness=0) + else: + col_frame = tk.Frame(tk_row_frame) + PackFormIntoFrame(element, col_frame, toplevel_form) + + col_frame.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + col_frame.configure(background=element.BackgroundColor, highlightbackground=element.BackgroundColor, highlightcolor=element.BackgroundColor) + + # ------------------------- TEXT element ------------------------- # + elif element_type == ELEM_TYPE_TEXT: + # auto_size_text = element.AutoSizeText + display_text = element.DisplayText # text to display + if auto_size_text is False: + width, height=element_size + else: + lines = display_text.split('\n') + max_line_len = max([len(l) for l in lines]) + num_lines = len(lines) + if max_line_len > element_size[0]: # if text exceeds element size, the will have to wrap + width = element_size[0] + else: + width=max_line_len + height=num_lines + # ---===--- LABEL widget create and place --- # + stringvar = tk.StringVar() + element.TKStringVar = stringvar + stringvar.set(display_text) + if auto_size_text: + width = 0 + if element.Justification is not None: + justification = element.Justification + elif toplevel_form.TextJustification is not None: + justification = toplevel_form.TextJustification + else: + justification = DEFAULT_TEXT_JUSTIFICATION + justify = tk.LEFT if justification == 'left' else tk.CENTER if justification == 'center' else tk.RIGHT + anchor = tk.NW if justification == 'left' else tk.N if justification == 'center' else tk.NE + tktext_label = tk.Label(tk_row_frame, textvariable=stringvar, width=width, height=height, justify=justify, bd=border_depth, font=font) + # Set wrap-length for text (in PIXELS) == PAIN IN THE ASS + wraplen = tktext_label.winfo_reqwidth()+40 # width of widget in Pixels + if not auto_size_text and height == 1: + wraplen = 0 + # print("wraplen, width, height", wraplen, width, height) + tktext_label.configure(anchor=anchor, wraplen=wraplen) # set wrap to width of widget + if element.Relief is not None: + tktext_label.configure(relief=element.Relief) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + tktext_label.configure(background=element.BackgroundColor) + if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + tktext_label.configure(fg=element.TextColor) + tktext_label.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1], expand=True) + element.TKText = tktext_label + if element.ClickSubmits: + tktext_label.bind('', element.TextClickedHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKText, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- BUTTON element ------------------------- # + elif element_type == ELEM_TYPE_BUTTON: + stringvar = tk.StringVar() + element.TKStringVar = stringvar + element.Location = (row_num, col_num) + btext = element.ButtonText + btype = element.BType + if element.AutoSizeButton is not None: + auto_size = element.AutoSizeButton + else: auto_size = toplevel_form.AutoSizeButtons + if auto_size is False or element.Size[0] is not None: + width, height = element_size + else: + width = 0 + height= toplevel_form.DefaultButtonElementSize[1] + if element.ButtonColor != (None, None)and element.ButtonColor != DEFAULT_BUTTON_COLOR: + bc = element.ButtonColor + elif toplevel_form.ButtonColor != (None, None) and toplevel_form.ButtonColor != DEFAULT_BUTTON_COLOR: + bc = toplevel_form.ButtonColor + else: + bc = DEFAULT_BUTTON_COLOR + border_depth = element.BorderWidth + if btype != BUTTON_TYPE_REALTIME: + tkbutton = tk.Button(tk_row_frame, text=btext, width=width, height=height,command=element.ButtonCallBack, justify=tk.LEFT, bd=border_depth, font=font) + else: + tkbutton = tk.Button(tk_row_frame, text=btext, width=width, height=height, justify=tk.LEFT, bd=border_depth, font=font) + tkbutton.bind('', element.ButtonReleaseCallBack) + tkbutton.bind('', element.ButtonPressCallBack) + if bc != (None, None) and bc != COLOR_SYSTEM_DEFAULT: + tkbutton.config(foreground=bc[0], background=bc[1]) + element.TKButton = tkbutton # not used yet but save the TK button in case + wraplen = tkbutton.winfo_reqwidth() # width of widget in Pixels + if element.ImageFilename: # if button has an image on it + tkbutton.config(highlightthickness=0) + photo = tk.PhotoImage(file=element.ImageFilename) + if element.ImageSize != (None, None): + width, height = element.ImageSize + if element.ImageSubsample: + photo = photo.subsample(element.ImageSubsample) + else: + width, height = photo.width(), photo.height() + tkbutton.config(image=photo, width=width, height=height) + tkbutton.image = photo + if width != 0: + tkbutton.configure(wraplength=wraplen+10) # set wrap to width of widget + tkbutton.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.BindReturnKey: + element.TKButton.bind('', element.ReturnKeyHandler) + if element.Focus is True or (toplevel_form.UseDefaultFocus and not focus_set): + focus_set = True + element.TKButton.bind('', element.ReturnKeyHandler) + element.TKButton.focus_set() + toplevel_form.TKroot.focus_force() + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKButton, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT (Single Line) element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_TEXT: + default_text = element.DefaultText + element.TKStringVar = tk.StringVar() + element.TKStringVar.set(default_text) + show = element.PasswordCharacter if element.PasswordCharacter else "" + if element.Justification is not None: + justification = element.Justification + else: + justification = DEFAULT_TEXT_JUSTIFICATION + justify = tk.LEFT if justification == 'left' else tk.CENTER if justification == 'center' else tk.RIGHT + # anchor = tk.NW if justification == 'left' else tk.N if justification == 'center' else tk.NE + element.TKEntry = tk.Entry(tk_row_frame, width=element_size[0], textvariable=element.TKStringVar, bd=border_depth, font=font, show=show, justify=justify) + element.TKEntry.bind('', element.ReturnKeyHandler) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKEntry.configure(background=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKEntry.configure(fg=text_color) + element.TKEntry.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1], expand=True, fill='x') + if element.Focus is True or (toplevel_form.UseDefaultFocus and not focus_set): + focus_set = True + element.TKEntry.focus_set() + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKEntry, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- COMBO BOX (Drop Down) element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_COMBO: + max_line_len = max([len(str(l)) for l in element.Values]) + if auto_size_text is False: width=element_size[0] + else: width = max_line_len + element.TKStringVar = tk.StringVar() + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + combostyle = ttk.Style() + try: + combostyle.theme_create('combostyle', + settings={'TCombobox': + {'configure': + {'selectbackground': element.BackgroundColor, + 'fieldbackground': element.BackgroundColor, + 'foreground': text_color, + 'background': element.BackgroundColor} + }}) + except: + try: + combostyle.theme_settings('combostyle', + settings={'TCombobox': + {'configure': + {'selectbackground': element.BackgroundColor, + 'fieldbackground': element.BackgroundColor, + 'foreground': text_color, + 'background': element.BackgroundColor} + }}) + except: pass + # ATTENTION: this applies the new style 'combostyle' to all ttk.Combobox + combostyle.theme_use('combostyle') + element.TKCombo = ttk.Combobox(tk_row_frame, width=width, textvariable=element.TKStringVar,font=font ) + if element.Size[1] != 1 and element.Size[1] is not None: + element.TKCombo.configure(height=element.Size[1]) + # element.TKCombo['state']='readonly' + element.TKCombo['values'] = element.Values + if element.InitializeAsDisabled: + element.TKCombo['state'] = 'disabled' + # if element.BackgroundColor is not None: + # element.TKCombo.configure(background=element.BackgroundColor) + element.TKCombo.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.DefaultValue: + for i, v in enumerate(element.Values): + if v == element.DefaultValue: + element.TKCombo.current(i) + break + else: + element.TKCombo.current(0) + if element.ChangeSubmits: + element.TKCombo.bind('<>', element.ComboboxSelectHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKCombo, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- OPTION MENU (Like ComboBox but different) element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_OPTION_MENU: + max_line_len = max([len(str(l)) for l in element.Values]) + if auto_size_text is False: width=element_size[0] + else: width = max_line_len + element.TKStringVar = tk.StringVar() + default = element.DefaultValue if element.DefaultValue else element.Values[0] + element.TKStringVar.set(default) + element.TKOptionMenu = tk.OptionMenu(tk_row_frame, element.TKStringVar ,*element.Values) + element.TKOptionMenu.config(highlightthickness=0, font=font, width=width ) + element.TKOptionMenu.config(borderwidth=border_depth) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKOptionMenu.configure(background=element.BackgroundColor) + if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + element.TKOptionMenu.configure(fg=element.TextColor) + element.TKOptionMenu.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKOptionMenu, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- LISTBOX element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_LISTBOX: + max_line_len = max([len(str(l)) for l in element.Values]) + if auto_size_text is False: width=element_size[0] + else: width = max_line_len + listbox_frame = tk.Frame(tk_row_frame) + element.TKStringVar = tk.StringVar() + element.TKListbox= tk.Listbox(listbox_frame, height=element_size[1], width=width, selectmode=element.SelectMode, font=font) + for index, item in enumerate(element.Values): + element.TKListbox.insert(tk.END, item) + if element.DefaultValues is not None and item in element.DefaultValues: + element.TKListbox.selection_set(index) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKListbox.configure(background=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKListbox.configure(fg=text_color) + if element.ChangeSubmits: + element.TKListbox.bind('<>', element.ListboxSelectHandler) + vsb = tk.Scrollbar(listbox_frame, orient="vertical", command=element.TKListbox.yview) + element.TKListbox.configure(yscrollcommand=vsb.set) + element.TKListbox.pack(side=tk.LEFT) + vsb.pack(side=tk.LEFT, fill='y') + listbox_frame.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.BindReturnKey: + element.TKListbox.bind('', element.ReturnKeyHandler) + element.TKListbox.bind('', element.ReturnKeyHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKListbox, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT MULTI LINE element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_MULTILINE: + default_text = element.DefaultText + width, height = element_size + element.TKText = ScrolledText.ScrolledText(tk_row_frame, width=width, height=height, wrap='word', bd=border_depth,font=font) + element.TKText.insert(1.0, default_text) # set the default text + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKText.configure(background=element.BackgroundColor) + element.TKText.vbar.config(troughcolor=DEFAULT_SCROLLBAR_COLOR) + element.TKText.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1], expand=True, fill='both') + if element.EnterSubmits: + element.TKText.bind('', element.ReturnKeyHandler) + if element.Focus is True or (toplevel_form.UseDefaultFocus and not focus_set): + focus_set = True + element.TKText.focus_set() + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKText.configure(fg=text_color) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKText, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT CHECKBOX element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_CHECKBOX: + width = 0 if auto_size_text else element_size[0] + default_value = element.InitialState + element.TKIntVar = tk.IntVar() + element.TKIntVar.set(default_value if default_value is not None else 0) + element.TKCheckbutton = tk.Checkbutton(tk_row_frame, anchor=tk.NW, text=element.Text, width=width, variable=element.TKIntVar, bd=border_depth, font=font) + if default_value is None: + element.TKCheckbutton.configure(state='disable') + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKCheckbutton.configure(background=element.BackgroundColor) + element.TKCheckbutton.configure(selectcolor=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKCheckbutton.configure(fg=text_color) + element.TKCheckbutton.pack(side=tk.LEFT,padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKCheckbutton, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- PROGRESS BAR element ------------------------- # + elif element_type == ELEM_TYPE_PROGRESS_BAR: + # save this form because it must be 'updated' (refreshed) solely for the purpose of updating bar + width = element_size[0] + fnt = tkFont.Font() + char_width = fnt.measure('A') # single character width + progress_length = width*char_width + progress_width = element_size[1] + direction = element.Orientation + if element.BarColor != (None, None): # if element has a bar color, use it + bar_color = element.BarColor + else: + bar_color = DEFAULT_PROGRESS_BAR_COLOR + element.TKProgressBar = TKProgressBar(tk_row_frame, element.MaxValue, progress_length, progress_width, orientation=direction, BarColor=bar_color, border_width=element.BorderWidth, relief=element.Relief, style=element.BarStyle ) + element.TKProgressBar.TKProgressBarForReal.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + # ------------------------- INPUT RADIO BUTTON element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_RADIO: + width = 0 if auto_size_text else element_size[0] + default_value = element.InitialState + ID = element.GroupID + # see if ID has already been placed + value = EncodeRadioRowCol(row_num, col_num) # value to set intvar to if this radio is selected + if ID in toplevel_form.RadioDict: + RadVar = toplevel_form.RadioDict[ID] + else: + RadVar = tk.IntVar() + toplevel_form.RadioDict[ID] = RadVar + element.TKIntVar = RadVar # store the RadVar in Radio object + if default_value: # if this radio is the one selected, set RadVar to match + element.TKIntVar.set(value) + element.TKRadio = tk.Radiobutton(tk_row_frame, anchor=tk.NW, text=element.Text, width=width, + variable=element.TKIntVar, value=value, bd=border_depth, font=font) + if not element.BackgroundColor in (None, COLOR_SYSTEM_DEFAULT): + element.TKRadio.configure(background=element.BackgroundColor) + element.TKRadio.configure(selectcolor=element.BackgroundColor) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKRadio.configure(fg=text_color) + element.TKRadio.pack(side=tk.LEFT, padx=element.Pad[0],pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKRadio, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- INPUT SPIN Box element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_SPIN: + width, height = element_size + width = 0 if auto_size_text else element_size[0] + element.TKStringVar = tk.StringVar() + element.TKSpinBox = tk.Spinbox(tk_row_frame, values=element.Values, textvariable=element.TKStringVar, width=width, bd=border_depth) + element.TKStringVar.set(element.DefaultValue) + element.TKSpinBox.configure(font=font) # set wrap to width of widget + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKSpinBox.configure(background=element.BackgroundColor) + element.TKSpinBox.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + element.TKSpinBox.configure(fg=text_color) + if element.ChangeSubmits: + element.TKSpinBox.bind('', element.SpinChangedHandler) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKSpinBox, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- OUTPUT element ------------------------- # + elif element_type == ELEM_TYPE_OUTPUT: + width, height = element_size + element.TKOut = TKOutput(tk_row_frame, width=width, height=height, bd=border_depth, background_color=element.BackgroundColor, text_color=text_color, font=font, pad=element.Pad) + element.TKOut.pack(side=tk.LEFT, expand=True, fill='both') + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKOut, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- IMAGE Box element ------------------------- # + elif element_type == ELEM_TYPE_IMAGE: + if element.Filename is not None: + photo = tk.PhotoImage(file=element.Filename) + elif element.Data is not None: + photo = tk.PhotoImage(data=element.Data) + else: + photo = None + print('*ERROR laying out form.... Image Element has no image specified*') + + if photo is not None: + if element_size == (None, None) or element_size == None or element_size == toplevel_form.DefaultElementSize: + width, height = photo.width(), photo.height() + else: + width, height = element_size + if photo is not None: + element.tktext_label = tk.Label(tk_row_frame, image=photo, width=width, height=height, bd=border_depth) + else: + element.tktext_label = tk.Label(tk_row_frame, width=width, height=height, bd=border_depth) + element.tktext_label.image = photo + # tktext_label.configure(anchor=tk.NW, image=photo) + element.tktext_label.pack(side=tk.LEFT, padx=element.Pad[0],pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.tktext_label, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- Canvas element ------------------------- # + elif element_type == ELEM_TYPE_CANVAS: + width, height = element_size + if element._TKCanvas is None: + element._TKCanvas = tk.Canvas(tk_row_frame, width=width, height=height, bd=border_depth) + else: + element._TKCanvas.master = tk_row_frame + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element._TKCanvas.configure(background=element.BackgroundColor, highlightthickness=0) + element._TKCanvas.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element._TKCanvas, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- Graph element ------------------------- # + elif element_type == ELEM_TYPE_GRAPH: + width, height = element_size + if element._TKCanvas is None: + element._TKCanvas = tk.Canvas(tk_row_frame, width=width, height=height, bd=border_depth) + else: + element._TKCanvas.master = tk_row_frame + element._TKCanvas2 = tk.Canvas(element._TKCanvas, width=width, height=height, bd=border_depth) + element._TKCanvas2.pack(side=tk.LEFT) + element._TKCanvas2.addtag_all('mytag') + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element._TKCanvas2.configure(background=element.BackgroundColor, highlightthickness=0) + element._TKCanvas.configure(background=element.BackgroundColor, highlightthickness=0) + element._TKCanvas.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element._TKCanvas, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- MENUBAR element ------------------------- # + elif element_type == ELEM_TYPE_MENUBAR: + menu_def = (('File', ('Open', 'Save')), + ('Help', 'About...'),) + # ('Help',)) + + menu_def = element.MenuDefinition + + element.TKMenu = tk.Menu(toplevel_form.TKroot, tearoff=element.Tearoff) # create the menubar + menubar = element.TKMenu + for menu_entry in menu_def: + # print(f'Adding a Menubar ENTRY') + baritem = tk.Menu(menubar, tearoff=element.Tearoff) + menubar.add_cascade(label=menu_entry[0], menu=baritem) + if len(menu_entry) > 1: + AddMenuItem(baritem, menu_entry[1], element) + + toplevel_form.TKroot.configure(menu=element.TKMenu) + # ------------------------- Frame element ------------------------- # + elif element_type == ELEM_TYPE_FRAME: + labeled_frame = tk.LabelFrame(tk_row_frame, text=element.Title, relief=element.Relief) + PackFormIntoFrame(element, labeled_frame, toplevel_form) + labeled_frame.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + labeled_frame.configure(background=element.BackgroundColor, highlightbackground=element.BackgroundColor, highlightcolor=element.BackgroundColor) + if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + labeled_frame.configure(foreground=element.TextColor) + if font is not None: + labeled_frame.configure(font=font) + if element.TitleLocation is not None: + labeled_frame.configure(labelanchor=element.TitleLocation) + if element.BorderWidth is not None: + labeled_frame.configure(borderwidth=element.BorderWidth) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(labeled_frame, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- Tab element ------------------------- # + elif element_type == ELEM_TYPE_TAB: + element.TKFrame = tk.Frame(form.TKNotebook) + PackFormIntoFrame(element, element.TKFrame, toplevel_form) + form.TKNotebook.add(element.TKFrame, text=element.Title) + form.TKNotebook.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1]) + + if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + element.TKFrame.configure(background=element.BackgroundColor, + highlightbackground=element.BackgroundColor, + highlightcolor=element.BackgroundColor) + # if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + # element.TKFrame.configure(foreground=element.TextColor) + if element.BorderWidth is not None: + element.TKFrame.configure(borderwidth=element.BorderWidth) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKFrame, text=element.Tooltip, + timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- TabGroup element ------------------------- # + elif element_type == ELEM_TYPE_TAB_GROUP: + element.TKNotebook = ttk.Notebook(tk_row_frame) + PackFormIntoFrame(element, toplevel_form.TKroot, toplevel_form) + + # element.TKNotebook.pack(side=tk.LEFT) + # if element.BackgroundColor != COLOR_SYSTEM_DEFAULT and element.BackgroundColor is not None: + # element.TKNotebook.configure(background=element.BackgroundColor, + # highlightbackground=element.BackgroundColor, + # highlightcolor=element.BackgroundColor) + # if element.TextColor != COLOR_SYSTEM_DEFAULT and element.TextColor is not None: + # element.TKNotebook.configure(foreground=element.TextColor) + if element.BorderWidth is not None: + element.TKNotebook.configure(borderwidth=element.BorderWidth) + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKNotebook, text=element.Tooltip, + timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- SLIDER Box element ------------------------- # + elif element_type == ELEM_TYPE_INPUT_SLIDER: + slider_length = element_size[0] * CharWidthInPixels() + slider_width = element_size[1] + element.TKIntVar = tk.IntVar() + element.TKIntVar.set(element.DefaultValue) + if element.Orientation[0] == 'v': + range_from = element.Range[1] + range_to = element.Range[0] + slider_length += DEFAULT_MARGINS[1]*(element_size[0]*2) # add in the padding + else: + range_from = element.Range[0] + range_to = element.Range[1] + if element.ChangeSubmits: + tkscale = tk.Scale(tk_row_frame, orient=element.Orientation, variable=element.TKIntVar, from_=range_from, to_=range_to, resolution = element.Resolution, length=slider_length, width=slider_width , bd=element.BorderWidth, relief=element.Relief, font=font, command=element.SliderChangedHandler) + else: + tkscale = tk.Scale(tk_row_frame, orient=element.Orientation, variable=element.TKIntVar, from_=range_from, to_=range_to, resolution = element.Resolution, length=slider_length, width=slider_width , bd=element.BorderWidth, relief=element.Relief, font=font) + tkscale.config(highlightthickness=0) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + tkscale.configure(background=element.BackgroundColor) + if DEFAULT_SCROLLBAR_COLOR != COLOR_SYSTEM_DEFAULT: + tkscale.config(troughcolor=DEFAULT_SCROLLBAR_COLOR) + if text_color is not None and text_color != COLOR_SYSTEM_DEFAULT: + tkscale.configure(fg=text_color) + tkscale.pack(side=tk.LEFT, padx=element.Pad[0],pady=element.Pad[1]) + element.TKScale = tkscale + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKScale, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + # ------------------------- TABLE element ------------------------- # + elif element_type == ELEM_TYPE_TABLE: + width, height = element_size + if element.Justification == 'left': + anchor = tk.W + elif element.Justification == 'right': + anchor = tk.E + else: + anchor = tk.CENTER + column_widths = {} + for row in element.Values: + for i,col in enumerate(row): + col_width = min(len(str(col)), element.MaxColumnWidth) + try: + if col_width > column_widths[i]: + column_widths[i] = col_width + except: + column_widths[i] = col_width + if element.ColumnsToDisplay is None: + displaycolumns = element.ColumnHeadings + else: + displaycolumns = [] + for i, should_display in enumerate(element.ColumnsToDisplay): + if should_display: + displaycolumns.append(element.ColumnHeadings[i]) + column_headings= element.ColumnHeadings + if element.DisplayRowNumbers: # if display row number, tack on the numbers to front of columns + displaycolumns = ['Row',] + displaycolumns + column_headings = ['Row',] + element.ColumnHeadings + element.TKTreeview = ttk.Treeview(tk_row_frame, columns=column_headings, + displaycolumns=displaycolumns, show='headings', height=height, selectmode=element.SelectMode) + treeview = element.TKTreeview + if element.DisplayRowNumbers: + treeview.heading('Row', text='Row') # make a dummy heading + treeview.column('Row', width=50, anchor=anchor) + for i, heading in enumerate(element.ColumnHeadings): + treeview.heading(heading, text=heading) + if element.AutoSizeColumns: + width = max(column_widths[i], len(heading)) + else: + try: + width = element.ColumnWidths[i] + except: + width = element.DefaultColumnWidth + + treeview.column(heading, width=width*CharWidthInPixels(), anchor=anchor) + for i, value in enumerate(element.Values): + if element.DisplayRowNumbers: + value = [i] + value + id = treeview.insert('', 'end', text=value, values=value) + if element.BackgroundColor is not None and element.BackgroundColor != COLOR_SYSTEM_DEFAULT: + element.TKTreeview.configure(background=element.BackgroundColor) + # scrollable_frame.pack(side=tk.LEFT, padx=element.Pad[0], pady=element.Pad[1], expand=True, fill='both') + element.TKTreeview.pack(side=tk.LEFT,expand=True, padx=0, pady=0, fill='both') + if element.Tooltip is not None: + element.TooltipObject = ToolTip(element.TKTreeview, text=element.Tooltip, timeout=DEFAULT_TOOLTIP_TIME) + #............................DONE WITH ROW pack the row of widgets ..........................# + # done with row, pack the row of widgets + # tk_row_frame.grid(row=row_num+2, sticky=tk.NW, padx=DEFAULT_MARGINS[0]) + tk_row_frame.pack(side=tk.TOP, anchor='nw', padx=DEFAULT_MARGINS[0], expand=True) + if form.BackgroundColor is not None and form.BackgroundColor != COLOR_SYSTEM_DEFAULT: + tk_row_frame.configure(background=form.BackgroundColor) + if not toplevel_form.IsTabbedForm: + toplevel_form.TKroot.configure(padx=DEFAULT_MARGINS[0], pady=DEFAULT_MARGINS[1]) + else: toplevel_form.ParentWindow.configure(padx=DEFAULT_MARGINS[0], pady=DEFAULT_MARGINS[1]) + return + + +def ConvertFlexToTK(MyFlexForm): + master = MyFlexForm.TKroot + # only set title on non-tabbed forms + if not MyFlexForm.IsTabbedForm: + master.title(MyFlexForm.Title) + InitializeResults(MyFlexForm) + try: + if MyFlexForm.NoTitleBar: + MyFlexForm.TKroot.wm_overrideredirect(True) + except: + pass + PackFormIntoFrame(MyFlexForm, master, MyFlexForm) + #....................................... DONE creating and laying out window ..........................# + if MyFlexForm.IsTabbedForm: + master = MyFlexForm.ParentWindow + screen_width = master.winfo_screenwidth() # get window info to move to middle of screen + screen_height = master.winfo_screenheight() + if MyFlexForm.Location != (None, None): + x,y = MyFlexForm.Location + elif DEFAULT_WINDOW_LOCATION != (None, None): + x,y = DEFAULT_WINDOW_LOCATION + else: + master.update_idletasks() # don't forget to do updates or values are bad + win_width = master.winfo_width() + win_height = master.winfo_height() + x = screen_width/2 -win_width/2 + y = screen_height/2 - win_height/2 + if y+win_height > screen_height: + y = screen_height-win_height + if x+win_width > screen_width: + x = screen_width-win_width + + move_string = '+%i+%i'%(int(x),int(y)) + master.geometry(move_string) + + master.update_idletasks() # don't forget + + return + + +# ----====----====----====----====----==== STARTUP TK ====----====----====----====----====----# +def StartupTK(my_flex_form): + global _my_windows + + ow = _my_windows.NumOpenWindows + # print('Starting TK open Windows = {}'.format(ow)) + root = tk.Tk() if not ow else tk.Toplevel() + try: + root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint' + except: + pass + # root.wm_overrideredirect(True) + if my_flex_form.BackgroundColor is not None and my_flex_form.BackgroundColor != COLOR_SYSTEM_DEFAULT: + root.configure(background=my_flex_form.BackgroundColor) + _my_windows.Increment() + + my_flex_form.TKroot = root + # Make moveable window + if (my_flex_form.GrabAnywhere is not False and not (my_flex_form.NonBlocking and my_flex_form.GrabAnywhere is not True)): + root.bind("", my_flex_form.StartMove) + root.bind("", my_flex_form.StopMove) + root.bind("", my_flex_form.OnMotion) + + if my_flex_form.KeepOnTop: + root.wm_attributes("-topmost", 1) + + # root.protocol("WM_DELETE_WINDOW", MyFlexForm.DestroyedCallback()) + # root.bind('', MyFlexForm.DestroyedCallback()) + ConvertFlexToTK(my_flex_form) + + my_flex_form.SetIcon(my_flex_form.WindowIcon) + + try: + root.attributes('-alpha', 255) # hide window while building it. makes for smoother 'paint' + except: + pass + + if my_flex_form.ReturnKeyboardEvents and not my_flex_form.NonBlocking: + root.bind("", my_flex_form._KeyboardCallback) + root.bind("", my_flex_form._MouseWheelCallback) + elif my_flex_form.ReturnKeyboardEvents: + root.bind("", my_flex_form._KeyboardCallback) + root.bind("", my_flex_form._MouseWheelCallback) + + if my_flex_form.AutoClose: + duration = DEFAULT_AUTOCLOSE_TIME if my_flex_form.AutoCloseDuration is None else my_flex_form.AutoCloseDuration + my_flex_form.TKAfterID = root.after(duration * 1000, my_flex_form._AutoCloseAlarmCallback) + if my_flex_form.NonBlocking: + my_flex_form.TKroot.protocol("WM_WINDOW_DESTROYED", my_flex_form.OnClosingCallback()) + else: # it's a blocking form + # print('..... CALLING MainLoop') + my_flex_form.TKroot.mainloop() + # print('..... BACK from MainLoop') + if not my_flex_form.FormRemainedOpen: + _my_windows.Decrement() + if my_flex_form.RootNeedsDestroying: + my_flex_form.TKroot.destroy() + my_flex_form.RootNeedsDestroying = False + return + +# ==============================_GetNumLinesNeeded ==# +# Helper function for determining how to wrap text # +# ===================================================# +def _GetNumLinesNeeded(text, max_line_width): + if max_line_width == 0: + return 1 + lines = text.split('\n') + num_lines = len(lines) # number of original lines of text + max_line_len = max([len(l) for l in lines]) # longest line + lines_used = [] + for L in lines: + lines_used.append(len(L)//max_line_width + (len(L) % max_line_width > 0)) # fancy math to round up + total_lines_needed = sum(lines_used) + return total_lines_needed + +# ============================== PROGRESS METER ========================================== # + +def ConvertArgsToSingleString(*args): + max_line_total, width_used , total_lines, = 0,0,0 + single_line_message = '' + # loop through args and built a SINGLE string from them + for message in args: + # fancy code to check if string and convert if not is not need. Just always convert to string :-) + # if not isinstance(message, str): message = str(message) + message = str(message) + longest_line_len = max([len(l) for l in message.split('\n')]) + width_used = max(longest_line_len, width_used) + max_line_total = max(max_line_total, width_used) + lines_needed = _GetNumLinesNeeded(message, width_used) + total_lines += lines_needed + single_line_message += message + '\n' + return single_line_message, width_used, total_lines + + +# ============================== ProgressMeter =====# +# ===================================================# +def _ProgressMeter(title, max_value, *args, **kwargs): + ''' + Create and show a form on tbe caller's behalf. + :param title: + :param max_value: + :param args: ANY number of arguments the caller wants to display + :param orientation: + :param bar_color: + :param size: + :param Style: + :param StyleOffset: + :return: ProgressBar object that is in the form + ''' + + # title, max_value, orientation=None, bar_color=(None,None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, grab_anywhere=True, *args + + try: orientation = kwargs['orientation'] + except: orientation = None + try: bar_color = kwargs['bar_color'] + except: bar_color = (None, None) + try: button_color = kwargs['button_color'] + except: button_color = None + try: size = kwargs['size'] + except: size = DEFAULT_PROGRESS_BAR_SIZE + try: border_width = kwargs['border_width'] + except: border_width = None + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = True + + + local_orientation = DEFAULT_METER_ORIENTATION if orientation is None else orientation + local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if border_width is None else border_width + bar2 = ProgressBar(max_value, orientation=local_orientation, size=size, bar_color=bar_color, border_width=local_border_width, relief=DEFAULT_PROGRESS_BAR_RELIEF) + form = Window(title, auto_size_text=True, grab_anywhere=grab_anywhere) + + # Form using a horizontal bar + if local_orientation[0].lower() == 'h': + single_line_message, width, height = ConvertArgsToSingleString(*args) + bar2.TextToDisplay = single_line_message + bar2.MaxValue = max_value + bar2.CurrentValue = 0 + bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True) + form.AddRow(bar_text) + form.AddRow((bar2)) + form.AddRow((Cancel(button_color=button_color))) + else: + single_line_message, width, height = ConvertArgsToSingleString(*args) + bar2.TextToDisplay = single_line_message + bar2.MaxValue = max_value + bar2.CurrentValue = 0 + bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True) + form.AddRow(bar2, bar_text) + form.AddRow((Cancel(button_color=button_color))) + + form.NonBlocking = True + form.Show(non_blocking= True) + return bar2, bar_text + +# ============================== ProgressMeterUpdate =====# +def _ProgressMeterUpdate(bar, value, text_elem, *args): + ''' + Update the progress meter for a form + :param form: class ProgressBar + :param value: int + :return: True if not cancelled, OK....False if Error + ''' + global _my_windows + if bar == None: return False + if bar.BarExpired: return False + message, w, h = ConvertArgsToSingleString(*args) + text_elem.Update(message) + # bar.TextToDisplay = message + bar.CurrentValue = value + rc = bar.UpdateBar(value) + if value >= bar.MaxValue or not rc: + bar.BarExpired = True + bar.ParentForm._Close() + if rc: # if update was OK but bar expired, decrement num windows + _my_windows.Decrement() + if bar.ParentForm.RootNeedsDestroying: + try: + bar.ParentForm.TKroot.destroy() + # _my_windows.Decrement() + except: pass + bar.ParentForm.RootNeedsDestroying = False + bar.ParentForm.__del__() + return False + + return rc + +# ============================== EASY PROGRESS METER ========================================== # +# class to hold the easy meter info (a global variable essentialy) +class EasyProgressMeterDataClass(): + def __init__(self, title='', current_value=1, max_value=10, start_time=None, stat_messages=()): + self.Title = title + self.CurrentValue = current_value + self.MaxValue = max_value + self.StartTime = start_time + self.StatMessages = stat_messages + self.ParentForm = None + self.MeterID = None + self.MeterText = None + + # =========================== COMPUTE PROGRESS STATS ======================# + def ComputeProgressStats(self): + utc = datetime.datetime.utcnow() + time_delta = utc - self.StartTime + total_seconds = time_delta.total_seconds() + if not total_seconds: + total_seconds = 1 + try: + time_per_item = total_seconds / self.CurrentValue + except: + time_per_item = 1 + seconds_remaining = (self.MaxValue - self.CurrentValue) * time_per_item + time_remaining = str(datetime.timedelta(seconds=seconds_remaining)) + time_remaining_short = (time_remaining).split(".")[0] + time_delta_short = str(time_delta).split(".")[0] + total_time = time_delta + datetime.timedelta(seconds=seconds_remaining) + total_time_short = str(total_time).split(".")[0] + self.StatMessages = [ + '{} of {}'.format(self.CurrentValue, self.MaxValue), + '{} %'.format(100*self.CurrentValue//self.MaxValue), + '', + ' {:6.2f} Iterations per Second'.format(self.CurrentValue/total_seconds), + ' {:6.2f} Seconds per Iteration'.format(total_seconds/(self.CurrentValue if self.CurrentValue else 1)), + '', + '{} Elapsed Time'.format(time_delta_short), + '{} Time Remaining'.format(time_remaining_short), + '{} Estimated Total Time'.format(total_time_short)] + return + + +# ============================== EasyProgressMeter =====# +def EasyProgressMeter(title, current_value, max_value, orientation=None, bar_color=(None,None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, *args): + ''' + A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second + function call before your loop. You've got enough code to write! + :param title: Title will be shown on the window + :param current_value: Current count of your items + :param max_value: Max value your count will ever reach. This indicates it should be closed + :param args: VARIABLE number of arguements... you request it, we'll print it no matter what the item! + :param orientation: + :param bar_color: + :param size: + :param Style: + :param StyleOffset: + :return: False if should stop the meter + ''' + local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if not border_width else border_width + # STATIC VARIABLE! + # This is a very clever form of static variable using a function attribute + # If the variable doesn't yet exist, then it will create it and initialize with the 3rd parameter + EasyProgressMeter.Data = getattr(EasyProgressMeter, 'Data', EasyProgressMeterDataClass()) + # if no meter currently running + if EasyProgressMeter.Data.MeterID is None: # Starting a new meter + print("Please change your call of EasyProgressMeter to use OneLineProgressMeter. EasyProgressMeter will be removed soon") + if int(current_value) >= int(max_value): + return False + del(EasyProgressMeter.Data) + EasyProgressMeter.Data = EasyProgressMeterDataClass(title, 1, int(max_value), datetime.datetime.utcnow(), []) + EasyProgressMeter.Data.ComputeProgressStats() + message = "\n".join([line for line in EasyProgressMeter.Data.StatMessages]) + EasyProgressMeter.Data.MeterID, EasyProgressMeter.Data.MeterText= _ProgressMeter(title, int(max_value), message, *args, orientation=orientation, bar_color=bar_color, size=size, button_color=button_color, border_width=local_border_width) + EasyProgressMeter.Data.ParentForm = EasyProgressMeter.Data.MeterID.ParentForm + return True + # if exactly the same values as before, then ignore. + if EasyProgressMeter.Data.MaxValue == max_value and EasyProgressMeter.Data.CurrentValue == current_value: + return True + if EasyProgressMeter.Data.MaxValue != int(max_value): + EasyProgressMeter.Data.MeterID = None + EasyProgressMeter.Data.ParentForm = None + del(EasyProgressMeter.Data) + EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter + return True # HAVE to return TRUE or else the new meter will thing IT is failing when it hasn't + EasyProgressMeter.Data.CurrentValue = int(current_value) + EasyProgressMeter.Data.MaxValue = int(max_value) + EasyProgressMeter.Data.ComputeProgressStats() + message = '' + for line in EasyProgressMeter.Data.StatMessages: + message = message + str(line) + '\n' + message = "\n".join(EasyProgressMeter.Data.StatMessages) + args= args + (message,) + rc = _ProgressMeterUpdate(EasyProgressMeter.Data.MeterID, current_value, + EasyProgressMeter.Data.MeterText, *args) + # if counter >= max then the progress meter is all done. Indicate none running + if current_value >= EasyProgressMeter.Data.MaxValue or not rc: + EasyProgressMeter.Data.MeterID = None + del(EasyProgressMeter.Data) + EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter + return False # even though at the end, return True so don't cause error with the app + return rc # return whatever the update told us + + +def EasyProgressMeterCancel(title, *args): + EasyProgressMeter.EasyProgressMeterData = getattr(EasyProgressMeter, 'EasyProgressMeterData', EasyProgressMeterDataClass()) + if EasyProgressMeter.EasyProgressMeterData.MeterID is not None: + # tell the normal meter update that we're at max value which will close the meter + rc = EasyProgressMeter(title, EasyProgressMeter.EasyProgressMeterData.MaxValue, EasyProgressMeter.EasyProgressMeterData.MaxValue, ' *** CANCELLING ***', 'Caller requested a cancel', *args) + return rc + return True + + +# global variable containing dictionary will all currently running one-line progress meters. +_one_line_progress_meters = {} + +# ============================== OneLineProgressMeter =====# +def OneLineProgressMeter(title, current_value, max_value, key, orientation=None, bar_color=(None,None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, grab_anywhere=True, *args): + + global _one_line_progress_meters + + local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if border_width is not None else border_width + try: + meter_data = _one_line_progress_meters[key] + except: # a new meater is starting + if int(current_value) >= int(max_value): # if already expired then it's an old meter, ignore + return False + meter_data = EasyProgressMeterDataClass(title, 1, int(max_value), datetime.datetime.utcnow(), []) + _one_line_progress_meters[key] = meter_data + meter_data.ComputeProgressStats() + message = "\n".join([line for line in meter_data.StatMessages]) + meter_data.MeterID, meter_data.MeterText= _ProgressMeter(title, int(max_value), message, orientation=orientation, bar_color=bar_color, size=size, button_color=button_color, border_width=local_border_width, grab_anywhere=grab_anywhere,*args) + meter_data.ParentForm = meter_data.MeterID.ParentForm + return True + + # if exactly the same values as before, then ignore, return success. + if meter_data.MaxValue == max_value and meter_data.CurrentValue == current_value: + return True + meter_data.CurrentValue = int(current_value) + meter_data.MaxValue = int(max_value) + meter_data.ComputeProgressStats() + message = '' + for line in meter_data.StatMessages: + message = message + str(line) + '\n' + message = "\n".join(meter_data.StatMessages) + args= args + (message,) + rc = _ProgressMeterUpdate(meter_data.MeterID, current_value, + meter_data.MeterText, *args) + # if counter >= max then the progress meter is all done. Indicate none running + if current_value >= meter_data.MaxValue or not rc: + del _one_line_progress_meters[key] + return False + return rc # return whatever the update told us + + +def OneLineProgressMeterCancel(key): + global _one_line_progress_meters + + try: + meter_data = _one_line_progress_meters[key] + except: # meter is already deleted + return + OneLineProgressMeter('', meter_data.MaxValue, meter_data.MaxValue, key=key) + + + + +# input is #RRGGBB +# output is #RRGGBB +def GetComplimentaryHex(color): + # strip the # from the beginning + color = color[1:] + # convert the string into hex + color = int(color, 16) + # invert the three bytes + # as good as substracting each of RGB component by 255(FF) + comp_color = 0xFFFFFF ^ color + # convert the color back to hex by prefixing a # + comp_color = "#%06X" % comp_color + return comp_color + + + +# ======================== EasyPrint =====# +# ===================================================# +_easy_print_data = None # global variable... I'm cheating + +class DebugWin(): + def __init__(self, size=(None, None)): + # Show a form that's a running counter + win_size = size if size !=(None, None) else DEFAULT_DEBUG_WINDOW_SIZE + self.form = Window('Debug Window', auto_size_text=True, font=('Courier New', 12)) + self.output_element = Output(size=win_size) + self.form_rows = [[Text('EasyPrint Output')], + [self.output_element], + [Quit()]] + self.form.AddRows(self.form_rows) + self.form.Show(non_blocking=True) # Show a ;non-blocking form, returns immediately + return + + def Print(self, end=None, sep=None, *args): + sepchar = sep if sep is not None else ' ' + endchar = end if end is not None else '\n' + # print(sep=sepchar, end=endchar, *args) + # for a in args: + # msg = str(a) + # print(msg, end="", sep=sepchar) + # print(1, 2, 3, sep='-') + # if end is None: + # print("") + self.form.ReadNonBlocking() + + def Close(self): + self.form.CloseNonBlockingForm() + self.form.__del__() + +def Print( size=(None,None), end=None, sep=None, *args): + EasyPrint(size=size, end=end, sep=sep, *args) + +def PrintClose(): + EasyPrintClose() + +def eprint(size=(None,None), end=None, sep=None, *args): + EasyPrint(size=size, end=end, sep=sep, *args) + +def EasyPrint(size=(None,None), end=None, sep=None, *args): + global _easy_print_data + + if _easy_print_data is None: + _easy_print_data = DebugWin(size=size) + _easy_print_data.Print(end=end, sep=sep, *args) + + + +def EasyPrintold(size=(None,None), end=None, sep=None, *args): + if 'easy_print_data' not in EasyPrint.__dict__: # use a function property to save DebugWin object (static variable) + EasyPrint.easy_print_data = DebugWin(size=size) + if EasyPrint.easy_print_data is None: + EasyPrint.easy_print_data = DebugWin(size=size) + EasyPrint.easy_print_data.Print( end=end, sep=sep,*args) + +def EasyPrintClose(): + if 'easy_print_data' in EasyPrint.__dict__: + if EasyPrint.easy_print_data is not None: + EasyPrint.easy_print_data._Close() + EasyPrint.easy_print_data = None + # del EasyPrint.easy_print_data + +# ======================== Scrolled Text Box =====# +# ===================================================# +def ScrolledTextBox(button_color=None, yes_no=False, auto_close=False, auto_close_duration=None, size=(None, None), *args): + if not args: return + width, height = size + width = width if width else MESSAGE_BOX_LINE_WIDTH + with Window(args[0], auto_size_text=True, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration) as form: + max_line_total, max_line_width, total_lines, height_computed = 0,0,0,0 + complete_output = '' + for message in args: + # fancy code to check if string and convert if not is not need. Just always convert to string :-) + # if not isinstance(message, str): message = str(message) + message = str(message) + longest_line_len = max([len(l) for l in message.split('\n')]) + width_used = min(longest_line_len, width) + max_line_total = max(max_line_total, width_used) + max_line_width = width + lines_needed = _GetNumLinesNeeded(message, width_used) + height_computed += lines_needed + complete_output += message + '\n' + total_lines += lines_needed + height_computed = MAX_SCROLLED_TEXT_BOX_HEIGHT if height_computed > MAX_SCROLLED_TEXT_BOX_HEIGHT else height_computed + if height: + height_computed = height + form.AddRow(Multiline(complete_output, size=(max_line_width, height_computed))) + pad = max_line_total-15 if max_line_total > 15 else 1 + # show either an OK or Yes/No depending on paramater + if yes_no: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False), Yes(), No()) + button, values = form.Read() + return button + else: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False), SimpleButton('OK', size=(5, 1), button_color=button_color)) + button, values = form.Read() + return button + + +PopupScrolled = ScrolledTextBox + +# ---------------------------------------------------------------------- # +# GetPathBox # +# Pre-made dialog that looks like this roughly # +# MESSAGE # +# __________________________ # +# |__________________________| (BROWSE) # +# (SUBMIT) (CANCEL) # +# RETURNS two values: # +# True/False, path # +# (True if Submit was pressed, false otherwise) # +# ---------------------------------------------------------------------- # + +def PopupGetFolder(message, default_path='', no_window=False, size=(None,None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None, None)): + """ + Display popup with text entry field and browse button. Browse for folder + :param message: + :param default_path: + :param no_window: + :param size: + :param button_color: + :param background_color: + :param text_color: + :param icon: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: Contents of text field. None if closed using X + """ + if no_window: + root = tk.Tk() + try: + root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint' + except: + pass + folder_name = tk.filedialog.askdirectory() # show the 'get folder' dialog box + root.destroy() + return folder_name + + with Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, background_color=background_color, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) as form: + layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)], + [InputText(default_text=default_path, size=size), FolderBrowse()], + [Ok(), Cancel()]] + + (button, input_values) = form.LayoutAndRead(layout) + if button != 'Ok': + return None + else: + path = input_values[0] + return path + +##################################### +# PopupGetFile # +##################################### +def PopupGetFile(message, default_path='',save_as=False, file_types=(("ALL Files", "*.*"),), no_window=False, size=(None,None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None)): + """ + Display popup with text entry field and browse button. Browse for file + + :param message: + :param default_path: + :param save_as: + :param file_types: + :param no_window: + :param size: + :param button_color: + :param background_color: + :param text_color: + :param icon: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + if no_window: + root = tk.Tk() + try: + root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint' + except: + pass + if save_as: + filename = tkFileDialog.asksaveasfilename(filetypes=file_types) # show the 'get file' dialog box + else: + filename = tkFileDialog.askopenfilename(filetypes=file_types) # show the 'get file' dialog box + root.destroy() + return filename + + browse_button = SaveAs(file_types=file_types) if save_as else FileBrowse(file_types=file_types) + + with Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, font=font, background_color=background_color, + no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) as form: + layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)], + [InputText(default_text=default_path, size=size), browse_button], + [Ok(), Cancel()]] + + (button, input_values) = form.LayoutAndRead(layout) + if button != 'Ok': + return None + else: + path = input_values[0] + return path + +##################################### +# PopupGetText # +##################################### +def PopupGetText(message, default_text='', password_char='', size=(None,None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None)): + """ + Display Popup with text entry field + :param message: + :param default_text: + :param password_char: + :param size: + :param button_color: + :param background_color: + :param text_color: + :param icon: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: Text entered or None if window was closed + """ + with Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, no_titlebar=no_titlebar, + background_color=background_color, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) as form: + layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color, font=font)], + [InputText(default_text=default_text, size=size, password_char=password_char)], + [Ok(), Cancel()]] + + (button, input_values) = form.LayoutAndRead(layout) + if button != 'Ok': + return None + else: + return input_values[0] + + +# ============================== SetGlobalIcon ======# +# Sets the icon to be used by default # +# ===================================================# +def SetGlobalIcon(icon): + global _my_windows + + try: + with open(icon, 'r') as icon_file: + pass + except: + raise FileNotFoundError + _my_windows.user_defined_icon = icon + return True + + +# ============================== SetOptions =========# +# Sets the icon to be used by default # +# ===================================================# +def SetOptions(icon=None, button_color=None, element_size=(None,None), button_element_size=(None, None), margins=(None,None), + element_padding=(None,None),auto_size_text=None, auto_size_buttons=None, font=None, border_width=None, + slider_border_width=None, slider_relief=None, slider_orientation=None, + autoclose_time=None, message_box_line_width=None, + progress_meter_border_depth=None, progress_meter_style=None, + progress_meter_relief=None, progress_meter_color=None, progress_meter_size=None, + text_justification=None, background_color=None, element_background_color=None, + text_element_background_color=None, input_elements_background_color=None, input_text_color=None, + scrollbar_color=None, text_color=None, element_text_color = None, debug_win_size=(None,None), window_location=(None,None), + tooltip_time=None): + + global DEFAULT_ELEMENT_SIZE + global DEFAULT_BUTTON_ELEMENT_SIZE + global DEFAULT_MARGINS # Margins for each LEFT/RIGHT margin is first term + global DEFAULT_ELEMENT_PADDING # Padding between elements (row, col) in pixels + global DEFAULT_AUTOSIZE_TEXT + global DEFAULT_AUTOSIZE_BUTTONS + global DEFAULT_FONT + global DEFAULT_BORDER_WIDTH + global DEFAULT_AUTOCLOSE_TIME + global DEFAULT_BUTTON_COLOR + global MESSAGE_BOX_LINE_WIDTH + global DEFAULT_PROGRESS_BAR_BORDER_WIDTH + global DEFAULT_PROGRESS_BAR_STYLE + global DEFAULT_PROGRESS_BAR_RELIEF + global DEFAULT_PROGRESS_BAR_COLOR + global DEFAULT_PROGRESS_BAR_SIZE + global DEFAULT_TEXT_JUSTIFICATION + global DEFAULT_DEBUG_WINDOW_SIZE + global DEFAULT_SLIDER_BORDER_WIDTH + global DEFAULT_SLIDER_RELIEF + global DEFAULT_SLIDER_ORIENTATION + global DEFAULT_BACKGROUND_COLOR + global DEFAULT_INPUT_ELEMENTS_COLOR + global DEFAULT_ELEMENT_BACKGROUND_COLOR + global DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR + global DEFAULT_SCROLLBAR_COLOR + global DEFAULT_TEXT_COLOR + global DEFAULT_WINDOW_LOCATION + global DEFAULT_ELEMENT_TEXT_COLOR + global DEFAULT_INPUT_TEXT_COLOR + global DEFAULT_TOOLTIP_TIME + global _my_windows + + if icon: + try: + with open(icon, 'r') as icon_file: + pass + except: + raise FileNotFoundError + _my_windows.user_defined_icon = icon + + if button_color != None: + DEFAULT_BUTTON_COLOR = button_color + + if element_size != (None,None): + DEFAULT_ELEMENT_SIZE = element_size + + if button_element_size != (None,None): + DEFAULT_BUTTON_ELEMENT_SIZE = button_element_size + + if margins != (None,None): + DEFAULT_MARGINS = margins + + if element_padding != (None,None): + DEFAULT_ELEMENT_PADDING = element_padding + + if auto_size_text != None: + DEFAULT_AUTOSIZE_TEXT = auto_size_text + + if auto_size_buttons != None: + DEFAULT_AUTOSIZE_BUTTONS = auto_size_buttons + + if font !=None: + DEFAULT_FONT = font + + if border_width != None: + DEFAULT_BORDER_WIDTH = border_width + + if autoclose_time != None: + DEFAULT_AUTOCLOSE_TIME = autoclose_time + + if message_box_line_width != None: + MESSAGE_BOX_LINE_WIDTH = message_box_line_width + + if progress_meter_border_depth != None: + DEFAULT_PROGRESS_BAR_BORDER_WIDTH = progress_meter_border_depth + + if progress_meter_style != None: + DEFAULT_PROGRESS_BAR_STYLE = progress_meter_style + + if progress_meter_relief != None: + DEFAULT_PROGRESS_BAR_RELIEF = progress_meter_relief + + if progress_meter_color != None: + DEFAULT_PROGRESS_BAR_COLOR = progress_meter_color + + if progress_meter_size != None: + DEFAULT_PROGRESS_BAR_SIZE = progress_meter_size + + if slider_border_width != None: + DEFAULT_SLIDER_BORDER_WIDTH = slider_border_width + + if slider_orientation != None: + DEFAULT_SLIDER_ORIENTATION = slider_orientation + + if slider_relief != None: + DEFAULT_SLIDER_RELIEF = slider_relief + + if text_justification != None: + DEFAULT_TEXT_JUSTIFICATION = text_justification + + if background_color != None: + DEFAULT_BACKGROUND_COLOR = background_color + + if text_element_background_color != None: + DEFAULT_TEXT_ELEMENT_BACKGROUND_COLOR = text_element_background_color + + if input_elements_background_color != None: + DEFAULT_INPUT_ELEMENTS_COLOR = input_elements_background_color + + if element_background_color != None: + DEFAULT_ELEMENT_BACKGROUND_COLOR = element_background_color + + if window_location != (None,None): + DEFAULT_WINDOW_LOCATION = window_location + + if debug_win_size != (None,None): + DEFAULT_DEBUG_WINDOW_SIZE = debug_win_size + + if text_color != None: + DEFAULT_TEXT_COLOR = text_color + + if scrollbar_color != None: + DEFAULT_SCROLLBAR_COLOR = scrollbar_color + + if element_text_color != None: + DEFAULT_ELEMENT_TEXT_COLOR = element_text_color + + if input_text_color is not None: + DEFAULT_INPUT_TEXT_COLOR = input_text_color + + if tooltip_time is not None: + DEFAULT_TOOLTIP_TIME = tooltip_time + + return True + + +#################### ChangeLookAndFeel ####################### +# Predefined settings that will change the colors and styles # +# of the elements. # +############################################################## +def ChangeLookAndFeel(index): + if sys.platform == 'darwin': + print('*** Changing look and feel is not supported on Mac platform ***') + return + + # look and feel table + look_and_feel = {'SystemDefault': {'BACKGROUND' : COLOR_SYSTEM_DEFAULT, 'TEXT': COLOR_SYSTEM_DEFAULT, 'INPUT': COLOR_SYSTEM_DEFAULT,'TEXT_INPUT' : COLOR_SYSTEM_DEFAULT, 'SCROLL': COLOR_SYSTEM_DEFAULT, 'BUTTON': OFFICIAL_PYSIMPLEGUI_BUTTON_COLOR, 'PROGRESS': COLOR_SYSTEM_DEFAULT, 'BORDER': 1,'SLIDER_DEPTH':1, 'PROGRESS_DEPTH':0}, + + 'GreenTan': {'BACKGROUND' : '#9FB8AD', 'TEXT': COLOR_SYSTEM_DEFAULT, 'INPUT':'#F7F3EC','TEXT_INPUT' : 'black','SCROLL': '#F7F3EC', 'BUTTON': ('white', '#475841'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'Dark': {'BACKGROUND': 'gray25', 'TEXT': 'white', 'INPUT': 'gray30', + 'TEXT_INPUT': 'white', 'SCROLL': 'gray44', 'BUTTON': ('white', '#004F00'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Dark2': {'BACKGROUND': 'gray25', 'TEXT': 'white', 'INPUT': 'white', + 'TEXT_INPUT': 'black', 'SCROLL': 'gray44', 'BUTTON': ('white', '#004F00'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Black': {'BACKGROUND': 'black', 'TEXT': 'white', 'INPUT': 'gray30', + 'TEXT_INPUT': 'white', 'SCROLL': 'gray44', 'BUTTON': ('black', 'white'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Tan': {'BACKGROUND': '#fdf6e3', 'TEXT': '#268bd1', 'INPUT': '#eee8d5', + 'TEXT_INPUT': '#6c71c3', 'SCROLL': '#eee8d5', 'BUTTON': ('white', '#063542'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'TanBlue': {'BACKGROUND': '#e5dece', 'TEXT': '#063289', 'INPUT': '#f9f8f4', + 'TEXT_INPUT': '#242834', 'SCROLL': '#eee8d5', 'BUTTON': ('white', '#063289'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'DarkTanBlue': {'BACKGROUND': '#242834', 'TEXT': '#dfe6f8', 'INPUT': '#97755c', + 'TEXT_INPUT': 'white', 'SCROLL': '#a9afbb', 'BUTTON': ('white', '#063289'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'DarkAmber': {'BACKGROUND': '#2c2825', 'TEXT': '#fdcb52', 'INPUT': '#705e52', + 'TEXT_INPUT': '#fdcb52', 'SCROLL': '#705e52', 'BUTTON': ('black', '#fdcb52'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'DarkBlue': {'BACKGROUND': '#1a2835', 'TEXT': '#d1ecff', 'INPUT': '#335267', + 'TEXT_INPUT': '#acc2d0', 'SCROLL': '#1b6497', 'BUTTON': ('black', '#fafaf8'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Reds': {'BACKGROUND': '#280001', 'TEXT': 'white', 'INPUT': '#d8d584', + 'TEXT_INPUT': 'black', 'SCROLL': '#763e00', 'BUTTON': ('black', '#daad28'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'Green': {'BACKGROUND': '#82a459', 'TEXT': 'black', 'INPUT': '#d8d584', + 'TEXT_INPUT': 'black', 'SCROLL': '#e3ecf3', 'BUTTON': ('white', '#517239'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1, 'SLIDER_DEPTH': 0, + 'PROGRESS_DEPTH': 0}, + + 'LightGreen' :{'BACKGROUND' : '#B7CECE', 'TEXT': 'black', 'INPUT':'#FDFFF7','TEXT_INPUT' : 'black', 'SCROLL': '#FDFFF7','BUTTON': ('white', '#658268'), 'PROGRESS':DEFAULT_PROGRESS_BAR_COLOR, 'BORDER':1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BluePurple': {'BACKGROUND' : '#A5CADD', 'TEXT': '#6E266E', 'INPUT':'#E0F5FF','TEXT_INPUT' : 'black', 'SCROLL': '#E0F5FF','BUTTON': ('white', '#303952'),'PROGRESS':DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'Purple': {'BACKGROUND': '#B0AAC2', 'TEXT': 'black', 'INPUT': '#F2EFE8','SCROLL': '#F2EFE8','TEXT_INPUT' : 'black', + 'BUTTON': ('black', '#C2D4D8'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BlueMono': {'BACKGROUND': '#AAB6D3', 'TEXT': 'black', 'INPUT': '#F1F4FC','SCROLL': '#F1F4FC','TEXT_INPUT' : 'black', + 'BUTTON': ('white', '#7186C7'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'GreenMono': {'BACKGROUND': '#A8C1B4', 'TEXT': 'black', 'INPUT': '#DDE0DE', 'SCROLL': '#E3E3E3','TEXT_INPUT' : 'black', + 'BUTTON': ('white', '#6D9F85'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BrownBlue': {'BACKGROUND': '#64778d', 'TEXT': 'white', 'INPUT': '#f0f3f7', 'SCROLL': '#A6B2BE','TEXT_INPUT' : 'black', 'BUTTON': ('white', '#283b5b'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'BrightColors': {'BACKGROUND': '#b4ffb4', 'TEXT': 'black', 'INPUT': '#ffff64','SCROLL': '#ffb482','TEXT_INPUT' : 'black', 'BUTTON': ('black', '#ffa0dc'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'NeutralBlue': {'BACKGROUND': '#92aa9d', 'TEXT': 'black', 'INPUT': '#fcfff6', + 'SCROLL': '#fcfff6', 'TEXT_INPUT': 'black', 'BUTTON': ('black', '#d0dbbd'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'Kayak': {'BACKGROUND': '#a7ad7f', 'TEXT': 'black', 'INPUT': '#e6d3a8', + 'SCROLL': '#e6d3a8', 'TEXT_INPUT': 'black', 'BUTTON': ('white', '#5d907d'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'SandyBeach': {'BACKGROUND': '#efeccb', 'TEXT': '#012f2f', 'INPUT': '#e6d3a8', + 'SCROLL': '#e6d3a8', 'TEXT_INPUT': '#012f2f', 'BUTTON': ('white', '#046380'), + 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}, + + 'TealMono': {'BACKGROUND': '#a8cfdd', 'TEXT': 'black', 'INPUT': '#dfedf2','SCROLL': '#dfedf2', 'TEXT_INPUT' : 'black', 'BUTTON': ('white', '#183440'), 'PROGRESS': DEFAULT_PROGRESS_BAR_COLOR, 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0} + } + try: + colors = look_and_feel[index] + + SetOptions(background_color=colors['BACKGROUND'], + text_element_background_color=colors['BACKGROUND'], + element_background_color=colors['BACKGROUND'], + text_color=colors['TEXT'], + input_elements_background_color=colors['INPUT'], + button_color=colors['BUTTON'], + progress_meter_color=colors['PROGRESS'], + border_width=colors['BORDER'], + slider_border_width=colors['SLIDER_DEPTH'], + progress_meter_border_depth=colors['PROGRESS_DEPTH'], + scrollbar_color=(colors['SCROLL']), + element_text_color=colors['TEXT'], + input_text_color=colors['TEXT_INPUT']) + except: # most likely an index out of range + pass + + + + +# ============================== sprint ======# +# Is identical to the Scrolled Text Box # +# Provides a crude 'print' mechanism but in a # +# GUI environment # +# ============================================# +sprint=ScrolledTextBox + +# Converts an object's contents into a nice printable string. Great for dumping debug data +def ObjToStringSingleObj(obj): + if obj is None: + return 'None' + return str(obj.__class__) + '\n' + '\n'.join( + (repr(item) + ' = ' + repr(obj.__dict__[item]) for item in sorted(obj.__dict__))) + +def ObjToString(obj, extra=' '): + if obj is None: + return 'None' + return str(obj.__class__) + '\n' + '\n'.join( + (extra + (str(item) + ' = ' + + (ObjToString(obj.__dict__[item], extra + ' ') if hasattr(obj.__dict__[item], '__dict__') else str( + obj.__dict__[item]))) + for item in sorted(obj.__dict__))) + + +# ------------------------------------------------------------------------------------------------------------------ # +# ===================================== Upper PySimpleGUI ======================================================== # +# Pre-built dialog boxes for all your needs These are the "high level API calls # +# ------------------------------------------------------------------------------------------------------------------ # + +# ----------------------------------- The mighty Popup! ------------------------------------------------------------ # + +def Popup(*args, **kwargs): + """ + Popup - Display a popup box with as many parms as you wish to include + :param args: + :param button_color: + :param background_color: + :param text_color: + :param button_type: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + + # , button_color=None, background_color=None, text_color=None, button_type=, auto_close=, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None) + + if not args: + args_to_print = [''] + else: + args_to_print = args + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: button_type = kwargs['button_type'] + except: button_type = POPUP_BUTTONS_OK + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + + if line_width != None: + local_line_width = line_width + else: + local_line_width = MESSAGE_BOX_LINE_WIDTH + title = args_to_print[0] if args_to_print[0] is not None else 'None' + form = Window(title, auto_size_text=True, background_color=background_color, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, icon=icon, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) + max_line_total, total_lines = 0,0 + for message in args_to_print: + # fancy code to check if string and convert if not is not need. Just always convert to string :-) + # if not isinstance(message, str): message = str(message) + message = str(message) + if message.count('\n'): + message_wrapped = message + else: + message_wrapped = textwrap.fill(message, local_line_width) + message_wrapped_lines = message_wrapped.count('\n')+1 + longest_line_len = max([len(l) for l in message.split('\n')]) + width_used = min(longest_line_len, local_line_width) + max_line_total = max(max_line_total, width_used) + # height = _GetNumLinesNeeded(message, width_used) + height = message_wrapped_lines + form.AddRow(Text(message_wrapped, auto_size_text=True, text_color=text_color, background_color=background_color)) + total_lines += height + + pad = max_line_total-15 if max_line_total > 15 else 1 + pad =1 + if non_blocking: + PopupButton = DummyButton + else: + PopupButton = SimpleButton + # show either an OK or Yes/No depending on paramater + if button_type is POPUP_BUTTONS_YES_NO: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('Yes', button_color=button_color, focus=True, bind_return_key=True), PopupButton('No', button_color=button_color)) + elif button_type is POPUP_BUTTONS_CANCELLED: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('Cancelled', button_color=button_color, focus=True, bind_return_key=True)) + elif button_type is POPUP_BUTTONS_ERROR: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('Error', size=(6, 1), button_color=button_color, focus=True, bind_return_key=True)) + elif button_type is POPUP_BUTTONS_OK_CANCEL: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, text_color=text_color, background_color=background_color), PopupButton('OK', size=(5, 1), button_color=button_color, focus=True, bind_return_key=True), + PopupButton('Cancel', size=(5, 1), button_color=button_color)) + elif button_type is POPUP_BUTTONS_NO_BUTTONS: + pass + else: + form.AddRow(Text('', size=(pad, 1), auto_size_text=False, background_color=background_color), PopupButton('OK', size=(5, 1), button_color=button_color, focus=True, bind_return_key=True)) + + if non_blocking: + button, values = form.ReadNonBlocking() + else: + button, values = form.Show() + + return button + + + +# ============================== MsgBox============# +# Lazy function. Same as calling Popup with parms # +# This function WILL Disappear perhaps today # +# ==================================================# +# MsgBox is the legacy call and should not be used any longer +def MsgBox(*args): + raise DeprecationWarning('MsgBox is no longer supported... change your call to Popup') + + +# --------------------------- PopupNoButtons --------------------------- +def PopupNoButtons(*args, **kwargs): + """ + Show a Popup but without any buttons + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + # button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None), *args): + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + + Popup(button_color=button_color, background_color=background_color, text_color=text_color, button_type=POPUP_BUTTONS_NO_BUTTONS, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location, *args) + + +# --------------------------- PopupNonBlocking --------------------------- +def PopupNonBlocking(*args, **kwargs): + """ + Show Popup box and immediately return (does not block) + :param args: + :param button_type: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + + # button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None), + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: button_type = kwargs['button_type'] + except: button_type = POPUP_BUTTONS_OK + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = True + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + Popup(button_color=button_color, background_color=background_color, text_color=text_color, button_type=button_type, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location, *args) + + +PopupNoWait = PopupNonBlocking + + +# --------------------------- PopupNoTitlebar --------------------------- +def PopupNoTitlebar(*args, **kwargs): + """ + Display a Popup without a titlebar. Enables grab anywhere so you can move it + :param args: + :param button_type: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + + # button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, grab_anywhere=True, keep_on_top=False, location=(None,None), + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: button_type = kwargs['button_type'] + except: button_type = POPUP_BUTTONS_OK + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + Popup(button_color=button_color, background_color=background_color, text_color=text_color, button_type=button_type, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=True, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location,*args) + +PopupNoFrame = PopupNoTitlebar +PopupNoBorder = PopupNoTitlebar +PopupAnnoying = PopupNoTitlebar + + +# --------------------------- PopupAutoClose --------------------------- +def PopupAutoClose(*args, **kwargs): + """ + Popup that closes itself after some time period + :param args: + :param button_type: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + + # button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=True, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None,no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None), + + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: button_type = kwargs['button_type'] + except: button_type = POPUP_BUTTONS_OK + try: auto_close = kwargs['auto_close'] + except: auto_close = True + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + Popup(button_color=button_color, background_color=background_color, text_color=text_color, button_type=button_type, + auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon, line_width=line_width, + font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location,*args) + +PopupTimed = PopupAutoClose + +# --------------------------- PopupError --------------------------- +def PopupError(*args, **kwargs): + """ + Popup with colored button and 'Error' as button text + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + # button_color=DEFAULT_ERROR_BUTTON_COLOR, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None), + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = DEFAULT_ERROR_BUTTON_COLOR + try: text_color = kwargs['text_color'] + except: text_color = None + try: button_type = kwargs['button_type'] + except: button_type = POPUP_BUTTONS_OK + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + Popup(button_type=POPUP_BUTTONS_ERROR, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location,*args) + + +# --------------------------- PopupCancel --------------------------- +def PopupCancel(*args, **kwargs): + """ + Display Popup with "cancelled" button text + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + + # button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None), + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + Popup( button_type=POPUP_BUTTONS_CANCELLED, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location, *args) + +# --------------------------- PopupOK --------------------------- +def PopupOK(*args, **kwargs): + """ + Display Popup with OK button only + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: + """ + + # button_color = None, background_color = None, text_color = None, auto_close = False, auto_close_duration = None, non_blocking = False, icon = DEFAULT_WINDOW_ICON, line_width = None, font = None, no_titlebar = False, grab_anywhere = True, keep_on_top = False, location = ( None, None), + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + Popup(button_type=POPUP_BUTTONS_OK, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location,*args) + +# --------------------------- PopupOKCancel --------------------------- +def PopupOKCancel(*args, **kwargs): + """ + Display popup with OK and Cancel buttons + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: OK, Cancel or None + """ + + # button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None), + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + return Popup(button_type=POPUP_BUTTONS_OK_CANCEL, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location,*args) + +# --------------------------- PopupYesNo --------------------------- +def PopupYesNo(*args, **kwargs): + """ + Display Popup with Yes and No buttons + :param args: + :param button_color: + :param background_color: + :param text_color: + :param auto_close: + :param auto_close_duration: + :param non_blocking: + :param icon: + :param line_width: + :param font: + :param no_titlebar: + :param grab_anywhere: + :param keep_on_top: + :param location: + :return: Yes, No or None + """ + + # button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=True, keep_on_top=False, location=(None,None), + + try: button_color = kwargs['button_color'] + except: button_color = None + try: background_color = kwargs['background_color'] + except: background_color = None + try: text_color = kwargs['text_color'] + except: text_color = None + try: auto_close = kwargs['auto_close'] + except: auto_close = False + try: auto_close_duration = kwargs['auto_close_duration'] + except: auto_close_duration = None + try: non_blocking = kwargs['non_blocking'] + except: non_blocking = False + try: icon = kwargs['icon'] + except: icon = DEFAULT_WINDOW_ICON + try: line_width = kwargs['line_width'] + except: line_width = None + try: font = kwargs['font'] + except: font = None + try: no_titlebar = kwargs['no_titlebar'] + except: no_titlebar = False + try: grab_anywhere = kwargs['grab_anywhere'] + except: grab_anywhere = None + try: keep_on_top = kwargs['keep_on_top'] + except: keep_on_top = False + try: location = kwargs['location'] + except: location = (None, None) + + return Popup(button_type=POPUP_BUTTONS_YES_NO, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location,*args) + + +def main(): + window = Window('Demo window..') + window_rows = [[Text('You are running the PySimpleGUI.py file itself')], + [Text('You should be importing it rather than running it', size=(50,2))], + [Text('Here is your sample input window....')], + [Text('Source Folder', size=(15, 1), justification='right'), InputText('Source', focus=True),FolderBrowse()], + [Text('Destination Folder', size=(15, 1), justification='right'), InputText('Dest'), FolderBrowse()], + [Ok(), Cancel()]] + + button, (source, dest) = window.LayoutAndRead(window_rows) + + +if __name__ == '__main__': + main() + exit(69) \ No newline at end of file diff --git a/PySimpleGUI_Logo_640.png b/PySimpleGUI_Logo_640.png new file mode 100644 index 000000000..0de414a32 Binary files /dev/null and b/PySimpleGUI_Logo_640.png differ diff --git a/default_icon.ico b/default_icon.ico new file mode 100644 index 000000000..1a41525ec Binary files /dev/null and b/default_icon.ico differ diff --git a/docs/PySimpleGUI Cookbook Table.pdf b/docs/PySimpleGUI Cookbook Table.pdf new file mode 100644 index 000000000..af0d81d5d Binary files /dev/null and b/docs/PySimpleGUI Cookbook Table.pdf differ diff --git a/docs/cookbook.md b/docs/cookbook.md new file mode 100644 index 000000000..07aa7f5ab --- /dev/null +++ b/docs/cookbook.md @@ -0,0 +1,1267 @@ + + + +# The PySimpleGUI Cookbook + + +You'll find that starting with a Recipe will give you a big jump-start on creating your custom GUI. Copy and paste one of these Recipes and modify it to match your requirements. Study them to get an idea of what design patterns to follow. + +The Recipes in this Cookbook all assume you're running on a Python3 machine. If you are running Python 2.7 then your code will differ by 2 character. Replace the import statement: + + import PySimpleGUI as sg + +with + + import PySimpleGUI27 as sg + +There is a short section in the Readme with instruction on installing PySimpleGUI + + +## Simple Data Entry - Return Values As List +Same GUI screen except the return values are in a list instead of a dictionary and doesn't have initial values. + +![super simple 2](https://user-images.githubusercontent.com/13696193/43934091-8100e29a-9c1b-11e8-8d0a-9bd2d13e6d8e.jpg) + + import PySimpleGUI as sg + + # Very basic window. Return values as a list + + layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText()], + [sg.Text('Address', size=(15, 1)), sg.InputText()], + [sg.Text('Phone', size=(15, 1)), sg.InputText()], + [sg.Submit(), sg.Cancel()] + ] + + window = sg.Window('Simple data entry window').Layout(layout) + button, values = window.Read() + + print(button, values[0], values[1], values[2]) + +## Simple data entry - Return Values As Dictionary +A simple GUI with default values. Results returned in a dictionary. + +![super simple 2](https://user-images.githubusercontent.com/13696193/43934091-8100e29a-9c1b-11e8-8d0a-9bd2d13e6d8e.jpg) + + import PySimpleGUI as sg + + # Very basic window. Return values as a dictionary + + layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText('name', key='name')], + [sg.Text('Address', size=(15, 1)), sg.InputText('address', key='address')], + [sg.Text('Phone', size=(15, 1)), sg.InputText('phone', key='phone')], + [sg.Submit(), sg.Cancel()] + ] + + window = sg.Window('Simple data entry GUI').Layout(layout) + + button, values = window.Read() + + print(button, values['name'], values['address'], values['phone']) + +--------------------- + + + +----------- +## Simple File Browse +Browse for a filename that is populated into the input field. + +![simple file browse](https://user-images.githubusercontent.com/13696193/43934539-d8bd9490-9c1d-11e8-927f-98b523776fcb.jpg) + + import PySimpleGUI as sg + + GUI_rows = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')], + [sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + + (button, (source_filename,)) = sg.Window('SHA-1 & 256 Hash').Layout(GUI_rows).Read() + + print(button, source_filename) + +-------------------------- +## Add GUI to Front-End of Script +Quickly add a GUI allowing the user to browse for a filename if a filename is not supplied on the command line using this 1-line GUI. It's the best of both worlds. + +![script front-end](https://user-images.githubusercontent.com/13696193/44756573-39e9c380-aaf9-11e8-97b4-6679f9f5bd46.jpg) + + + import PySimpleGUI as sg + import sys + + if len(sys.argv) == 1: + button, (fname,) = sg.Window('My Script').Layout([[sg.Text('Document to open')], + [sg.In(), sg.FileBrowse()], + [sg.Open(), sg.Cancel()]]).Read() + else: + fname = sys.argv[1] + + if not fname: + sg.Popup("Cancel", "No filename supplied") + raise SystemExit("Cancelling: no filename supplied") + print(button, fname) + + + +-------------- + +## Compare 2 Files + +Browse to get 2 file names that can be then compared. + +![compare 2 files](https://user-images.githubusercontent.com/13696193/43934659-60dc5fbe-9c1e-11e8-8d2b-07c0e3b61892.jpg) + + import PySimpleGUI as sg + + gui_rows = [[sg.Text('Enter 2 files to comare')], + [sg.Text('File 1', size=(8, 1)), sg.InputText(), sg.FileBrowse()], + [sg.Text('File 2', size=(8, 1)), sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('File Compare').Layout(gui_rows) + + button, values = window.Read() + + print(button, values) + +--------------- +## Nearly All Widgets with Green Color Theme +Example of nearly all of the widgets in a single window. Uses a customized color scheme. + +![latest everything bagel](https://user-images.githubusercontent.com/13696193/45920376-22d89000-be71-11e8-8ac4-640f011f84d0.jpg) + + + + #!/usr/bin/env Python3 + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('GreenTan') + + # ------ Menu Definition ------ # + menu_def = [['File', ['Open', 'Save', 'Exit', 'Properties']], + ['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ], + ['Help', 'About...'], ] + + # ------ Column Definition ------ # + column1 = [[sg.Text('Column 1', background_color='#F7F3EC', 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'), initial_value='Spin Box 2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] + + layout = [ + [sg.Menu(menu_def, tearoff=True)], + [sg.Text('All graphic widgets in one window!', size=(30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text')], + [sg.Frame(layout=[ + [sg.Checkbox('Checkbox', size=(10,1)), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10,1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), + sg.Multiline(default_text='A second multi-line', size=(35, 3))], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], + [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), + sg.Frame('Labelled Group',[[ + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), + sg.Column(column1, background_color='#F7F3EC')]])], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder'), sg.FolderBrowse()], + [sg.Submit(tooltip='Click to submit this window'), sg.Cancel()] + ] + + + window = sg.Window('Everything bagel', default_element_size=(40, 1), grab_anywhere=False).Layout(layout) + + button, values = window.Read() + + sg.Popup('Title', + 'The results of the window.', + 'The button clicked was "{}"'.format(button), + 'The values are', values) + +------------- + + + + +## Non-Blocking Window With Periodic Update +An async Window that has a button read loop. A Text Element is updated periodically with a running timer. Note that `value` is checked for None which indicates the window was closed using X. + +![non-blocking](https://user-images.githubusercontent.com/13696193/43955295-70f6ac48-9c6d-11e8-8ea2-e6729ba9330c.jpg) + + + import PySimpleGUI as sg + import time + + gui_rows = [[sg.Text('Stopwatch', size=(20, 2), justification='center')], + [sg.Text('', size=(10, 2), font=('Helvetica', 20), justification='center', key='output')], + [sg.T(' ' * 5), sg.ReadButton('Start/Stop', focus=True), sg.Quit()]] + + window = sg.Window('Running Timer').Layout(gui_rows) + + timer_running = True + i = 0 + # Event Loop + while True: + i += 1 * (timer_running is True) + button, values = window.ReadNonBlocking() + + if values is None or button == 'Quit': # if user closed the window using X or clicked Quit button + break + elif button == 'Start/Stop': + timer_running = not timer_running + + window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100)) + time.sleep(.01) + +-------- + +## Callback Function Simulation +The architecture of some programs works better with button callbacks instead of handling in-line. While button callbacks are part of the PySimpleGUI implementation, they are not directly exposed to the caller. The way to get the same result as callbacks is to simulate them with a recipe like this one. + +![button callback 2](https://user-images.githubusercontent.com/13696193/43955588-e139ddc6-9c6e-11e8-8c78-c1c226b8d9b1.jpg) + + import PySimpleGUI as sg + + # This design pattern simulates button callbacks + # Note that callbacks are NOT a part of the package's interface to the + # caller intentionally. The underlying implementation actually does use + # tkinter callbacks. They are simply hidden from the user. + + # The callback functions + def button1(): + print('Button 1 callback') + + def button2(): + print('Button 2 callback') + + + # Layout the design of the GUI + layout = [[sg.Text('Please click a button', auto_size_text=True)], + [sg.ReadButton('1'), sg.ReadButton('2'), sg.Quit()]] + + # Show the Window to the user + window = sg.Window('Button callback example').Layout(layout) + + # Event loop. Read buttons, make callbacks + while True: + # Read the Window + button, value = window.Read() + # Take appropriate action based on button + if button == '1': + button1() + elif button == '2': + button2() + elif button =='Quit' or button is None: + break + + # All done! + sg.PopupOK('Done') + +----- +## Realtime Buttons (Good For Raspberry Pi) +This recipe implements a remote control interface for a robot. There are 4 directions, forward, reverse, left, right. When a button is clicked, PySimpleGUI immediately returns button events for as long as the buttons is held down. When released, the button events stop. This is an async/non-blocking window. + +![robot control](https://user-images.githubusercontent.com/13696193/44006710-d227f23e-9e56-11e8-89a3-2be5b2726199.jpg) + + import PySimpleGUI as sg + + + gui_rows = [[sg.Text('Robotics Remote Control')], + [sg.T(' ' * 10), sg.RealtimeButton('Forward')], + [sg.RealtimeButton('Left'), sg.T(' ' * 15), sg.RealtimeButton('Right')], + [sg.T(' ' * 10), sg.RealtimeButton('Reverse')], + [sg.T('')], + [sg.Quit(button_color=('black', 'orange'))] + ] + + window = sg.Window('Robotics Remote Control', auto_size_text=True).Layout(gui_rows) + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your window every now and then or + # else it won't refresh. + # + # your program's main loop + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + if button is not None: + print(button) + if button == 'Quit' or values is None: + break + + window.CloseNonBlocking() # Don't forget to close your window! + +--------- + +## OneLineProgressMeter + +This recipe shows just how easy it is to add a progress meter to your code. + +![onelineprogressmeter](https://user-images.githubusercontent.com/13696193/45589254-bd285900-b8f0-11e8-9122-b43f06bf074d.jpg) + + + import PySimpleGUI as sg + + for i in range(1000): + sg.OneLineProgressMeter('One Line Meter Example', i+1, 1000, 'key') + + + +----- +## Button Graphics (Media Player) +Buttons can have PNG of GIF images on them. This Media Player recipe requires 4 images in order to function correctly. The background is set to the same color as the button background so that they blend together. + +![media player](https://user-images.githubusercontent.com/13696193/43958418-5dd133f2-9c79-11e8-9432-0a67007e85ac.jpg) + + import PySimpleGUI as sg + + background = '#F0F0F0' + # Set the backgrounds the same as the background on the buttons + sg.SetOptions(background_color=background, element_background_color=background) + # Images are located in a subfolder in the Demo Media Player.py folder + image_pause = './ButtonGraphics/Pause.png' + image_restart = './ButtonGraphics/Restart.png' + image_next = './ButtonGraphics/Next.png' + image_exit = './ButtonGraphics/Exit.png' + + # define layout of the rows + layout = [[sg.Text('Media File Player', size=(17, 1), font=("Helvetica", 25))], + [sg.Text('', size=(15, 2), font=("Helvetica", 14), key='output')], + [sg.ReadButton('Restart Song', button_color=(background, background), + image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.ReadButton('Pause', button_color=(background, background), + image_filename=image_pause, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.ReadButton('Next', button_color=(background, background), + image_filename=image_next, image_size=(50, 50), image_subsample=2, border_width=0), + sg.Text(' ' * 2), + sg.Text(' ' * 2), sg.Button('Exit', button_color=(background, background), + image_filename=image_exit, image_size=(50, 50), image_subsample=2, + border_width=0)], + [sg.Text('_' * 30)], + [sg.Text(' ' * 30)], + [ + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', + font=("Helvetica", 15)), + sg.Text(' ' * 2), + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', + font=("Helvetica", 15)), + sg.Text(' ' * 8), + sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', + font=("Helvetica", 15))], + [sg.Text('Bass', font=("Helvetica", 15), size=(6, 1)), + sg.Text('Treble', font=("Helvetica", 15), size=(10, 1)), + sg.Text('Volume', font=("Helvetica", 15), size=(7, 1))] + ] + + window = sg.Window('Media File Player', auto_size_text=True, default_element_size=(20, 1), + font=("Helvetica", 25)).Layout(layout) + # Our event loop + while (True): + # Read the window (this call will not block) + button, values = window.ReadNonBlocking() + if button == 'Exit' or values is None: + break + # If a button was pressed, display it on the GUI by updating the text element + if button: + window.FindElement('output').Update(button) + +---- +## Script Launcher - Persistent Window +This Window doesn't close after button clicks. To achieve this the buttons are specified as `sg.ReadButton` instead of `sg.Button`. The exception to this is the EXIT button. Clicking it will close the window. This program will run commands and display the output in the scrollable window. + +![launcher 2](https://user-images.githubusercontent.com/13696193/43958519-b30af218-9c79-11e8-88da-fadc69da818c.jpg) + + import PySimpleGUI as sg + import subprocess + + # Please check Demo programs for better examples of launchers + def ExecuteCommandSubprocess(command, *args): + try: + sp = subprocess.Popen([command, *args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = sp.communicate() + if out: + print(out.decode("utf-8")) + if err: + print(err.decode("utf-8")) + except: + pass + + + layout = [ + [sg.Text('Script output....', size=(40, 1))], + [sg.Output(size=(88, 20))], + [sg.ReadButton('script1'), sg.ReadButton('script2'), sg.Button('EXIT')], + [sg.Text('Manual command', size=(15, 1)), sg.InputText(focus=True), sg.ReadButton('Run', bind_return_key=True)] + ] + + + window = sg.Window('Script launcher').Layout(layout) + + # ---===--- Loop taking in user input and using it to call scripts --- # + + while True: + (button, value) = window.Read() + if button == 'EXIT' or button is None: + break # exit button clicked + if button == 'script1': + ExecuteCommandSubprocess('pip', 'list') + elif button == 'script2': + ExecuteCommandSubprocess('python', '--version') + elif button == 'Run': + ExecuteCommandSubprocess(value[0]) + +---- +## Machine Learning GUI +A standard non-blocking GUI with lots of inputs. + +![machine learning green](https://user-images.githubusercontent.com/13696193/43979000-408b77ba-9cb7-11e8-9ffd-24c156767532.jpg) + + import PySimpleGUI as sg + + # Green & tan color scheme + sg.ChangeLookAndFeel('GreenTan') + + sg.SetOptions(text_justification='right') + + layout = [[sg.Text('Machine Learning Command Line Parameters', font=('Helvetica', 16))], + [sg.Text('Passes', size=(15, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)), + sg.Text('Steps', size=(18, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1))], + [sg.Text('ooa', size=(15, 1)), sg.In(default_text='6', size=(10, 1)), sg.Text('nn', size=(15, 1)), + sg.In(default_text='10', size=(10, 1))], + [sg.Text('q', size=(15, 1)), sg.In(default_text='ff', size=(10, 1)), sg.Text('ngram', size=(15, 1)), + sg.In(default_text='5', size=(10, 1))], + [sg.Text('l', size=(15, 1)), sg.In(default_text='0.4', size=(10, 1)), sg.Text('Layers', size=(15, 1)), + sg.Drop(values=('BatchNorm', 'other'), auto_size_text=True)], + [sg.Text('_' * 100, size=(65, 1))], + [sg.Text('Flags', font=('Helvetica', 15), justification='left')], + [sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1))], + [sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True)], + [sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1))], + [sg.Text('_' * 100, size=(65, 1))], + [sg.Text('Loss Functions', font=('Helvetica', 15), justification='left')], + [sg.Radio('Cross-Entropy', 'loss', size=(12, 1)), sg.Radio('Logistic', 'loss', default=True, size=(12, 1))], + [sg.Radio('Hinge', 'loss', size=(12, 1)), sg.Radio('Huber', 'loss', size=(12, 1))], + [sg.Radio('Kullerback', 'loss', size=(12, 1)), sg.Radio('MAE(L1)', 'loss', size=(12, 1))], + [sg.Radio('MSE(L2)', 'loss', size=(12, 1)), sg.Radio('MB(L0)', 'loss', size=(12, 1))], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('Machine Learning Front End', font=("Helvetica", 12)).Layout(layout) + + button, values = window.Read() + +------- +## Custom Progress Meter / Progress Bar +Perhaps you don't want all the statistics that the EasyProgressMeter provides and want to create your own progress bar. Use this recipe to do just that. + +![custom progress meter](https://user-images.githubusercontent.com/13696193/43982958-3393b23e-9cc6-11e8-8b49-e7f4890cbc4b.jpg) + + + import PySimpleGUI as sg + + # layout the Window + layout = [[sg.Text('A custom progress meter')], + [sg.ProgressBar(10000, orientation='h', size=(20, 20), key='progbar')], + [sg.Cancel()]] + + # create the Window + window = sg.Window('Custom Progress Meter').Layout(layout) + # loop that would normally do something useful + for i in range(10000): + # check to see if the cancel button was clicked and exit loop if clicked + button, values = window.ReadNonBlocking() + if button == 'Cancel' or values == None: + break + # update bar with loop value +1 so that bar eventually reaches the maximum + window.FindElement('progbar').UpdateBar(i + 1) + # done with loop... need to destroy the window as it's still open + window.CloseNonBlocking() + + + ---- + +## The One-Line GUI + +For those of you into super-compact code, a complete customized GUI can be specified, shown, and received the results using a single line of Python code. + + +![simple](https://user-images.githubusercontent.com/13696193/44227935-ecb53b80-a161-11e8-968b-b3f963404dec.jpg) + + +Instead of + + import PySimpleGUI as sg + + layout = [[sg.Text('Filename')], + [sg.Input(), sg.FileBrowse()], + [sg.OK(), sg.Cancel()]] + + button, (number,) = sg.Window('Get filename example').Layout(layout).Read() + +you can write this line of code for the exact same result (OK, two lines with the import): + + import PySimpleGUI as sg + + button, (filename,) = sg.Window('Get filename example').Layout( + [[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()]]).Read() + +-------------------- +## Multiple Columns + +A Column is required when you have a tall element to the left of smaller elements. + +In this example, there is a Listbox on the left that is 3 rows high. To the right of it are 3 single rows of text and input. These 3 rows are in a Column Element. + +To make it easier to see the Column in the window, the Column background has been shaded blue. The code is wordier than normal due to the blue shading. Each element in the column needs to have the color set to match blue background. + +![cookbook columns](https://user-images.githubusercontent.com/13696193/45309948-f6c52280-b4f2-11e8-8691-a45fa0e06c50.jpg) + + + + import PySimpleGUI as sg + + # Demo of how columns work + # GUI has on row 1 a vertical slider followed by a COLUMN with 7 rows + # Prior to the Column element, this layout was not possible + # Columns layouts look identical to GUI layouts, they are a list of lists of elements. + + sg.ChangeLookAndFeel('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 3', text_color='white', background_color='blue'), sg.Input('col input 2')]] + + layout = [[sg.Listbox(values=('Listbox Item 1', 'Listbox Item 2', 'Listbox Item 3'), select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20,3)), sg.Column(col, background_color='blue')], + [sg.Input('Last input')], + [sg.OK()]] + + # Display the Window and get values + + button, values = sg.Window('Compact 1-line Window with column').Layout(layout).Read() + + sg.Popup(button, values, line_width=200) + + +## Persistent Window With Text Element Updates + +This simple program keep a window open, taking input values until the user terminates the program using the "X" button. + +![math game](https://user-images.githubusercontent.com/13696193/44537842-c9444080-a6cd-11e8-94bc-6cdf1b765dd8.jpg) + + + + import PySimpleGUI as sg + + layout = [ [sg.Txt('Enter values to calculate')], + [sg.In(size=(8,1), key='numerator')], + [sg.Txt('_' * 10)], + [sg.In(size=(8,1), key='denominator')], + [sg.Txt('', size=(8,1), key='output') ], + [sg.ReadButton('Calculate', bind_return_key=True)]] + + window = sg.Window('Math').Layout(layout) + + while True: + button, values = window.Read() + + if button is not None: + try: + numerator = float(values['numerator']) + denominator = float(values['denominator']) + calc = numerator / denominator + except: + calc = 'Invalid' + + window.FindElement('output').Update(calc) + else: + break + + + +## tkinter Canvas Widget + +The Canvas Element is one of the few tkinter objects that are directly accessible. The tkinter Canvas widget itself can be retrieved from a Canvas Element like this: + + can = sg.Canvas(size=(100,100)) + tkcanvas = can.TKCanvas + tkcanvas.create_oval(50, 50, 100, 100) + +While it's fun to scribble on a Canvas Widget, try Graph Element makes it a downright pleasant experience. You do not have to worry about the tkinter coordinate system and can instead work in your own coordinate system. + + +![canvas](https://user-images.githubusercontent.com/13696193/44632429-5266ac00-a948-11e8-9ee0-664103c40178.jpg) + + + import PySimpleGUI as sg + + layout = [ + [sg.Canvas(size=(100, 100), background_color='red', key= 'canvas')], + [sg.T('Change circle color to:'), sg.ReadButton('Red'), sg.ReadButton('Blue')] + ] + + window = sg.Window('Canvas test') + window.Layout(layout) + window.Finalize() + + canvas = window.FindElement('canvas') + cir = canvas.TKCanvas.create_oval(50, 50, 100, 100) + + while True: + button, values = window.Read() + if button is None: + break + if button == 'Blue': + canvas.TKCanvas.itemconfig(cir, fill="Blue") + elif button == 'Red': + canvas.TKCanvas.itemconfig(cir, fill="Red") + +## Graph Element - drawing circle, rectangle, etc, objects + +Just like you can draw on a tkinter widget, you can also draw on a Graph Element. Graph Elements are easier on the programmer as you get to work in your own coordinate system. + +![graph recipe](https://user-images.githubusercontent.com/13696193/45920640-751bb000-be75-11e8-9530-45b71cbae07d.jpg) + + + import PySimpleGUI as sg + + layout = [ + [sg.Graph(canvas_size=(400, 400), graph_bottom_left=(0,0), graph_top_right=(400, 400), background_color='red', key='graph')], + [sg.T('Change circle color to:'), sg.ReadButton('Red'), sg.ReadButton('Blue'), sg.ReadButton('Move')] + ] + + window = sg.Window('Graph test') + window.Layout(layout) + window.Finalize() + + graph = window.FindElement('graph') + circle = graph.DrawCircle((75,75), 25, fill_color='black',line_color='white') + point = graph.DrawPoint((75,75), 10, color='green') + oval = graph.DrawOval((25,300), (100,280), fill_color='purple', line_color='purple' ) + rectangle = graph.DrawRectangle((25,300), (100,280), line_color='purple' ) + line = graph.DrawLine((0,0), (100,100)) + + while True: + button, values = window.Read() + if button is None: + break + if button is 'Blue': + graph.TKCanvas.itemconfig(circle, fill = "Blue") + elif button is 'Red': + graph.TKCanvas.itemconfig(circle, fill = "Red") + elif button is 'Move': + graph.MoveFigure(point, 10,10) + graph.MoveFigure(circle, 10,10) + graph.MoveFigure(oval, 10,10) + graph.MoveFigure(rectangle, 10,10) + + +## Keypad Touchscreen Entry - Input Element Update + +This Recipe implements a Raspberry Pi touchscreen based keypad entry. As the digits are entered using the buttons, the Input Element above it is updated with the input digits. +There are a number of features used in this Recipe including: +* Default Element Size +* auto_size_buttons +* ReadButton +* Dictionary Return values +* Update of Elements in window (Input, Text) +* do_not_clear of Input Elements + + +![keypad 2](https://user-images.githubusercontent.com/13696193/44640891-57504d80-a992-11e8-93f4-4e97e586505e.jpg) + + + + import PySimpleGUI as sg + + # Demonstrates a number of PySimpleGUI features including: + # Default element size + # auto_size_buttons + # ReadButton + # Dictionary return values + # Update of elements in window (Text, Input) + # do_not_clear of Input elements + + layout = [[sg.Text('Enter Your Passcode')], + [sg.Input(size=(10, 1), do_not_clear=True, justification='right', key='input')], + [sg.ReadButton('1'), sg.ReadButton('2'), sg.ReadButton('3')], + [sg.ReadButton('4'), sg.ReadButton('5'), sg.ReadButton('6')], + [sg.ReadButton('7'), sg.ReadButton('8'), sg.ReadButton('9')], + [sg.ReadButton('Submit'), sg.ReadButton('0'), sg.ReadButton('Clear')], + [sg.Text('', size=(15, 1), font=('Helvetica', 18), text_color='red', key='out')], + ] + + window = sg.Window('Keypad', default_button_element_size=(5, 2), auto_size_buttons=False, grab_anywhere=False).Layout(layout) + + # Loop forever reading the window's values, updating the Input field + keys_entered = '' + while True: + button, values = window.Read() # read the window + if button is None: # if the X button clicked, just exit + break + if button == 'Clear': # clear keys if clear button + keys_entered = '' + elif button in '1234567890': + keys_entered = values['input'] # get what's been entered so far + keys_entered += button # add the new digit + elif button == 'Submit': + keys_entered = values['input'] + window.FindElement('out').Update(keys_entered) # output the final string + + window.FindElement('input').Update(keys_entered) # change the window to reflect current key string + +## Animated Matplotlib Graph + +Use the Canvas Element to create an animated graph. The code is a bit tricky to follow, but if you know Matplotlib then this recipe shouldn't be too difficult to copy and modify. + +![animated matplotlib](https://user-images.githubusercontent.com/13696193/44640937-91b9ea80-a992-11e8-9c1c-85ae74013679.jpg) + + + from tkinter import * + from random import randint + import PySimpleGUI as g + from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureCanvasAgg + from matplotlib.figure import Figure + import matplotlib.backends.tkagg as tkagg + import tkinter as Tk + + + fig = Figure() + + ax = fig.add_subplot(111) + ax.set_xlabel("X axis") + ax.set_ylabel("Y axis") + ax.grid() + + layout = [[g.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')], + [g.Canvas(size=(640, 480), key='canvas')], + [g.ReadButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]] + + # create the window and show it without the plot + + + window = g.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout) + window.Finalize() # needed to access the canvas element prior to reading the window + + canvas_elem = window.FindElement('canvas') + + graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas) + canvas = canvas_elem.TKCanvas + + dpts = [randint(0, 10) for x in range(10000)] + # Our event loop + for i in range(len(dpts)): + button, values = window.ReadNonBlocking() + if button == 'Exit' or values is None: + exit(69) + + ax.cla() + ax.grid() + + ax.plot(range(20), dpts[i:i + 20], color='purple') + graph.draw() + figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds + figure_w, figure_h = int(figure_w), int(figure_h) + photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) + + canvas.create_image(640 / 2, 480 / 2, image=photo) + + figure_canvas_agg = FigureCanvasAgg(fig) + figure_canvas_agg.draw() + + tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) + + + +## Tight Layout with Button States + +Saw this example layout written in tkinter and liked it so much I duplicated the interface. It's "tight", clean, and has a nice dark look and feel. + +This Recipe also contains code that implements the button interactions so that you'll have a template to build from. + +In other GUI frameworks this program would be most likely "event driven" with callback functions being used to communicate button events. The "event loop" would be handled by the GUI engine. If code already existed that used a call-back mechanism, the loop in the example code below could simply call these callback functions directly based on the button text it receives in the window.Read call. + +![timemanagement](https://user-images.githubusercontent.com/13696193/44996818-0f27c100-af78-11e8-8836-9ef6164efe3b.jpg) + + + import PySimpleGUI as sg + """ + Demonstrates using a "tight" layout with a Dark theme. + Shows how button states can be controlled by a user application. The program manages the disabled/enabled + states for buttons and changes the text color to show greyed-out (disabled) buttons + """ + + sg.ChangeLookAndFeel('Dark') + sg.SetOptions(element_padding=(0,0)) + + layout = [[sg.T('User:', pad=((3,0),0)), sg.OptionMenu(values = ('User 1', 'User 2'), size=(20,1)), sg.T('0', size=(8,1))], + [sg.T('Customer:', pad=((3,0),0)), sg.OptionMenu(values=('Customer 1', 'Customer 2'), size=(20,1)), sg.T('1', size=(8,1))], + [sg.T('Notes:', pad=((3,0),0)), sg.In(size=(44,1), background_color='white', text_color='black')], + [sg.ReadButton('Start', button_color=('white', 'black'), key='Start'), + sg.ReadButton('Stop', button_color=('white', 'black'), key='Stop'), + sg.ReadButton('Reset', button_color=('white', 'firebrick3'), key='Reset'), + sg.ReadButton('Submit', button_color=('white', 'springgreen4'), key='Submit')] + ] + + window = sg.Window("Time Tracker", default_element_size=(12,1), text_justification='r', auto_size_text=False, auto_size_buttons=False, + default_button_element_size=(12,1)) + window.Layout(layout) + window.Finalize() + window.FindElement('Stop').Update(disabled=True) + window.FindElement('Reset').Update(disabled=True) + window.FindElement('Submit').Update(disabled=True) + recording = have_data = False + while True: + button, values = window.Read() + print(button) + if button is None: + exit(69) + if button is 'Start': + window.FindElement('Start').Update(disabled=True) + window.FindElement('Stop').Update(disabled=False) + window.FindElement('Reset').Update(disabled=False) + window.FindElement('Submit').Update(disabled=True) + recording = True + elif button is 'Stop' and recording: + window.FindElement('Stop').Update(disabled=True) + window.FindElement('Start').Update(disabled=False) + window.FindElement('Submit').Update(disabled=False) + recording = False + have_data = True + elif button is 'Reset': + window.FindElement('Stop').Update(disabled=True) + window.FindElement('Start').Update(disabled=False) + window.FindElement('Submit').Update(disabled=True) + window.FindElement('Reset').Update(disabled=False) + recording = False + have_data = False + elif button is 'Submit' and have_data: + window.FindElement('Stop').Update(disabled=True) + window.FindElement('Start').Update(disabled=False) + window.FindElement('Submit').Update(disabled=True) + window.FindElement('Reset').Update(disabled=False) + recording = False + +## Password Protection For Scripts + +You get 2 scripts in one. + +Use the upper half to generate your hash code. Then paste it into the code in the lower half. Copy and paste lower 1/2 into your code to get password protection for your script without putting the password into your source code. + +![password entry](https://user-images.githubusercontent.com/13696193/45129440-ab58f000-b151-11e8-8ebe-e519a50b3ead.jpg) + +![password hash](https://user-images.githubusercontent.com/13696193/45129441-ab58f000-b151-11e8-8a46-c2789bb7824e.jpg) + + import PySimpleGUI as sg + import hashlib + + ''' + Create a secure login for your scripts without having to include your password in the program. Create an SHA1 hash code for your password using the GUI. Paste into variable in final program + 1. Choose a password + 2. Generate a hash code for your chosen password by running program and entering 'gui' as the password + 3. Type password into the GUI + 4. Copy and paste hash code Window GUI into variable named login_password_hash + 5. Run program again and test your login! + ''' + + # Use this GUI to get your password's hash code + def HashGeneratorGUI(): + layout = [[sg.T('Password Hash Generator', size=(30,1), font='Any 15')], + [sg.T('Password'), sg.In(key='password')], + [sg.T('SHA Hash'), sg.In('', size=(40,1), key='hash')], + ] + + window = sg.Window('SHA Generator', auto_size_text=False, default_element_size=(10,1), + text_justification='r', return_keyboard_events=True, grab_anywhere=False).Layout(layout) + + + while True: + button, values = window.Read() + if button is None: + exit(69) + + password = values['password'] + try: + password_utf = password.encode('utf-8') + sha1hash = hashlib.sha1() + sha1hash.update(password_utf) + password_hash = sha1hash.hexdigest() + window.FindElement('hash').Update(password_hash) + except: + pass + + # ----------------------------- Paste this code into your program / script ----------------------------- + # determine if a password matches the secret password by comparing SHA1 hash codes + def PasswordMatches(password, hash): + password_utf = password.encode('utf-8') + sha1hash = hashlib.sha1() + sha1hash.update(password_utf) + password_hash = sha1hash.hexdigest() + if password_hash == hash: + return True + else: + return False + + login_password_hash = '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8' + password = sg.PopupGetText('Password', password_char='*') + if password == 'gui': # Remove when pasting into your program + HashGeneratorGUI() # Remove when pasting into your program + exit(69) # Remove when pasting into your program + if PasswordMatches(password, login_password_hash): + print('Login SUCCESSFUL') + else: + print('Login FAILED!!') + + +## Desktop Floating Toolbar + +#### Hiding your windows commmand window +For this and the Time & CPU Widgets you may wish to consider using a tool or technique that will hide your Windows Command Prompt window. I recommend the techniques found on this site: + +[http://www.robvanderwoude.com/battech_hideconsole.php](http://www.robvanderwoude.com/battech_hideconsole.php) + +At the moment I'm using the technique that involves wscript and a script named RunNHide.vbs. They are working beautifully. I'm using a hotkey program and launch by using this script with the command "python.exe insert_program_here.py". I guess the next widget should be one that shows all the programs launched this way so you can kill any bad ones. If you don't properly catch the exit button on your window then your while loop is going to keep on working while your window is no longer there so be careful in your code to always have exit explicitly handled. + + +### Floating toolbar + +This is a cool one! (Sorry about the code pastes... I'm working in it) + +Impress your friends at what a tool-wizard you are by popping a custom toolbar that you keep in the corner of your screen. It stays on top of all your other windows. + + + + +![toolbar gray](https://user-images.githubusercontent.com/13696193/45324308-bfb73700-b51b-11e8-90e7-ab24f3d6e61d.jpg) + +You can easily change colors to match your background by changing a couple of parameters in the code. + +![toolbar black](https://user-images.githubusercontent.com/13696193/45324307-bfb73700-b51b-11e8-8709-6c3c23f737c4.jpg) + + + import PySimpleGUI as sg + import subprocess + import os + import sys + + """ + Demo_Toolbar - A floating toolbar with quick launcher One cool PySimpleGUI demo. Shows borderless windows, grab_anywhere, tight button layout + You can setup a specific program to launch when a button is clicked, or use the Combobox to select a .py file found in the root folder, and run that file. """ + + ROOT_PATH = './' + + def Launcher(): + + def print(line): + window.FindElement('output').Update(line) + + sg.ChangeLookAndFeel('Dark') + + namesonly = [f for f in os.listdir(ROOT_PATH) if f.endswith('.py') ] + + sg.SetOptions(element_padding=(0,0), button_element_size=(12,1), auto_size_buttons=False) + layout = [[sg.Combo(values=namesonly, size=(35,30), key='demofile'), + sg.ReadButton('Run', button_color=('white', '#00168B')), + sg.ReadButton('Program 1'), + sg.ReadButton('Program 2'), + sg.ReadButton('Program 3', button_color=('white', '#35008B')), + sg.Button('EXIT', button_color=('white','firebrick3'))], + [sg.T('', text_color='white', size=(50,1), key='output')]] + + window = sg.Window('Floating Toolbar', no_titlebar=True, keep_on_top=True).Layout(layout) + + # ---===--- Loop taking in user input (buttons) --- # + while True: + (button, value) = window.Read() + if button == 'EXIT' or button is None: + break # exit button clicked + if button == 'Program 1': + print('Run your program 1 here!') + elif button == 'Program 2': + print('Run your program 2 here!') + elif button == 'Run': + file = value['demofile'] + print('Launching %s'%file) + ExecuteCommandSubprocess('python', os.path.join(ROOT_PATH, file)) + else: + print(button) + + def ExecuteCommandSubprocess(command, *args, wait=False): + try: + if sys.platwindow == 'linux': + arg_string = '' + for arg in args: + arg_string += ' ' + str(arg) + sp = subprocess.Popen(['python3' + arg_string, ], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + else: + sp = subprocess.Popen([command, list(args)], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + if wait: + out, err = sp.communicate() + if out: + print(out.decode("utf-8")) + if err: + print(err.decode("utf-8")) + except: pass + + + + if __name__ == '__main__': + Launcher() + + + + +## Desktop Floating Widget - Timer + +This is a little widget you can leave running on your desktop. Will hopefully see more of these for things like checking email, checking server pings, displaying system information, dashboards, etc +. +Much of the code is handling the button states in a fancy way. It could be much simpler if you don't change the button text based on state. + +![timer](https://user-images.githubusercontent.com/13696193/45336349-26a31300-b551-11e8-8b06-d1232ff8ca10.jpg) + + import PySimpleGUI as sg + import time + + """ + Timer Desktop Widget Creates a floating timer that is always on top of other windows You move it by grabbing anywhere on the window Good example of how to do a non-blocking, polling program using PySimpleGUI Can be used to poll hardware when running on a Pi NOTE - you will get a warning message printed when you exit using exit button. It will look something like: invalid command name \"1616802625480StopMove\" + """ + + + # ---------------- Create window ---------------- + sg.ChangeLookAndFeel('Black') + sg.SetOptions(element_padding=(0, 0)) + + layout = [[sg.Text('')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='text')], + [sg.ReadButton('Pause', key='button', button_color=('white', '#001480')), + sg.ReadButton('Reset', button_color=('white', '#007339'), key='Reset'), + sg.Exit(button_color=('white', 'firebrick4'), key='Exit')]] + + window = sg.Window('Running Timer', no_titlebar=True, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout) + + + # ---------------- main loop ---------------- + current_time = 0 + paused = False + start_time = int(round(time.time() * 100)) + while (True): + # --------- Read and update window -------- + if not paused: + button, values = window.ReadNonBlocking() + current_time = int(round(time.time() * 100)) - start_time + else: + button, values = window.Read() + if button == 'button': + button = window.FindElement(button).GetText() + # --------- Do Button Operations -------- + if values is None or button == 'Exit': + break + if button is 'Reset': + start_time = int(round(time.time() * 100)) + current_time = 0 + paused_time = start_time + elif button == 'Pause': + paused = True + paused_time = int(round(time.time() * 100)) + element = window.FindElement('button') + element.Update(text='Run') + elif button == 'Run': + paused = False + start_time = start_time + int(round(time.time() * 100)) - paused_time + element = window.FindElement('button') + element.Update(text='Pause') + + # --------- Display timer in window -------- + window.FindElement('text').Update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60, + (current_time // 100) % 60, + current_time % 100)) + time.sleep(.01) + + # --------- After loop -------- + + # Broke out of main loop. Close the window. + window.CloseNonBlocking() + +## Desktop Floating Widget - CPU Utilization + +Like the Timer widget above, this script can be kept running. You will need the package psutil installed in order to run this Recipe. +The spinner changes the number of seconds between reads. Note that you will get an error message printed when exiting because the window does not have have a titlebar. It's a known problem. + + +![cpu widget 2](https://user-images.githubusercontent.com/13696193/45456096-77348080-b6b7-11e8-8906-6663c31ad0eb.jpg) + + + + import PySimpleGUI as sg + import psutil + + # ---------------- Create Window ---------------- + sg.ChangeLookAndFeel('Black') + layout = [[sg.Text('')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='text')], + [sg.Exit(button_color=('white', 'firebrick4'), pad=((15,0), 0)), sg.Spin([x+1 for x in range(10)], 1, key='spin')]] + + window = sg.Window('Running Timer', no_titlebar=True, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout) + + + # ---------------- main loop ---------------- + while (True): + # --------- Read and update window -------- + button, values = window.ReadNonBlocking() + + # --------- Do Button Operations -------- + if values is None or button == 'Exit': + break + try: + interval = int(values['spin']) + except: + interval = 1 + + cpu_percent = psutil.cpu_percent(interval=interval) + + # --------- Display timer in window -------- + + window.FindElement('text').Update(f'CPU {cpu_percent:02.0f}%') + + # Broke out of main loop. Close the window. + window.CloseNonBlocking() + +## Menus + +Menus are nothing more than buttons that live in a menu-bar. When you click on a menu item, you get back a "button" with that menu item's text, just as you would had that text been on a button. + +Menu's are defined separately from the GUI window. To add one to your window, simply insert sg.Menu(menu_layout). The menu definition is a list of menu choices and submenus. They are a list of lists. Copy the Recipe and play with it. You'll eventually get when you're looking for. + +If you double click the dashed line at the top of the list of choices, that menu will tear off and become a floating toolbar. How cool! + + +![tear off](https://user-images.githubusercontent.com/13696193/45307668-9aabcf80-b4ed-11e8-9b2b-8564d4bf82a8.jpg) + + + + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('LightGreen') + sg.SetOptions(element_padding=(0, 0)) + + # ------ Menu Definition ------ # + menu_def = [['File', ['Open', 'Save', 'Exit' ]], + ['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ], + ['Help', 'About...'], ] + + # ------ GUI Defintion ------ # + layout = [ + [sg.Menu(menu_def)], + [sg.Output(size=(60, 20))] + ] + + window = sg.Window("Windows-like program", default_element_size=(12, 1), auto_size_text=False, auto_size_buttons=False, + default_button_element_size=(12, 1)).Layout(layout) + + # ------ Loop & Process button menu choices ------ # + while True: + button, values = window.Read() + if button == None or button == 'Exit': + break + print('Button = ', button) + # ------ Process menu choices ------ # + if button == 'About...': + sg.Popup('About this program', 'Version 1.0', 'PySimpleGUI rocks...') + elif button == 'Open': + filename = sg.PopupGetFile('file to open', no_window=True) + print(filename) + +## Graphing with Graph Element + +Use the Graph Element to draw points, lines, circles, rectangles using ***your*** coordinate systems rather than the underlying graphics coordinates. + +In this example we're defining our graph to be from -100, -100 to +100,+100. That means that zero is in the middle of the drawing. You define this graph description in your call to Graph. + +![snap0354](https://user-images.githubusercontent.com/13696193/45861485-cd9a6280-bd3a-11e8-83ea-32ca42dc9f3a.jpg) + + + + import math + import PySimpleGUI as sg + + layout = [[sg.Graph(canvas_size=(400, 400), graph_bottom_left=(-100,-100), graph_top_right=(100,100), background_color='white', key='graph')],] + + window = sg.Window('Graph of Sine Function').Layout(layout) + window.Finalize() + graph = window.FindElement('graph') + + graph.DrawLine((-100,0), (100,0)) + graph.DrawLine((0,-100), (0,100)) + + for x in range(-100,100): + y = math.sin(x/20)*50 + graph.DrawPoint((x,y), color='red') + + button, values = window.Read() + +## Tabs + +Tabs bring not only an extra level of sophistication to your window layout, they give you extra room to add more elements. Tabs are one of the 3 container Elements, Elements that hold or contain other Elements. The other two are the Column and Frame Elements. + + +![tabs](https://user-images.githubusercontent.com/13696193/46049479-97732f00-c0fc-11e8-8015-5bbed8bd88bb.jpg) + + + +``` +import PySimpleGUI as sg + +tab1_layout = [[sg.T('This is inside tab 1')]] + +tab2_layout = [[sg.T('This is inside tab 2')], + [sg.In(key='in')]] + +layout = [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout, tooltip='tip'), sg.Tab('Tab 2', tab2_layout)]], tooltip='TIP2')], + [sg.RButton('Read')]] + +window = sg.Window('My window with tabs', default_element_size=(12,1)).Layout(layout) + +while True: + button, v = window.Read() + print(button,values) + if button is None: # always, always give a way out! + break +``` + + + + +## Creating a Windows .EXE File + +It's possible to create a single .EXE file that can be distributed to Windows users. There is no requirement to install the Python interpreter on the PC you wish to run it on. Everything it needs is in the one EXE file, assuming you're running a somewhat up to date version of Windows. + +Installation of the packages, you'll need to install PySimpleGUI and PyInstaller (you need to install only once) + + pip install PySimpleGUI + pip install PyInstaller + +To create your EXE file from your program that uses PySimpleGUI, `my_program.py`, enter this command in your Windows command prompt: + + pyinstaller -wF my_program.py + +You will be left with a single file, `my_program.exe`, located in a folder named `dist` under the folder where you executed the `pyinstaller` command. + +That's all... Run your `my_program.exe` file on the Windows machine of your choosing. + +> "It's just that easy." +> +(famous last words that screw up just about anything being referenced) + +Your EXE file should run without creating a "shell window". Only the GUI window should show up on your taskbar. diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 000000000..9bf329997 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,2986 @@ + + + + +![pysimplegui_logo](https://user-images.githubusercontent.com/13696193/43165867-fe02e3b2-8f62-11e8-9fd0-cc7c86b11772.png) + +[![Downloads](http://pepy.tech/badge/pysimplegui)](http://pepy.tech/project/pysimplegui) +[![Downloads ](https://pepy.tech/badge/pysimplegui27)](https://pepy.tech/project/pysimplegui27) +![Documentation Status](https://readthedocs.org/projects/pysimplegui/badge/?version=latest) + ![Awesome Meter](https://img.shields.io/badge/Awesome_meter-100-yellow.svg) + ![Python Version](https://img.shields.io/badge/Python-2.7_3.x-yellow.svg) + + + + + + +# PySimpleGUI + + +## Now supports both Python 2.7 & 3 + +![Python Version](https://img.shields.io/badge/PySimpleGUI_For_Python_3_Version-3.8.4-red.svg?longCache=true&style=for-the-badge) + + ![Python Version](https://img.shields.io/badge/PySimpleGUI_For_Python_2.7_Version-1.0.4-blue.svg?longCache=true&style=for-the-badge) + +[Announcements of Latest Developments](https://github.com/MikeTheWatchGuy/PySimpleGUI/issues/142) + +[ReadTheDocs](http://pysimplegui.readthedocs.io/) + +[COOKBOOK!](https://pysimplegui.readthedocs.io/en/latest/cookbook/) + +[Brief Tutorial](https://pysimplegui.readthedocs.io/en/latest/tutorial/) + +[Latest Demos and Master Branch on GitHub](https://github.com/MikeTheWatchGuy/PySimpleGUI) + +Super-simple GUI to use... Powerfully customizable. + +Home of the 1-line custom GUI and 1-line progress meter + +#### Note regarding Python versions +As of 9/25/2018 **both Python 3 and Python 2.7 are supported**! The Python 3 version is named `PySimpleGUI`. The Python 2.7 version is `PySimpleGUI27`. They are installed separately and the imports are different. See instructions in Installation section for more info. + + +------------------------------------------------------------------------ + + +Looking for a GUI package? +* Taking your Python code from the world of command lines and into the convenience of a GUI? * +* Have a Raspberry **Pi** with a touchscreen that's going to waste because you don't have the time to learn a GUI SDK? +* Into Machine Learning and are sick of the command line? +* Would like to distribute your Python code to Windows users as a single .EXE file that launches straight into a GUI, much like a WinForms app? + +Look no further, **you've found your GUI package**. + + import PySimpleGUI as sg + + sg.Popup('Hello From PySimpleGUI!', 'This is the shortest GUI program ever!') + + +![hello world](https://user-images.githubusercontent.com/13696193/44960047-1f7f6380-aec6-11e8-9d5e-12ef935bcade.jpg) + + +Or how about a ***custom GUI*** in 1 line of code? + + import PySimpleGUI as sg + + button, (filename,) = sg.Window('Get filename example'). LayoutAndRead([[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ]) + +![get filename](https://user-images.githubusercontent.com/13696193/44960039-f1018880-aec5-11e8-8a43-3d7f8ff93b67.jpg) + + + Build beautiful customized windows that fit your specific problem. Let PySimpleGUI solve your GUI problem while you solve your real problems. Look through the Cookbook, find a matching recipe, copy, paste, run within minutes. This is the process PySimpleGUI was designed to facilitate. + + +![borderless grayed buttons](https://user-images.githubusercontent.com/13696193/45168664-d848e980-b1c9-11e8-886e-63279ae4017f.jpg) + + + +PySimpleGUI wraps tkinter so that you get all the same widgets as you would tkinter, but you interact with them in a more friendly way. It does the layout and boilerplate code for you and presents you with a simple, efficient interface. + +![everything dark theme](https://user-images.githubusercontent.com/13696193/44959854-b1d23800-aec3-11e8-90b6-5af915a86d15.jpg) + +Perhaps you're looking for a way to interact with your **Raspberry Pi** in a more friendly way. The same for shown as on Pi (roughly the same) + +![raspberry pi everything demo](https://user-images.githubusercontent.com/13696193/44279694-5b58ce80-a220-11e8-9ab6-d6021f5a944f.jpg) + + + +In addition to a primary GUI, you can add a Progress Meter to your code with ONE LINE of code. Slide this line into any of your `for` loops and get a nice meter: + + OneLineProgressMeter('My meter title', current_value, max value, 'key') + + ![easyprogressmeter](https://user-images.githubusercontent.com/13696193/44960065-83099100-aec6-11e8-8aa8-96e4b100a0e4.jpg) + +You can build an async media player GUI with custom buttons in 30 lines of code. + +![media player 2](https://user-images.githubusercontent.com/13696193/44960091-eeebf980-aec6-11e8-884e-80d4447a83cd.jpg) + + +How about embedding a game inside of a GUI? This game of Pong is written in tkinter and then dropped into the PySimpleGUI window creating a game that has an accompanying GUI. + +![pong](https://user-images.githubusercontent.com/13696193/45860012-2d8d0b00-bd33-11e8-9efd-3eaf4c30f324.gif) + + +Combining PySimpleGUI with PyInstaller creates something truly remarkable and special, a Python program that looks like a Windows WinForms application. This application with working menu was created in 20 lines of Python code. It is a single .EXE file that launches straight into the screen you see. And more good news, the only icon you see on the taskbar is the window itself... there is no pesky shell window. + +![menu demo](https://user-images.githubusercontent.com/13696193/45923097-8fbc4c00-beaa-11e8-87d2-01a5331811c8.gif) + + + ## Background +I was frustrated by having to deal with the dos prompt when I had a powerful Windows machine right in front of me. Why is it SO difficult to do even the simplest of input/output to a window in Python?? + +There are a number of 'easy to use' Python GUIs, but they were too limited for my requirements. PySimpleGUI aims for the same simplicity found in packages like `EasyGUI`and `WxSimpleGUI` , both really handy but limited, and adds the ability to define your own layouts. This ability to make your own windows using a large palette of widgets is but one difference between the existing "simple" packages and `PySimpleGUI`. + +With a simple GUI, it becomes practical to "associate" .py files with the python interpreter on Windows. Double click a py file and up pops a GUI window, a more pleasant experience than opening a dos Window and typing a command line. + +The `PySimpleGUI` package is focused on the ***developer***. +> Create a custom GUI with as little and as simple code as possible. + +This was the primary focus used to create PySimpleGUI. + +> "Do it in a Python-like way" + +was the second. + +## Features + +While simple to use, PySimpleGUI has significant depth to be explored by more advanced programmers. The feature set goes way beyond the requirements of a beginner programmer, and into the required features needed for complex GUIs. + + Features of PySimpleGUI include: + Support for versions Python 2.7 and 3 + Text + Single Line Input + Buttons including these types: + File Browse + Files Browse + Folder Browse + SaveAs + Non-closing return + Close window + Realtime + Calendar chooser + Color chooser + Checkboxes + Radio Buttons + Listbox + Option Menu + Slider + Graph + Frame with title + Icons + Multi-line Text Input + Scroll-able Output + Images + Progress Bar Async/Non-Blocking Windows + Tabbed windows + Persistent Windows + Redirect Python Output/Errors to scrolling window + 'Higher level' APIs (e.g. MessageBox, YesNobox, ...) + Single-Line-Of-Code Proress Bar & Debug Print + Complete control of colors, look and feel + Selection of pre-defined palettes + Button images + Return values as dictionary + Set focus + Bind return key to buttons + Group widgets into a column and place into window anywhere + Scrollable columns + Keyboard low-level key capture + Mouse scroll-wheel support + Get Listbox values as they are selected + Get slider, spinner, combo as they are changed + Update elements in a live window + Bulk window-fill operation + Save / Load window to/from disk + Borderless (no titlebar) windows + Always on top windows + Menus + Tooltips + Clickable links + No async programming required (no callbacks to worry about) + + +An example of many widgets used on a single window. A little further down you'll find the 21 lines of code required to create this complex window. Try it if you don't believe it. Install PySimpleGUI then : + +>Start Python, copy and paste the code below into the >>> prompt and hit enter. This will pop up... +> + +![everything example](https://user-images.githubusercontent.com/13696193/43097412-0a4652aa-8e8a-11e8-8e09-939484e3c568.jpg) + + + + import PySimpleGUI as sg + + layout = [[sg.Text('All graphic widgets in one window!', size=(30, 1), font=("Helvetica", 25), text_color='blue')], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText()], + [sg.Checkbox('My first checkbox!'), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True), sg.Radio('My second Radio!', "RADIO1")], + [sg.Multiline(default_text='This is the default Text shoulsd you decide not to type anything',)], + [sg.InputCombo(['Combobox 1', 'Combobox 2'], size=(20, 3)), + sg.Slider(range=(1, 100), orientation='h', size=(35, 20), default_value=85)], + [sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6)), + sg.Slider(range=(1, 100), orientation='v', size=(10, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(10, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(10, 20), default_value=10)], + [sg.Text('_' * 100, size=(70, 1))], + [sg.Text('Choose Source and Destination Folders', size=(35, 1))], + [sg.Text('Source Folder', size=(15, 1), auto_size_text=False, justification='right'), sg.InputText('Source'), + sg.FolderBrowse()], + [sg.Text('Destination Folder', size=(15, 1), auto_size_text=False, justification='right'), sg.InputText('Dest'), + sg.FolderBrowse()], + [sg.Submit(), sg.Cancel(), sg.Button('Customized', button_color=('white', 'green'))]] + + button, values = sg.Window('Everything bagel', auto_size_text=True, default_element_size=(40, 1)).LayoutAndRead(layout) + + + +--- +### Design Goals + +> Copy, Paste, Run. + +`PySimpleGUI's` goal with the API is to be easy on the programmer, and to function in a Python-like way. Since GUIs are visual, it was desirable for the code to visually match what's on the screen. By providing a significant amount of documentation and an easy to use Cookbook, it's possible to see your first GUI within 5 minutes of beginning the installation. + + > Be Pythonic + + Be Pythonic... Attempted to use language constructs in a natural way and to exploit some of Python's interesting features. Python's lists and optional parameters make PySimpleGUI work smoothly. + + - windows are represented as Python lists. + - A window is a list of rows + - A row is a list of elements +- Return values are a list of button presses and input values. +- Return values can also be represented as a dictionary +- The SDK calls collapse down into a single line of Python code that presents a custom GUI and returns values +- Linear programming instead of callbacks + + #### Lofty Goals + +> Change Python + +The hope is not that ***this*** package will become part of the Python Standard Library. + +The hope is that Python will become ***the*** go-to language for creating GUI programs that run on Windows, Mac, and Linux *for all levels of developer*. + +The hope is that beginners that are interested in graphic design will have an easy way to express themselves, right from the start of their Python experience. + +There is a noticeable gap in the Python GUI solution. Fill that gap and who knows what will happen. + +Maybe there's no "there there". ***Or*** maybe a simple GUI API will enable Python to dominate yet another computing discipline like it has so many others. This is my attempt to find out. + + + ----- +## Getting Started with PySimpleGUI + +### Installing Python 3 + + pip install --upgrade PySimpleGUI + +On some systems you need to run pip3. + + pip3 install --upgrade PySimpleGUI + +On a Raspberry Pi, this is should work: + + sudo pip3 install --upgrade pysimplegui + +Some users have found that upgrading required using an extra flag on the pip `--no-cache-dir`. + + pip install --upgrade --no-cache-dir + +On some versions of Linux you will need to first install pip. Need the Chicken before you can get the Egg (get it... Egg?) + +`sudo apt install python3-pip ` + +If for some reason you are unable to install using `pip`, don't worry, you can still import PySimpleGUI by downloading the file PySimleGUI.py and placing it in your folder along with the application that is importing it. + +`tkinter` is a requirement for PySimpleGUI (the only requirement). Some OS variants, such as Ubuntu, do not some with `tkinter` already installed. If you get an error similar to: +``` +ImportError: No module named tkinter +``` +then yosudou need to install `tkinter`. Be sure and get the Python 3 version. +` +```sudo apt-get install python3-tk ``` + + +### Installing for Python 2.7 + + pip install --upgrade PySimpleGUI27 + +Python 2.7 support is relatively new and the bugs are still being worked out. I'm unsure what may need to be done to install tkinter for Python 2.7. Will update this readme when more info is available + +Like above, you may have to install either pip or tkinter. To do this on Python 2.7: + +`sudo apt install python-pip` + +`sudo apt install python-tkinter` + +### Testing your installation + +Once you have installed, or copied the .py file to your app folder, you can test the installation using python. At the command prompt start up Python. + +#### Instructions for Python 2.7: +``` +python +>>> import PySimpleGUI27 +>>> PySimpleGUI27.main() +``` + +#### Instructions for Python 3: + +``` +python3 +>>> import PySimpleGUI +>>> PySimpleGUI.main() +``` + +You will see a sample window in the center of your screen. If it's not installed correctly you are likely to get an error message during one of those commands + +Here is the window you should see: + +![sample window](https://user-images.githubusercontent.com/13696193/46097669-79efa500-c190-11e8-885c-e5d4d5d09ea6.jpg) + + + +### Prerequisites +Python 2.7 or Python 3 +tkinter + +PySimpleGUI Runs on all Python3 platforms that have tkinter running on them. It has been tested on Windows, Mac, Linux, Raspberry Pi. Even runs on `pypy3`. + +### EXE file creation + +If you wish to create an EXE from your PySimpleGUI application, you will need to install `PyInstaller`. There are instructions on how to create an EXE at the bottom of this ReadMe + + +## Using - Python 3 + +To use in your code, simply import.... + `import PySimpleGUI as sg` + +Then use either "high level" API calls or build your own windows. + + sg.Popup('This is my first Popup') + +![first popup](https://user-images.githubusercontent.com/13696193/44957300-c7813680-ae9e-11e8-9a8c-c70198db7907.jpg) + + +Yes, it's just that easy to have a window appear on the screen using Python. With PySimpleGUI, making a custom window appear isn't much more difficult. The goal is to get you running on your GUI within ***minutes***, not hours nor days. + +## Using - Python 2.7 + +Those using Python 2.7 will import a different module name + `import PySimpleGUI27 as sg` + +## Code Samples Assume Python 3 + +While all of the code examples you will see in this Readme and the Cookbook assume Python 3 and thus have an `import PySimpleGUI` at the top, you can run ***all*** of this code on Python 2.7 by changing the import statement to `import PySimpleGUI27` + +--- +## APIs + +PySimpleGUI can be broken down into 2 types of API's: + * High Level single call functions (The `Popup` calls) + * Custom window functions + + +### Python Language Features + + There are a number of Python language features that PySimpleGUI utilizes heavily for API access that should be understood... + * Variable number of arguments to a function call + * Optional parameters to a function call + * Dictionaries + +#### Variable Number of Arguments + + The "High Level" API calls that *output* values take a variable number of arguments so that they match a "print" statement as much as possible. The idea is to make it simple for the programmer to output as many items as desired and in any format. The user need not convert the variables to be output into the strings. The PySimpleGUI functions do that for the user. + + sg.Popup('Variable number of parameters example', var1, var2, "etc") + +Each new item begins on a new line in the Popup + + ![snap0179](https://user-images.githubusercontent.com/13696193/43658129-f6ca49c6-9725-11e8-9317-1f77443eb04a.jpg) + + + +#### Optional Parameters to a Function Call + +This feature of the Python language is utilized ***heavily*** as a method of customizing windows and window Elements. Rather than requiring the programmer to specify every possible option for a widget, instead only the options the caller wants to override are specified. + +Here is the function definition for the Popup function. The details aren't important. What is important is seeing that there is a long list of potential tweaks that a caller can make. However, they don't *have* to be specified on each and every call. + + def Popup(*args, + button_color=None, + button_type=MSG_BOX_OK, + auto_close=False, + auto_close_duration=None, + icon=DEFAULT_WINDOW_ICON, + line_width=MESSAGE_BOX_LINE_WIDTH, + font=None): + +If the caller wanted to change the button color to be black on yellow, the call would look something like this: + + sg.Popup('This box has a custom button color', button_color=('black', 'yellow')) + + +![snap0180](https://user-images.githubusercontent.com/13696193/43658171-13a72bfe-9726-11e8-8c7a-0a46e46fb202.jpg) + + +#### Dictionaries + +Dictionaries are used by more advanced PySimpleGUI users. You'll know that dictionaries are being used if you see a `key` parameter on any Element. Dictionaries are used in 2 ways: +1. To identify values when a window is read +2. To identify Elements so that they can be "updated" + +--- + +### High Level API Calls - Popup's + +"High level calls" are those that start with "Popup". They are the most basic form of communications with the user. They are named after the type of window they create, a pop-up window. These windows are meant to be short lived while, either delivering information or collecting it, and then quickly disappearing. + +### Popup Output + +Think of the `Popup` call as the GUI equivalent of a `print` statement. It's your way of displaying results to a user in the windowed world. Each call to Popup will create a new Popup window. + +`Popup` calls are normally blocking. your program will stop executing until the user has closed the Popup window. A non-blocking window of Popup discussed in the async section. + +Just like a print statement, you can pass any number of arguments you wish. They will all be turned into strings and displayed in the popup window. + +There are a number of Popup output calls, each with a slightly different look (e.g. different button labels). + +The list of Popup output functions are + + Popup + PopupOk + PopupYesNo + PopupCancel + PopupOkCancel + PopupError + PopupTimed, PopupAutoClose + PopupNoWait, PopupNonBlocking + +The trailing portion of the function name after Popup indicates what buttons are shown. `PopupYesNo` shows a pair of button with Yes and No on them. `PopupCancel` has a Cancel button, etc. + +While these are "output" windows, they do collect input in the form of buttons. The Popup functions return the button that was clicked. If the Ok button was clicked, then Popup returns the string 'Ok'. If the user clicked the X button to close the window, then the button value returned is `None`. + +The function `PopupTimed` or `PopupAutoClose` are popup windows that will automatically close after come period of time. + +Here is a quick-reference showing how the Popup calls look. + + + sg.Popup('Popup') + sg.PopupOk('PopupOk') + sg.PopupYesNo('PopupYesNo') + sg.PopupCancel('PopupCancel') + sg.PopupOkCancel('PopupOkCancel') + sg.PopupError('PopupError') + sg.PopupTimed('PopupTimed') + sg.PopupAutoClose('PopupAutoClose') + + + +![snap0256](https://user-images.githubusercontent.com/13696193/44957394-1380ab00-aea0-11e8-98b1-1ab7d7bd5b37.jpg) + +![snap0257](https://user-images.githubusercontent.com/13696193/44957400-167b9b80-aea0-11e8-9d42-2314f24e62de.jpg) + +![snap0258](https://user-images.githubusercontent.com/13696193/44957399-154a6e80-aea0-11e8-9580-e716f839d400.jpg) + +![snap0259](https://user-images.githubusercontent.com/13696193/44957398-14b1d800-aea0-11e8-9e88-c2b36a248447.jpg) + +![snap0260](https://user-images.githubusercontent.com/13696193/44957397-14b1d800-aea0-11e8-950b-6d0b4f33841a.jpg) + +![snap0261](https://user-images.githubusercontent.com/13696193/44957396-14194180-aea0-11e8-8eef-bb2e1193ecfa.jpg) + +![snap0264](https://user-images.githubusercontent.com/13696193/44957595-9e15da00-aea1-11e8-8909-6b6121b74509.jpg) + +#### Scrolled Output +There is a scrolled version of Popups should you have a lot of information to display. + + sg.PopupScrolled(my_text) + +![scrolledtextbox 2](https://user-images.githubusercontent.com/13696193/43667324-712aa0d4-9745-11e8-83a9-a0d0570d0865.jpg) + + +The `PopupScrolled` will auto-fit the window size to the size of the text. Specify `None` in the height field of a `size` parameter to get auto-sized height. + +This call will create a scrolled box 80 characters wide and a height dependent upon the number of lines of text. + +sg.PopupScrolled(my_text, size=(80, None)) + +Note that the default max number of lines before scrolling happens is set to 50. At 50 lines the scrolling will begin. + +### PopupNoWait + +The Popup call PopupNoWait or PopupNonBlocking will create a popup window and then immediately return control back to you. All other popup functions will block, waiting for the user to close the popup window. + +This function is very handy for when you're **debugging** and want to display something as output but don't want to change the programs's overall timing by blocking. Think of it like a `print` statement + +A word of ***caution***... Windows that are created after the NoWait Popup are "slaves" to the NoWait'd popup. If you close the Popup, it will also lose the window the you created after the Popup. A good rule of thumb is to leave the popup open while you're interacting with the rest of your program until you understand what happens when you close the NoWaitPopup. + + + +### Popup Input + +There are Popup calls for single-item inputs. These follow the pattern of `Popup` followed by `Get` and then the type of item to get. + + - `PopupGetString` - get a single line of text + - `PopupGetFile` - get a filename + - `PopupGetFolder` - get a folder name + +Rather than make a custom window to get one data value, call the Popup input function to get the item from the user. + + + import PySimpleGUI as sg + + text = sg.PopupGetText('Title', 'Please input something') + sg.Popup('Results', 'The value returned from PopupGetText', text) + + ![popupgettext](https://user-images.githubusercontent.com/13696193/44957281-8721b880-ae9e-11e8-98cd-d06369f4187e.jpg) + +![popup gettext response](https://user-images.githubusercontent.com/13696193/44957282-8721b880-ae9e-11e8-84ae-dc8bb30504a0.jpg) + + + text = sg.PopupGetFile('Please enter a file name') + sg.Popup('Results', 'The value returned from PopupGetFile', text) + +![popupgetfile](https://user-images.githubusercontent.com/13696193/44957857-2fd31680-aea5-11e8-8eb7-f6b91c202cc8.jpg) + +The window created to get a folder name looks the same as the get a file name. The difference is in what the browse button does. `PopupGetFile` shows an Open File dialog box while `PopupGetFolder` shows an Open Folder dialog box. + + text = sg.PopupGetFolder('Please enter a folder name') + sg.Popup('Results', 'The value returned from PopupGetFolder', text) + +![popupgetfolder](https://user-images.githubusercontent.com/13696193/44957861-45484080-aea5-11e8-926c-cf607a45251c.jpg) + +#### Progress Meters! +We all have loops in our code. 'Isn't it joyful waiting, watching a counter scrolling past in a text window? How about one line of code to get a progress meter, that contains statistics about your code? + + + OneLineProgressMeter(title, + current_value, + max_value, + key, + *args, + orientation=None, + bar_color=DEFAULT_PROGRESS_BAR_COLOR, + button_color=None, + size=DEFAULT_PROGRESS_BAR_SIZE, + border_width=DEFAULT_PROGRESS_BAR_BORDER_WIDTH): + +Here's the one-line Progress Meter in action! + + for i in range(1,10000): + sg.OneLineProgressMeter('My Meter', i+1, 10000, 'key','Optional message') + +That line of code resulted in this window popping up and updating. + +![preogress meter](https://user-images.githubusercontent.com/13696193/43667625-d47da702-9746-11e8-91e6-e5177883abae.jpg) + +A meter AND fun statistics to watch while your machine grinds away, all for the price of 1 line of code. +With a little trickery you can provide a way to break out of your loop using the Progress Meter window. The cancel button results in a `False` return value from `OneLineProgressMeter`. It normally returns `True`. + +***Be sure and add one to your loop counter*** so that your counter goes from 1 to the max value. If you do not add one, your counter will never hit the max value. Instead it will go from 0 to max-1. + +#### Debug Output +Another call in the 'Easy' families of APIs is `EasyPrint`. It will output to a debug window. If the debug window isn't open, then the first call will open it. No need to do anything but stick a 'print' call in your code. You can even replace your 'print' calls with calls to EasyPrint by simply sticking the statement + + print = sg.EasyPrint + +at the top of your code. +There are a number of names for the same EasyPrint function. `Print` is one of the better ones to use as it's easy to remember. It is simply `print` with a capital P. + + import PySimpleGUI as sg + + for i in range(100): + sg.Print(i) + +![snap0125](https://user-images.githubusercontent.com/13696193/43114979-a696189e-8ecf-11e8-83c7-473fcf0ccc66.jpg) +Or if you didn't want to change your code: + + import PySimpleGUI as sg + + print=sg.Print + for i in range(100): + print(i) + +Just like the standard print call, `EasyPrint` supports the `sep` and `end` keyword arguments. Other names that can be used to call `EasyPrint` include Print, `eprint`, If you want to close the window, call the function `EasyPrintClose`. + +A word of caution. There are known problems when multiple PySimpleGUI windows are opened, particularly if the user closes them in an unusual way. Not a reason to stay away from using it. Just something to keep in mind if you encounter a problem. + +You can change the size of the debug window using the `SetOptions` call with the `debug_win_size` parameter. + +--- +# Custom window API Calls (Your First window) + +This is the FUN part of the programming of this GUI. In order to really get the most out of the API, you should be using an IDE that supports auto complete or will show you the definition of the function. This will make customizing go smoother. + +This first section on custom windows is for your typical, blocking, non-persistant window. By this I mean, when you "show" the window, the function will not return until the user has clicked a button or closed the window. When this happens, the window will be automatically closed. + +Two other types of windows exist. +1. Persistent window - rather than closing on button clicks, the show window function returns and the window continues to be visible. This is good for applications like a chat window. +2. Asynchronous window - the trickiest of the lot. Great care must be exercised. Examples are an MP3 player or status dashboard. Async windows are updated (refreshed) on a periodic basis. + +It's both not enjoyable nor helpful to immediately jump into tweaking each and every little thing available to you. + +## The window Designer +The good news to newcomers to GUI programming is that PySimpleGUI has a window designer. Better yet, the window designer requires no training and everyone knows how to use it. + +![gui0_1](https://user-images.githubusercontent.com/13696193/44159598-e2257400-a085-11e8-9b02-343e72cc75c3.JPG) + +It's a manual process, but if you follow the instructions, it will take only a minute to do and the result will be a nice looking GUI. The steps you'll take are: +1. Sketch your GUI on paper +2. Divide your GUI up into rows +3. Label each Element with the Element name +4. Write your Python code using the labels as pseudo-code + +Let's take a couple of examples. + +**Enter a number**.... Popular beginner programs are often based on a game or logic puzzle that requires the user to enter something, like a number. The "high-low" answer game comes to mind where you try to guess the number based on high or low tips. + +**Step 1- Sketch the GUI** +![gui1_1](https://user-images.githubusercontent.com/13696193/44160127-6a584900-a087-11e8-8fec-09099a8e16f6.JPG) + +**Step 2 - Divide into rows** + +![gui2_1](https://user-images.githubusercontent.com/13696193/44160128-6a584900-a087-11e8-9973-af866fb94c56.JPG) + +Step 3 - Label elements + +![gui6_1](https://user-images.githubusercontent.com/13696193/44160116-64626800-a087-11e8-8b57-671c0461b508.JPG) + +Step 4 - Write the code +The code we're writing is the layout of the GUI itself. This tutorial only focuses on getting the window code written, not the stuff to display it, get results. + +We have only 1 element on the first row, some text. Rows are written as a "list of elements", so we'll need [ ] to make a list. Here's the code for row 1 + + [ sg.Text('Enter a number') ] + +Row 2 has 1 elements, an input field. + + [ sg.Input() ] +Row 3 has an OK button + + [ sg.OK() ] + +Now that we've got the 3 rows defined, they are put into a list that represents the entire window. + + layout = [ [sg.Text('Enter a Number')], + [sg.Input()], + [sg.OK()] ] + +Finally we can put it all together into a program that will display our window. + + import PySimpleGUI as sg + + layout = [[sg.Text('Enter a Number')], + [sg.Input()], + [sg.OK()] ] + + button, (number,) = sg.Window('Enter a number example').LayoutAndRead(layout) + + sg.Popup(button, number) + +### Example 2 - Get a filename +Let's say you've got a utility you've written that operates on some input file and you're ready to use a GUI to enter than filename rather than the command line. Follow the same steps as the previous example - draw your window on paper, break it up into rows, label the elements. + +![gui4_1](https://user-images.githubusercontent.com/13696193/44160132-6a584900-a087-11e8-862f-7d791a67ee5d.JPG) +![gui5_1](https://user-images.githubusercontent.com/13696193/44160133-6af0df80-a087-11e8-9dec-bb4d4c59393d.JPG) + +Writing the code for this one is just as straightforward. There is one tricky thing, that browse for a file button. Thankfully PySimpleGUI takes care of associating it with the input field next to it. As a result, the code looks almost exactly like the window on the paper. + + import PySimpleGUI as sg + + layout = [[sg.Text('Filename')], + [sg.Input(), sg.FileBrowse()], + [sg.OK(), sg.Cancel()] ] + + button, (number,) = sg.Window('Get filename example').LayoutAndRead(layout) + + sg.Popup(button, number) + + +Read on for detailed instructions on the calls that show the window and return your results. + + + +# Copy these design patterns! + +All of your PySimpleGUI programs will utilize one of these 3 design patterns depending on the type of window you're implementing. + + +## Pattern 1 - Single read windows + +This is the most basic design pattern. Use this for windows that are shown to the user 1 time. The input values are gathered and returned to the program + + window_rows = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')], + [sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('SHA-1 & 256 Hash') + + button, (source_filename,) = window.LayoutAndRead(window_rows) + + ---- + +## Pattern 2 - Single-read window "chained" + +Python has a ***beautiful*** way of compacting code known as "chaining". You take the output from one function and feed it as input to the next. Notice in the first example how a window is first obtained by calling Window and then that window is then read. It's possible to combine the creation of the window with the read. This design pattern does exactly that, chain together the window creation and the window reading. + + window_rows = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')], + [sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + + button, (source_filename,) = sg.Window('SHA-1 & 256 Hash').LayoutAndRead(window_rows) + + +## Pattern 3 - Persistent window (multiple reads) + +Some of the more advanced programs operate with the window remaining visible on the screen. Input values are collected, but rather than closing the window, it is kept visible acting as a way to both output information to the user and gather input data. + +This is done by splitting the LayoutAndRead call apart into a Layout call and a Read call. Note how chaining is again used. In this case a window is created by calling Window which is then passed on to the Layout method. The Layout method returns the window value so that it can be stored and used later in the program to Read the window. + + import PySimpleGUI as sg + + layout = [[sg.Text('Persistent window')], + [sg.RButton('Turn LED On')], + [sg.RButton('Turn LED Off')], + [sg.Exit()]] + + window = sg.Window('Raspberry Pi GUI').Layout(layout) + + while True: + button, values = window.Read() + if button is None: + break + + +### How GUI Programming in Python Should Look? At least for beginners + +Why is Python such a great teaching language and yet no GUI framework exists that lends itself to the basic building blocks of Python, the list or dictionary? PySimpleGUI set out to be a Pythonic solution to the GUI problem. Whether it achieved this goal is debatable, but it was an attempt just the same. + +The key to custom windows in PySimpleGUI is to view windows as ROWS of Elements. Each row is specified as a list of these Elements. Put the rows together and you've got a window. + + Let's dissect this little program + + import PySimpleGUI as sg + + layout = [[sg.Text('Rename files or folders')], + [sg.Text('Source for Folders', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Text('Source for Files ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('Rename Files or Folders') + + button, (folder_path, file_path) = window.LayoutAndRead(layout) + + + +![snap0131](https://user-images.githubusercontent.com/13696193/43417007-df6d8408-9407-11e8-9986-30f0415f08a5.jpg) + +Let's agree the window has 4 rows. + +The first row only has **text** that reads `Rename files or folders` + +The second row has 3 elements in it. First the **text** `Source for Folders`, then an **input** field, then a **browse** button. + +Now let's look at how those 2 rows and the other two row from Python code: + + layout = [[sg.Text('Rename files or folders')], + [sg.Text('Source for Folders', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Text('Source for Files ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Submit(), sg.Cancel()]] + +See how the source code mirrors the layout? You simply make lists for each row, then submit that table to PySimpleGUI to show and get values from. + +And what about those return values? Most people simply want to show a window, get the input values and do something with them. So why break up the code into button callbacks, etc, when I simply want my window's input values to be given to me. + +For return values the window is scanned from top to bottom, left to right. Each field that's an input field will occupy a spot in the return values. + +In our example window, there are 2 fields, so the return values from this window will be a list with 2 values in it. + + button, (folder_path, file_path) = window.LayoutAndRead(layout) + +In the statement that shows and reads the window, the two input fields are directly assigned to the caller's variables `folder_path` and `file_path`, ready to use. No parsing no callbacks. + +Isn't this what almost every Python programmer looking for a GUI wants?? Something easy to work with to get the values and move on to the rest of the program, where the real action is taking place. Why write pages of GUI code when the same layout can be achieved with PySimpleGUI in 3 or 4 lines of code. 4 lines or 40? I chose 4. + + +## Return values + + As of version 2.8 there are 2 forms of return values, list and dictionary. + +### Return values as a list + + By default return values are a list of values, one entry for each input field. + + Return information from Window, SG's primary window builder interface, is in this format: + + button, (value1, value2, ...) + +Each of the Elements that are Input Elements will have a value in the list of return values. You can unpack your GUI directly into the variables you want to use. + + button, (filename, folder1, folder2, should_overwrite) = window.LayoutAndRead(window_rows) + + Or, you can unpack the return results separately. + + button, values = window.LayoutAndRead(window_rows) + filename, folder1, folder2, should_overwrite = values + +If you have a SINGLE value being returned, it is written this way: + + button, (value1,) = window.LayoutAndRead(window_rows) + + + Another way of parsing the return values is to store the list of values into a variable representing the list of values and then index each individual value. This is not the preferred way of doing it. + + button, value_list = window.LayoutAndRead(window_rows) + value1 = value_list[0] + value2 = value_list[1] + ... + +### Return values as a dictionary + +For windows longer than 3 or 4 fields you will want to use a dictionary to help you organize your return values. In almost all (if not all) of the demo programs you'll find the return values being passed as a dictionary. It is not a difficult concept to grasp, the syntax is easy to understand, and it makes for very readable code. + +The most common window read statement you'll encounter looks something like this: + + button, values = window.LayoutAndRead(layout) + +or + + button, values = window.Read() + +All of your return values will be stored in the variable `values`. When using the dictionary return values, the `values` variable is a dictionary. + + To use a dictionary, you will need to: + * Mark each input element you wish to be in the dictionary with the keyword `key`. + +If **any** element in the window has a `key`, then **all** of the return values are returned via a dictionary. If some elements do not have a key, then they are numbered starting at zero. + +Let's take a look at your first dictionary-based window. + + import PySimpleGUI as sg + window = sg.Window('Simple data entry window') + layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText('1', key='name')], + [sg.Text('Address', size=(15, 1)), sg.InputText('2', key='address')], + [sg.Text('Phone', size=(15, 1)), sg.InputText('3', key='phone')], + [sg.Submit(), sg.Cancel()] + ] + + button, values = window.LayoutAndRead(layout) + + sg.Popup(button, values, values['name'], values['address'], values['phone']) + +To get the value of an input field, you use whatever value used as the `key` value as the index value. Thus to get the value of the name field, it is written as + + values['name'] + +You will find the key field used quite heavily in most PySimpleGUI windows unless the window is very simple. + +### Button Return Values + +The button value from a Read call will be one of 3 values: +1. The Button's text +2. The Button's key +3. None + +If a button has a key set for it when it's created, then that key will be returned. If no key is set, then the button text is returned. If no button was clicked, but the window returned anyway, the button value is None. + +None is returned when the user clicks the X to close a window. + +If your window has an event loop where it is read over and over, remember to give your user an "out". You should always check for a None value and it's a good practice to provide an Exit button of some kind. Thus design patterns often resemble this Event Loop: + + while True: + button, values= window.Read() + if button is None or button == 'Quit': + break + +## The Event Loop / Callback Functions + +All GUIs have one thing in common, an "event loop" or some kind. If your program shows a single window, collects the data and then executes the primary code of the program then you likely don't need an event loop. + +Event Loops are used in programs where the window ***stays open*** after button presses. The program processes button clicks and user input in a loop called the event loop. You often hear the term event loop when discussing embedded systems or on a Raspberry Pi. + +Let's take a Pi demo program as an example. This program shows a GUI window, gets button presses, and uses them to control some LEDs. It loops, reading user input and doing something with it. + +This little program has a typical Event Loop + +![pi leds](https://user-images.githubusercontent.com/13696193/45448517-8cea7b80-b6a0-11e8-8dbe-eeefea2e93c1.jpg) + + + + import PySimpleGUI as sg + layout = [[sg.T('Raspberry Pi LEDs')], + [sg.RButton('Turn LED On')], + [sg.RButton('Turn LED Off')], + [sg.Exit()]] + + window = sg.Window('Raspberry Pi).Layout(layout) + + # ---- Event Loop ---- # + while True: + button, values = window.Read() + + # ---- Process Button Clicks ---- # + if button is None or button == 'Exit': + break + if button == 'Turn LED Off': + turn_LED_off() + elif button == 'Turn LED On': + turn_LED_on() + + # ---- After Event Loop ---- # + sg.Popup('Done... exiting') + + + +In the Event Loop we are reading the window and then doing a series of button compares to determine what to do based on the button that was clicks (value of `button` variable) + +The way buttons are presented to the caller in PySimpleGUI is ***not*** how *most* GUI frameworks handle button clicks. Most GUI frameworks, including tkinter, use ***callback*** functions, a function you define would be called when a button is clicked. This requires you to write code where data is shared. + +There is a more communications that have to happen between parts of your program when using callbacks. Callbacks can break your program's logic apart and scatter it. One of the larger hurdles for beginners to GUI programming are these callback functions. + +PySimpleGUI was specifically designed in a way that callbacks would not be required. There is no coordination between one function and another required. You simply read your button click and take appropriate action at the same location as when you . + +Whether or not this is a "proper" design for GUI programs can be debated. It's not a terrible trade-off to run your own event loop and having a functioning GUI application versus one that maybe never gets written because callback functions were too much to grasp. + +--- + +## All Widgets / Elements + +This code utilizes as many of the elements in one window as possible. + + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('GreenTan') + + # ------ Menu Definition ------ # + menu_def = [['File', ['Open', 'Save', 'Exit', 'Properties']], + ['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ], + ['Help', 'About...'], ] + + # ------ Column Definition ------ # + column1 = [[sg.Text('Column 1', background_color='#F7F3EC', 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'), initial_value='Spin Box 2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] + + layout = [ + [sg.Menu(menu_def, tearoff=True)], + [sg.Text('All graphic widgets in one window!', size=(30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text')], + [sg.Frame(layout=[ + [sg.Checkbox('Checkbox', size=(10,1)), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10,1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), + sg.Multiline(default_text='A second multi-line', size=(35, 3))], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], + [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), + sg.Frame('Labelled Group',[[ + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), + sg.Column(column1, background_color='#F7F3EC')]])], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder'), sg.FolderBrowse()], + [sg.Submit(tooltip='Click to submit this window'), sg.Cancel()] + ] + + + window = sg.Window('Everything bagel', default_element_size=(40, 1), grab_anywhere=False).Layout(layout) + + button, values = window.Read() + + sg.Popup('Title', + 'The results of the window.', + 'The button clicked was "{}"'.format(button), + 'The values are', values) + +This is a somewhat complex window with quite a bit of custom sizing to make things line up well. This is code you only have to write once. When looking at the code, remember that what you're seeing is a list of lists. Each row contains a list of Graphical Elements that are used to create the window. + + ![everything bagel](https://user-images.githubusercontent.com/13696193/45914128-87163800-be0e-11e8-9a83-7ee5960e88b9.jpg) + +Clicking the Submit button caused the window call to return. The call to Popup resulted in this dialog box. + +![everything bagel reseults](https://user-images.githubusercontent.com/13696193/45914129-87aece80-be0e-11e8-8aae-9a483a9ad4a6.jpg) + + +**`Note, button value can be None`**. The value for `button` will be the text that is displayed on the button element when it was created. If the user closed the window using something other than a button, then `button` will be `None`. + +You can see in the Popup that the values returned are a list. Each input field in the window generates one item in the return values list. All input fields return a `string` except for Check Boxes and Radio Buttons. These return `bool`. + +--- +# Building Custom windows + +You will find it much easier to write code using PySimpleGUI if you use an IDE such as PyCharm. The features that show you documentation about the API call you are making will help you determine which settings you want to change, if any. In PyCharm, two commands are particularly helpful. + + Control-Q (when cursor is on function name) brings up a box with the function definition + Control-P (when cursor inside function call "()") shows a list of parameters and their default values + +## Synchronous windows +The most common use of PySimpleGUI is to display and collect information from the user. The most straightforward way to do this is using a "blocking" GUI call. Execution is "blocked" while waiting for the user to close the GUI window/dialog box. +You've already seen a number of examples above that use blocking windows. Anytime you see a context manager used (see the `with` statement) it's most likely a blocking window. You can examine the show calls to be sure. If the window is a non-blocking window, it must indicate that in the call to `window.show`. + +NON-BLOCKING window call: + + window.Show(non_blocking=True) + +### Beginning a window +The first step is to create the window object using the desired window customization. + + with Window('Everything bagel', auto_size_text=True, default_element_size=(30,1)) as window: + +This is the definition of the Window object: + + def Window(title, + default_element_size=(DEFAULT_ELEMENT_SIZE[0], DEFAULT_ELEMENT_SIZE[1]), + default_button_element_size = (None, None), + auto_size_text=None, + auto_size_buttons=None, + location=(None, None), + font=None, + button_color=None,Font=None, + progress_bar_color=(None,None), + background_color=None + border_depth=None, + auto_close=False, + auto_close_duration=DEFAULT_AUTOCLOSE_TIME, + icon=DEFAULT_WINDOW_ICON, + force_toplevel=False + return_keyboard_events=False, + use_default_focus=True, + text_justification=None, + no_titlebar=False, + grab_anywhere=False + keep_on_top=False): + + +Parameter Descriptions. You will find these same parameters specified for each `Element` and some of them in `Row` specifications. The `Element` specified value will take precedence over the `Row` and `window` values. + + default_element_size - Size of elements in window in characters (width, height) + default_button_element_size - Size of buttons on this window + auto_size_text - Bool. True if elements should size themselves according to contents. Defaults to True + auto_size_buttons - Bool. True if button elements should size themselves according to their text label + location - (x,y) Location to place window in pixels + font - Font name and size for elements of the window + button_color - Default color for buttons (foreground, background). Can be text or hex + progress_bar_color - Foreground and background colors for progress bars + background_color - Color of the window background + border_depth - Amount of 'bezel' to put on input boxes, buttons, etc. + auto_close - Bool. If True window will autoclose + auto_close_duration - Duration in seconds before window closes + icon - .ICO file that will appear on the Task Bar and end of Title Bar + force_top_level - Bool. If set causes a tk.Tk window to be used as primary window rather than tk.TopLevel. Used to get around Matplotlib problem + return_keyboard_events - if True key presses are returned as buttons + use_default_focus - if True and no focus set, then automatically set a focus + text_justification - Justification to use for Text Elements in this window + no_titlebar - Create window without a titlebar + grab_anywhere - Grab any location on the window to move the window + keep_on_top - if True then window will always stop on top of other windows on the screen. Great for floating toolbars. + + +#### Window Location +PySimpleGUI computes the exact center of your window and centers the window on the screen. If you want to locate your window elsewhere, such as the system default of (0,0), if you have 2 ways of doing this. The first is when the window is created. Use the `location` parameter to set where the window. The second way of doing this is to use the `SetOptions` call which will set the default window location for all windows in the future. + +#### Sizes +Note several variables that deal with "size". Element sizes are measured in characters. A Text Element with a size of 20,1 has a size of 20 characters wide by 1 character tall. + +The default Element size for PySimpleGUI is `(45,1)`. + +Sizes can be set at the element level, or in this case, the size variables apply to all elements in the window. Setting `size=(20,1)` in the window creation call will set all elements in the window to that size. + +There are a couple of widgets where one of the size values is in pixels rather than characters. This is true for Progress Meters and Sliders. The second parameter is the 'height' in pixels. + +#### No Titlebar + +Should you wish to create cool looking windows that are clean with no windows titlebar, use the no_titlebar option when creating the window. + +Be sure an provide your user an "exit" button or they will not be able to close the window! When no titlebar is enabled, there will be no icon on your taskbar for the window. Without an exit button you will need to kill via taskmanager... not fun. + +Windows with no titlebar rely on the grab anywhere option to be enabled or else you will be unable to move the window. + +Windows without a titlebar can be used to easily create a floating launcher. + + +![floating launcher](https://user-images.githubusercontent.com/13696193/45258246-71bafb80-b382-11e8-9f5e-79421e6c00bb.jpg) + + +#### Grab Anywhere + +This is a feature unique to PySimpleGUI. The default is ENABLED.... unless the window is a non-blocking window. + +It is turned off for non-blocking because there is a warning message printed out if the user closes a non-blocking window using a button with grab_anywhere enabled. There is no harm in these messages, but it may be distressing to the user. Should you wish to enable for a non-blocking window, simply get grab_anywhere = True when you create the window. + +#### Always on top + +To keep a window on top of all other windows on the screen, set keep_on_top = True when the window is created. This feature makes for floating toolbars that are very helpful and always visible on your desktop. + +### Window Methods (things you can do with a Window object) + +There are a few methods (functions) that you will see in this document that act on Windows. The ones you will primarily be calling are: + + window.Layout(layout) - Turns your definition of the Window into Window + window.Finalize() - creates the tkinter objects for the Window. Normally you do not call this + window.Read() - Read the Windows values and get the button / key that caused the Read to return + window.ReadNonBlocking() - Same as Read but will return right away + window.Refresh() - Use if updating elements and want to show the updates prior to the nex Read + window.Fill(values_dict) - Fill each Element with entry from the dictionary passed in + window.SaveToDisk(filename) - Save the Window's values to disk + window.LoadFromDisk(filename) - Load the Window's values from disk + window.CloseNonBlocking() - When done, for good, reading a non-blocking window + window.Disable() - Use to disable the window inpurt when opening another window on top of the primnary Window + window.Enable() - Re-enable a Disabled window + window.FindElement(key) - Returns the element that has a matching key value + + + +## Elements +"Elements" are the building blocks used to create windows. Some GUI APIs use the term "Widget" to describe these graphic elements. + + Text + Single Line Input + Buttons including these types: + File Browse + Folder Browse + Calendar picker + Date Chooser + Read window + Close window + Realtime + Checkboxes + Radio Buttons + Listbox + Slider + Multi-line Text Input + Scroll-able Output + Progress Bar + Option Menu + Menu + Frame + Column + Graph + Image + Table + Tab, TabGroup + Async/Non-Blocking Windows + Tabbed windows + Persistent Windows + Redirect Python Output/Errors to scrolling Window + "Higher level" APIs (e.g. MessageBox, YesNobox, ...) + +#### Common Parameters +Some parameters that you will see on almost all Elements are: +key +tooltip + +#### Tooltip +Tooltips are text boxes that popup next to an element if you hold your mouse over the top of it. If you want to be extra kind to your window's user, then you can create tooltips for them by setting the parameter `tooltip` to some text string. You will need to supply your own line breaks / text wrapping. If you don't want to manually add them, then take a look at the standard library package `textwrap`. + +Tooltips are one of those "polish" items that really dress-up a GUI and show's a level of sophistication. Go ahead, impress people, throw some tooltips into your GUI. + + + +### Output Elements +Building a window is simply making lists of Elements. Each list is a row in the overall GUI dialog box. The definition looks something like this: + + layout = [ [row 1 element, row 1 element], + [row 2 element, row 2 element, row 2 element] ] +The code is a crude representation of the GUI, laid out in text. + +#### Text Element + + layout = [[sg.Text('This is what a Text Element looks like')]] + + ![simple text](https://user-images.githubusercontent.com/13696193/44959877-e9d97b00-aec3-11e8-9d24-b4405ee4a148.jpg) + + +The most basic element is the Text element. It simply displays text. Many of the 'options' that can be set for a Text element are shared by other elements. + + Text(text + size=(None, None) + auto_size_text=None + click_submits=None + relief=None + font=None + text_color=None + background_color=None + justification=None + pad=None + key=None + tooltip=None) + +. + + Text - The text that's displayed + size - Element's size + click_submits - if clicked will cause a read call to return they key value as the button + relief - relief to use around the text + auto_size_text - Bool. Change width to match size of text + font - Font name and size to use + text_color - text color + background_color - background color + justification - Justification for the text. String - 'left', 'right', 'center' + pad - (x,y) amount of padding in pixels to use around element when packing + key - used to identify element. This value will return as button if click_submits True + tooltip - string representing tooltip + +Some commonly used elements have 'shorthand' versions of the functions to make the code more compact. The functions `T` and `Txt` are the same as calling `Text`. + +**Fonts** in PySimpleGUI are always in this format: + + (font_name, point_size) + +The default font setting is + + ("Helvetica", 10) + +**Color** in PySimpleGUI are in one of two format. They can be a single color or a color pair. Buttons are an example of a color pair. + + (foreground, background) + + Individual colors are specified using either the color names as defined in tkinter or an RGB string of this format: + + "#RRGGBB" + +**auto_size_text** +A `True` value for `auto_size_text`, when placed on Text Elements, indicates that the width of the Element should be shrunk do the width of the text. The default setting is True. + + - [ ] List item + + +**Shortcut functions** +The shorthand functions for `Text` are `Txt` and `T` + +#### Multiline Text Element + + layout = [[sg.Multiline('This is what a Multi-line Text Element looks like', size=(45,5))]] + +![multiline](https://user-images.githubusercontent.com/13696193/44959853-b139a180-aec3-11e8-972f-f52188510c88.jpg) + +This Element doubles as both an input and output Element. The `DefaultText` optional parameter is used to indicate what to output to the window. + + Multiline(default_text='', + enter_submits = False, + size=(None, None), + auto_size_text=None) +. + + default_text - Text to display in the text box + enter_submits - Bool. If True, pressing Enter key submits window + size - Element's size + auto_size_text - Bool. Change width to match size of text + +#### Output Element +Output re-routes `Stdout` to a scrolled text box. It's used with Async windows. More on this later. + + window.AddRow(gg.Output(size=(100,20))) + +![output](https://user-images.githubusercontent.com/13696193/44959863-b72f8280-aec3-11e8-8caa-7bc743149953.jpg) + + Output(size=(None, None)) +. + + size - Size of element (width, height) in characters + +### Input Elements + These make up the majority of the window definition. Optional variables at the Element level override the window level values (e.g. `size` is specified in the Element). All input Elements create an entry in the list of return values. A Text Input Element creates a string in the list of items returned. + +#### Text Input Element + + layout = [[sg.InputText('Default text')]] + +![inputtext 2](https://user-images.githubusercontent.com/13696193/44959861-b5fe5580-aec3-11e8-8040-53ec241b5079.jpg) + + + def InputText(default_text = '', + size=(None, None), + auto_size_text=None, + password_char='', + background_color=None, + text_color=None, + do_not_clear=False, + key=None, + focus=False + +. + + default_text - Text initially shown in the input box + size - (width, height) of element in characters + auto_size_text- Bool. True is element should be sized to fit text + password_char - Character that will be used to replace each entered character. Setting to a value indicates this field is a password entry field + background_color - color to use for the input field background + text_color - color to use for the typed text + do_not_clear - Bool. Normally windows clear when read, turn off clearing with this flag. + key = Dictionary key to use for return values + focus = Bool. True if this field should capture the focus (moves cursor to this field) + + There are two methods that can be called: + + InputText.Update(new_Value) - sets the input value + Input.Text(Get() - returns the current value of the field. + + +Shorthand functions that are equivalent to `InputText` are `Input` and `In` + + +#### Combo Element +Also known as a drop-down list. Only required parameter is the list of choices. The return value is a string matching what's visible on the GUI. + + layout = [[sg.InputCombo(['choice 1', 'choice 2'])]] + +![combobox](https://user-images.githubusercontent.com/13696193/44959860-b565bf00-aec3-11e8-82fe-dbe41252458b.jpg) + + InputCombo(values, , + default_value=None + size=(None, None) + auto_size_text=None + background_color=None + text_color=None + change_submits=False + disabled=False + key=None + pad=None + tooltip=None +. + + values - Choices to be displayed. List of strings + default_value - which value should be initially chosen + size - (width, height) of element in characters + auto_size_text - Bool. True if size should fit the text length + background_color - color to use for the input field background + text_color - color to use for the typed text + change_submits - Bool. If set causes Read to immediately return if the selected value changes + disabled - Bool. If set will disable changes + key - Dictionary key to use for return values + pad - (x,y) Amount of padding to put around element in pixels + tooltip - Text string. If set, hovering over field will popup the text + +#### Listbox Element +The standard listbox like you'll find in most GUIs. Note that the return values from this element will be a ***list of results, not a single result***. This is because the user can select more than 1 item from the list (if you set the right mode). + + layout = [[sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6))]] + +![listbox 2](https://user-images.githubusercontent.com/13696193/44959859-b4cd2880-aec3-11e8-881c-1e369d5c6337.jpg) + + + Listbox(values + default_values=None + select_mode=None + change_submits=False + bind_return_key=False + size=(None, None) + auto_size_text=None + font=None + background_color=None + text_color=None + key=None + pad=None + tooltip=None): + +. + + values - Choices to be displayed. List of strings + select_mode - Defines how to list is to operate. + Choices include constants or strings: + Constants version: + LISTBOX_SELECT_MODE_BROWSE + LISTBOX_SELECT_MODE_EXTENDED + LISTBOX_SELECT_MODE_MULTIPLE + LISTBOX_SELECT_MODE_SINGLE - the default + Strings version: + 'browse' + 'extended' + 'multiple' + 'single' + change_submits - if True, the window read will return with a button value of '' + bind_return_key - if the focus is on the listbox and the user presses return key, or if the user double clicks an item, then the read will return + size - (width, height) of element in characters + auto_size_text - Bool. True if size should fit the text length + background_color - color to use for the input field background + font - font to use for items in list + text_color - color to use for the typed text + key - Dictionary key to use for return values and to find element + pad - amount of padding to use when packing + tooltip - tooltip text + +The `select_mode` option can be a string or a constant value defined as a variable. Generally speaking strings are used for these kinds of options. + +ListBoxes can cause a window to return from a Read call. If the flag change_submits is set, then when a user makes a selection, the Read immediately returns. +Another way ListBoxes can cause Reads to return is if the flag bind_return_key is set. If True, then if the user presses the return key while an entry is selected, then the Read returns. Also, if this flag is set, if the user double-clicks an entry it will return from the Read. + +#### Slider Element + +Sliders have a couple of slider-specific settings as well as appearance settings. Examples include the `orientation` and `range` settings. + + layout = [[sg.Slider(range=(1,500), default_value=222, size=(20,15), orientation='horizontal', font=('Helvetica', 12))]] + +![slider](https://user-images.githubusercontent.com/13696193/44959858-b4349200-aec3-11e8-9e25-c0fcf025d19e.jpg) + + Slider(range=(None,None), + default_value=None, + orientation=None, + border_width=None, + relief=None, + size=(None, None), + font=None, + background_color = None, + change_submits = False, + text_color = None, + key = None) ): +. + + range - (min, max) slider's range + default_value - default setting (within range) + orientation - 'horizontal' or 'vertical' ('h' or 'v' work) + border_width - how deep the widget looks + relief - relief style. Values are same as progress meter relief values. Can be a constant or a string: + RELIEF_RAISED= 'raised' + RELIEF_SUNKEN= 'sunken' + RELIEF_FLAT= 'flat' + RELIEF_RIDGE= 'ridge' + RELIEF_GROOVE= 'groove' + RELIEF_SOLID = 'solid' + size - (width, height) of element in characters + auto_size_text - Bool. True if size should fit the text + background_color - color to use for the input field background + text_color - color to use for the typed text + change_submits - causes window read to immediately return if the checkbox value changes + key = Dictionary key to use for return values + +#### Radio Button Element + +Creates one radio button that is assigned to a group of radio buttons. Only 1 of the buttons in the group can be selected at any one time. + + layout = [[sg.Radio('My first Radio!', "RADIO1", default=True), sg.Radio('My second radio!', "RADIO1")]] + +![radio](https://user-images.githubusercontent.com/13696193/44959857-b4349200-aec3-11e8-8e2d-e6a49ffbd0b6.jpg) + + Radio(text, + group_id, + default=False, + size=(None, None), + auto_size_text=None, + font=None, + background_color = None, + text_color = None, + key = None) + +. + + text - Text to display next to button + group_id - Groups together multiple Radio Buttons. Can be any value + default - Bool. Initial state + size- (width, height) size of element in characters + auto_size_text - Bool. True if should size width to fit text + font - Font type and size for text display + background_color - color to use for the background + text_color - color to use for the text + key = Dictionary key to use for return values + + +#### Checkbox Element +Checkbox elements are like Radio Button elements. They return a bool indicating whether or not they are checked. + + layout = [[sg.Checkbox('My first Checkbox!', default=True), sg.Checkbox('My second Checkbox!')]] + + +![checkbox](https://user-images.githubusercontent.com/13696193/44959906-6f5d2b00-aec4-11e8-9c8a-962c787f0286.jpg) + + + Checkbox(text, + default=False, + size=(None, None), + auto_size_text=None, + font=None, + background_color = None, + text_color = None, + change_submits = False + key = None): +. + + text - Text to display next to checkbox + default- Bool + None. Initial state. True = Checked, False = unchecked, None = Not available (grayed out) + size - (width, height) size of element in characters + auto_size_text- Bool. True if should size width to fit text + font- Font type and size for text display + background_color - color to use for the background + text_color - color to use for the typed text + change_submits - causes window read to immediately return if the checkbox value changes + key = Dictionary key to use for return values + + +#### Spin Element + +An up/down spinner control. The valid values are passed in as a list. + + layout = [[sg.Spin([i for i in range(1,11)], initial_value=1), sg.Text('Volume level')]] + +![spinner](https://user-images.githubusercontent.com/13696193/44959855-b1d23800-aec3-11e8-9f51-afb2109879da.jpg) + + Spin(values, + intiial_value=None, + size=(None, None), + auto_size_text=None, + font=None, + background_color = None, + text_color = None, + key = None): +. + + values - List of valid values + initial_value - String with initial value + size - (width, height) size of element in characters + auto_size_text - Bool. True if should size width to fit text + font - Font type and size for text display + background_color - color to use for the background + text_color - color to use for the typed text + change_submits - causes window read to immediately return if the spinner value changes + key = Dictionary key to use for return values + +### Button Element + +Buttons are the most important element of all! They cause the majority of the action to happen. After all, it's a button press that will get you out of a window, whether it be Submit or Cancel, one way or another a button is involved in all windows. The only exception is to this is when the user closes the window using the "X" in the upper corner which means no button was involved. + +The Types of buttons include: +* Folder Browse +* File Browse +* Files Browse +* File SaveAs +* File Save +* Close window (normal button) +* Read window +* Realtime +* Calendar Chooser +* Color Chooser + + + Close window - Normal buttons like Submit, Cancel, Yes, No, etc, are "Close window" buttons. They cause the input values to be read and then the window is ***closed***, returning the values to the caller. + +Folder Browse - When clicked a folder browse dialog box is opened. The results of the Folder Browse dialog box are written into one of the input fields of the window. + +File Browse - Same as the Folder Browse except rather than choosing a folder, a single file is chosen. + +Calendar Chooser - Opens a graphical calendar to select a date. + +Color Chooser - Opens a color chooser dialog + +Read window - This is a window button that will read a snapshot of all of the input fields, but does not close the window after it's clicked. + +Realtime - This is another async window button. Normal button clicks occur after a button's click is released. Realtime buttons report a click the entire time the button is held down. + +Most programs will use a combination of shortcut button calls (Submit, Cancel, etc), plain buttons that close the window, and ReadForm buttons that keep the window open but returns control back to the caller. + +Sometimes there are multiple names for the same function. This is simply to make the job of the programmer quicker and easier. + +The 3 primary windows of PySimpleGUI buttons and their names are: + + 1. `Button` = `SimpleButton` + 2. `ReadButton` = `RButton` = `ReadFormButton` (old style... use ReadButton instead) + 3. `RealtimeButton` + +You will find the long-form in the older programs. + +The most basic Button element call to use is `Button` + + Button(button_text='' + button_type=BUTTON_TYPE_CLOSES_WIN + target=(None, None) + tooltip=None + file_types=(("ALL Files", "*.*"),) + initial_folder=None + image_filename=None + image_size=(None, None) + image_subsample=None + border_width=None + size=(None, None) + auto_size_button=None + button_color=None + default_value = None + font=None + bind_return_key=False + focus=False + pad=None + key=None): + +Parameters + + button_text - Text to be displayed on the button + button_type - You should NOT be setting this directly + target - key or (row,col) target for the button + tooltip - tooltip text for the button + file_types - the filetypes that will be used to match files + initial_folder - starting path for folders and files + image_filename - image filename if there is a button image + image_size - size of button image in pixels + image_subsample - amount to reduce the size of the image + border_width - width of border around button in pixels + size - size in characters + auto_size_button - True if button size is determined by button text + button_color - (text color, backound color) + default_value - initial value for buttons that hold information + font - font to use for button text + bind_return_key - If True the return key will cause this button to fire + focus - if focus should be set to this button + pad - (x,y) padding in pixels for packing the button + key - key used for finding the element + +#### Pre-defined Buttons +These Pre-made buttons are some of the most important elements of all because they are used so much. They all basically do the same thing, set the button text to match the function name and set the parameters to commonly used values. If you find yourself needing to create a custom button often because it's not on this list, please post a request on GitHub. . They include: + + OK + Ok + Submit + Cancel + Yes + No + Exit + Quit + Help + Save + SaveAs + FileBrowse + FilesBrowse + FileSaveAs + FolderBrowse +. + layout = [[sg.OK(), sg.Cancel()]] + +![ok cancel 3](https://user-images.githubusercontent.com/13696193/44959927-aa5f5e80-aec4-11e8-86e1-5dc0b3a2b803.jpg) + + #### Button targets + +The `FileBrowse`, `FolderBrowse`, `FileSaveAs` , `FilesSaveAs`, `CalendarButton`, `ColorChooserButton` buttons all fill-in values into another element located on the window. The target can be a Text Element or an InputText Element. The location of the element is specified by the `target` variable in the function call. + +The Target comes in two forms. +1. Key +2. (row, column) + +Targets that are specified using a key will find its target element by using the target's key value. This is the "preferred" method. + +If the Target is specified using (row, column) then it utilizes a grid system. The rows in your GUI are numbered starting with 0. The target can be specified as a hard coded grid item or it can be relative to the button. + +The (row, col) targeting can only target elements that are in the same "container". Containers are the Window, Column and Frame Elements. A File Browse button located inside of a Column is unable to target elements outside of that Column. + +The default value for `target` is `(ThisRow, -1)`. `ThisRow` is a special value that tells the GUI to use the same row as the button. The Y-value of -1 means the field one value to the left of the button. For a File or Folder Browse button, the field that it fills are generally to the left of the button is most cases. (ThisRow, -1) means the Element to the left of the button, on the same row. + +If a value of `(None, None)` is chosen for the target, then the button itself will hold the information. Later the button can be queried for the value by using the button's key. + +Let's examine this window as an example: + + +![file browse](https://user-images.githubusercontent.com/13696193/44959944-d1b62b80-aec4-11e8-8a68-9d79d37b2c81.jpg) + + +The `InputText` element is located at (1,0)... row 1, column 0. The `Browse` button is located at position (2,0). The Target for the button could be any of these values: + + Target = (1,0) + Target = (-1,0) + +The code for the entire window could be: + + layout = [[sg.T('Source Folder')], + [sg.In()], + [sg.FolderBrowse(target=(-1, 0)), sg.OK()]] + +or if using keys, then the code would be: + + layout = [[sg.T('Source Folder')], + [sg.In(key='input')], + [sg.FolderBrowse(target='input'), sg.OK()]] + +See how much easier the key method is? + +**Save & Open Buttons** + +There are 3 different types of File/Folder open dialog box available. If you are looking for a file to open, the `FileBrowse` is what you want. If you want to save a file, `SaveAs` is the button. If you want to get a folder name, then `FolderBrowse` is the button to use. To open several files at once, use the `FilesBrowse` button. It will create a list of files that are separated by ';' + + +![open](https://user-images.githubusercontent.com/13696193/45243804-2b529780-b2c3-11e8-90dc-6c9061db2a1e.jpg) + + +![folder](https://user-images.githubusercontent.com/13696193/45243805-2b529780-b2c3-11e8-95ee-fec3c0b11319.jpg) + + +![saveas](https://user-images.githubusercontent.com/13696193/45243807-2beb2e00-b2c3-11e8-8549-ba71cdc05951.jpg) + + + +**Calendar Buttons** + +These buttons pop up a calendar chooser window. The chosen date is returned as a string. + +![calendar](https://user-images.githubusercontent.com/13696193/45243374-99965a80-b2c1-11e8-8311-49777835ca40.jpg) + +**Color Chooser Buttons** + +These buttons pop up a standard color chooser window. The result is returned as a tuple. One of the returned values is an RGB hex representation. + +![color](https://user-images.githubusercontent.com/13696193/45243375-99965a80-b2c1-11e8-9779-b71bed85fab6.jpg) + + +**Custom Buttons** +Not all buttons are created equal. A button that closes a window is different that a button that returns from the window without closing it. If you want to define your own button, you will generally do this with the Button Element `Button`, which closes the window when clicked. + +layout = [[sg.Button('My Button')]] + +![button](https://user-images.githubusercontent.com/13696193/44959862-b696ec00-aec3-11e8-9e88-4b9af0338a03.jpg) + +All buttons can have their text changed by changing the `button_text` variable in the button call. It is this text that is returned when a window is read. This text will be what tells you which button is called so make it unique. Most of the convenience buttons (Submit, Cancel, Yes, etc) are all Buttons. Some that are not are `FileBrowse` , `FolderBrowse`, `FileSaveAs`. They clearly do not close the window. Instead they bring up a file or folder browser dialog box. + +**Button Images** +Now this is an exciting feature not found in many simplified packages.... images on buttons! You can make a pretty spiffy user interface with the help of a few button images. + +Your button images need to be in PNG or GIF format. When you make a button with an image, set the button background to the same color as the background. There's a button color TRANSPARENT_BUTTON that you can set your button color to in order for it to blend into the background. Note that this value is currently the same as the color as the default system background on Windows. + +This example comes from the `Demo Media Player.py` example program. Because it's a non-blocking button, it's defined as `RButton`. You also put images on blocking buttons by using `Button`. + + + sg.RButton('Restart Song', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0) + +Three parameters are used for button images. + + image_filename - Filename. Can be a relative path + image_size - Size of image file in pixels + image_subsample - Amount to divide the size by. 2 means your image will be 1/2 the size. 3 means 1/3 + +Here's an example window made with button images. + +![media file player](https://user-images.githubusercontent.com/13696193/43161977-9ee7cace-8f57-11e8-8ff8-3ea24b69dab9.jpg) + +You'll find the source code in the file Demo Media Player. Here is what the button calls look like to create media player window + + sg.RButton('Pause', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_pause, image_size=(50, 50), image_subsample=2, border_width=0) + +This is one you'll have to experiment with at this point. Not up for an exhaustive explanation. + + **Realtime Buttons** + + Normally buttons are considered "clicked" when the mouse button is let UP after a downward click on the button. What about times when you need to read the raw up/down button values. A classic example for this is a robotic remote control. Building a remote control using a GUI is easy enough. One button for each of the directions is a start. Perhaps something like this: + +![robot remote](https://user-images.githubusercontent.com/13696193/44959958-ff9b7000-aec4-11e8-99ea-7450926409be.jpg) + + +This window has 2 button types. There's the normal "Simple Button" (Quit) and 4 "Realtime Buttons". + +Here is the code to make, show and get results from this window: + + window = sg.Window('Robotics Remote Control', auto_size_text=True) + + window_rows = [[sg.Text('Robotics Remote Control')], + [sg.T(' '*10), sg.RealtimeButton('Forward')], + [ sg.RealtimeButton('Left'), sg.T(' '*15), sg.RealtimeButton('Right')], + [sg.T(' '*10), sg.RealtimeButton('Reverse')], + [sg.T('')], + [sg.Quit(button_color=('black', 'orange'))] + ] + + window.LayoutAndRead(window_rows, non_blocking=True) + +Somewhere later in your code will be your main event loop. This is where you do your polling of devices, do input/output, etc. It's here that you will read your window's buttons. + + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + if button is not None: + sg.Print(button) + if button == 'Quit' or values is None: + break + time.sleep(.01) + +This loop will read button values and print them. When one of the Realtime buttons is clicked, the call to `window.ReadNonBlocking` will return a button name matching the name on the button that was depressed. It will continue to return values as long as the button remains depressed. Once released, the ReadNonBlocking will return None for buttons until a button is again clicked. + +**File Types** +The `FileBrowse` & `SaveAs` buttons have an additional setting named `file_types`. This variable is used to filter the files shown in the file dialog box. The default value for this setting is + + FileTypes=(("ALL Files", "*.*"),) + +This code produces a window where the Browse button only shows files of type .TXT + + layout = [[sg.In() ,sg.FileBrowse(file_types=(("Text Files", "*.txt"),))]] + + ***The ENTER key*** + The ENTER key is an important part of data entry for windows. There's a long tradition of the enter key being used to quickly submit windows. PySimpleGUI implements this by tying the ENTER key to the first button that closes or reads a window. + +The Enter Key can be "bound" to a particular button so that when the key is pressed, it causes the window to return as if the button was clicked. This is done using the `bind_return_key` parameter in the button calls. +If there are more than 1 button on a window, the FIRST button that is of type Close window or Read window is used. First is determined by scanning the window, top to bottom and left to right. + + --- +#### ProgressBar +The `ProgressBar` element is used to build custom Progress Bar windows. It is HIGHLY recommended that you use OneLineProgressMeter that provides a complete progress meter solution for you. Progress Meters are not easy to work with because the windows have to be non-blocking and they are tricky to debug. + +The **easiest** way to get progress meters into your code is to use the `OneLineProgressMeter` API. This consists of a pair of functions, `OneLineProgressMeter` and `OneLineProgressMeterCancel`. You can easily cancel any progress meter by calling it with the current value = max value. This will mark the meter as expired and close the window. +You've already seen OneLineProgressMeter calls presented earlier in this readme. + + sg.OneLineProgressMeter('My Meter', i+1, 1000, 'key', 'Optional message') + +The return value for `OneLineProgressMeter` is: +`True` if meter updated correctly +`False` if user clicked the Cancel button, closed the window, or vale reached the max value. + +#### Progress Mater in Your window +Another way of using a Progress Meter with PySimpleGUI is to build a custom window with a `ProgressBar` Element in the window. You will need to run your window as a non-blocking window. When you are ready to update your progress bar, you call the `UpdateBar` method for the `ProgressBar` element itself. + +![progress custom](https://user-images.githubusercontent.com/13696193/45243969-c3508100-b2c3-11e8-82bc-927d0307e093.jpg) + + import PySimpleGUI as sg + + # layout the window + layout = [[sg.Text('A custom progress meter')], + [sg.ProgressBar(10000, orientation='h', size=(20, 20), key='progressbar')], + [sg.Cancel()]] + + # create the window` + window = sg.Window('Custom Progress Meter').Layout(layout) + progress_bar = window.FindElement('progressbar') + # loop that would normally do something useful + for i in range(10000): + # check to see if the cancel button was clicked and exit loop if clicked + button, values = window.ReadNonBlocking() + if button == 'Cancel' or values == None: + break + # update bar with loop value +1 so that bar eventually reaches the maximum + progress_bar.UpdateBar(i + 1) + # done with loop... need to destroy the window as it's still open + window.CloseNonBlocking()) + + +#### Output +The Output Element is a re-direction of Stdout. Anything "printed" will be displayed in this element. + + Output(size=(None, None)) + +Here's a complete solution for a chat-window using an Async window with an Output Element + + import PySimpleGUI as sg + + # Blocking window that doesn't close + def ChatBot(): + layout = [[(sg.Text('This is where standard out is being routed', size=[40, 1]))], + [sg.Output(size=(80, 20))], + [sg.Multiline(size=(70, 5), enter_submits=True), + sg.RButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0])), + sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]] + + window = sg.Window('Chat Window', default_element_size=(30, 2)).Layout(layout) + + # ---===--- Loop taking in user input and using it to query HowDoI web oracle --- # + while True: + button, value = window.Read() + if button == 'SEND': + print(value) + else: + break + + ChatBot() + +------------------- +## Columns +Starting in version 2.9 you'll be able to do more complex layouts by using the Column Element. Think of a Column as a window within a window. And, yes, you can have a Column within a Column if you want. + +Columns are specified in exactly the same way as a window is, as a list of lists. + + def Column(layout - the list of rows that define the layout + background_color - color of background + size - size of visible portion of column + pad - element padding to use when packing + scrollable - bool. True if should add scrollbars + + +Columns are needed when you have an element that has a height > 1 line on the left, with single-line elements on the right. Here's an example of this kind of layout: + + +![column](https://user-images.githubusercontent.com/13696193/44959988-66b92480-aec5-11e8-9c26-316ed24a68c0.jpg) + + +This code produced the above window. + + + import PySimpleGUI as sg + + # Demo of how columns work + # window has on row 1 a vertical slider followed by a COLUMN with 7 rows + # Prior to the Column element, this layout was not possible + # Columns layouts look identical to window layouts, they are a list of lists of elements. + + window = sg.Window('Columns') # blank window + + # Column layout + col = [[sg.Text('col Row 1')], + [sg.Text('col Row 2'), sg.Input('col input 1')], + [sg.Text('col Row 3'), sg.Input('col input 2')], + [sg.Text('col Row 4'), sg.Input('col input 3')], + [sg.Text('col Row 5'), sg.Input('col input 4')], + [sg.Text('col Row 6'), sg.Input('col input 5')], + [sg.Text('col Row 7'), sg.Input('col input 6')]] + + layout = [[sg.Slider(range=(1,100), default_value=10, orientation='v', size=(8,20)), sg.Column(col)], + [sg.In('Last input')], + [sg.OK()]] + + # Display the window and get values + # If you're willing to not use the "context manager" design pattern, then it's possible + # to collapse the window display and read down to a single line of code. + button, values = sg.Window('Compact 1-line window with column').LayoutAndRead(layout) + + sg.Popup(button, values, line_width=200) + +The Column Element has 1 required parameter and 1 optional (the layout and the background color). Setting the background color has the same effect as setting the window's background color, except it only affects the column rectangle. + + Column(layout, background_color=None) + +The default background color for Columns is the same as the default window background color. If you change the look and feel of the window, the column background will match the window background automatically. + + + +---- +## Frames (Labelled Frames, Frames with a title) + +Frames work exactly the same way as Columns. You create layout that is then used to initialize the Frame. + + def Frame(title - the label / title to put on frame + layout - list of rows of elements the frame contains + title_color - color of the title text + background_color - color of background + title_location - locations to put the title + relief - type of relief to use + size - size of Frame in characters. Do not use if you want frame to autosize + font - font to use for title + pad - element padding to use when packing + border_width - how thick the line going around frame should be + key - key used to location the element + tooltip - tooltip text + + + +This code creates a window with a Frame and 2 buttons. + + frame_layout = [ + [sg.T('Text inside of a frame')], + [sg.CB('Check 1'), sg.CB('Check 2')], + ] + layout = [ + [sg.Frame('My Frame Title', frame_layout, font='Any 12', title_color='blue')], + [sg.Submit(), sg.Cancel()] + ] + + window = sg.Window('Frame with buttons', font=("Helvetica", 12)).Layout(layout) + + +![frame element](https://user-images.githubusercontent.com/13696193/45889173-c2245700-bd8d-11e8-8f73-1e5f1be3ddb1.jpg) + + + +Notice how the Frame layout looks identical to a window layout. A window works exactly the same way as a Column and a Frame. They all are "container elements". Elements that contain other elements. + +*These container Elements can be nested as deep as you want.* That's a pretty spiffy feature, right? Took a lot of work so be appreciative. Recursive code isn't trivial. + +## Canvas Element + +In my opinion, the tkinter Canvas Widget is the most powerful of the tkinter widget. While I try my best to completely isolate the user from anything that is tkinter related, the Canvas Element is the one exception. It enables integration with a number of other packages, often with spectacular results. + +### Matplotlib, Pyplot Integration + +One such integration is with Matploplib and Pyplot. There is a Demo program written that you can use as a design pattern to get an understanding of how to use the Canvas Widget once you get it. + + def Canvas(canvas - a tkinter canvasf if you created one. Normally not set + background_color - canvas color + size - size in pixels + pad - element padding for packing + key - key used to lookup element + tooltip - tooltip text + +The order of operations to obtain a tkinter Canvas Widget is: + + figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds + # define the window layout + layout = [[sg.Text('Plot test')], + [sg.Canvas(size=(figure_w, figure_h), key='canvas')], + [sg.OK(pad=((figure_w / 2, 0), 3), size=(4, 2))]] + + # create the window and show it without the plot + window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize() + + + # add the plot to the window + fig_photo = draw_figure(window.FindElement('canvas').TKCanvas, fig) + + # show it all again and get buttons + button, values = window.Read() + +To get a tkinter Canvas Widget from PySimpleGUI, follow these steps: +* Add Canvas Element to your window +* Layout your window +* Call `window.Finalize()` - this is a critical step you must not forget +* Find the Canvas Element by looking up using key +* Your Canvas Widget Object will be the found_element.TKCanvas +* Draw on your canvas to your heart's content +* Call `window.Read()` - Nothing will appear on your canvas until you call Read + +See `Demo_Matplotlib.py` for a Recipe you can copy. + + +## Graph Element + +All you math fans will enjoy this Element... and all you non-math fans will enjoy it too. + +I've found nothing to be less fun than dealing with a graphic's coordinate system from a GUI Framework. It's always upside down from what I want. (0,0) is in the upper left hand corner. In short, it's a **pain in the ass**. + +Graph Element to the rescue. A Graph Element creates a pixel addressable canvas using YOUR coordinate system. *You* get to define the units on the X and Y axis. + +There are 3 values you'll need to supply the Graph Element. They are: +* Size of the canvas in pixels +* The lower left (x,y) coordinate of your coordinate system +* The upper right (x,y) coordinate of your coordinate system + +After you supply those values you can scribble all of over your graph by creating Graph Figures. Graph Figures are created, and a Figure ID is obtained by calling: +* DrawCircle +* DrawLine +* DrawPoint +* DrawRectangle +* DrawOval + +You can move your figures around on the canvas by supplying the Figure ID the x,y amount to move. + + graph.MoveFigure(my_circle, 10, 10) + +This Element is relatively new and may have some parameter additions or deletions. It shouldn't break your code however. + + def Graph( canvas_size - size of canvas in pixels + graph_bottom_left - the x,y location of your coordinate system's bottom left point + graph_top_right - the x,y location of your coordinate system's top right point + background_color - color to use for background + pad - element padding for pack + key - key used to lookup element + tooltip - tooltip text + + + +## Table Element + +Let me say up front that the Table Element has Beta status. The reason is that some of the parameters are not quite right and will change. Be warned one or two parameters may change. The `size` parameter in particular is gong to change. Currently the number of rows to allocate for the table is set by the height parameter of size. The problem is that the width is not used. The plan is to instead have a parameter named `number_of_rows` or something like it. + + def Table(values - Your table's array + headings - list of strings representing your headings, if you have any + visible_column_map - list of bools. If True, column in that position is shown. Defaults to all columns + col_widths - list of column widths + def_col_width - default column width. defaults to 10 + auto_size_columns - bool. If True column widths are determined by table contents + max_col_width - maximum width of a column. defaults to 25 + select_mode - table rows can be selected, but doesn't currently do anything + display_row_numbers - bool. If True shows numbers next to rows + scrollable - if True table will be scrolled + font - font for table entries + justification - left, right, center + text_color - color of text + background_color - cell background color + size - (None, number of rows). + pad - element padding for packing + key - key used to lookup element + tooltip - tooltip text + + + + +## Tab and Tab Group Elements + +Tabs have been a part of PySimpleGUI since the initial release. However, the initial implementation applied tabs at the top level only. The entire window had to be tabbed. There with other limitations that came along with that implementation. That all changed in version 3.8.0 with the new elements - Tab and TabGroup. The old implementation of Tabs was removed in version 3.8.0 as well. + +Tabs are another "Container Element". The other Container Elements include: +* Frame +* Column + +You layout a Frame in exactly the same way as a Frame or Column elements, by passing in a list of elements. + +How you place a Tab into a Window is different than Graph or Frame elements. You cannot place a tab directly into a Window's layout. It much first be placed into a TabGroup. The TabGroup can then be placed into the Window. + +Let's look at this Window as an example: + +![tabbed 1](https://user-images.githubusercontent.com/13696193/45992808-b10f6a80-c059-11e8-9746-ac71afd4d3d6.jpg) + +View of second tab: + +![tabbed 2](https://user-images.githubusercontent.com/13696193/45992809-b10f6a80-c059-11e8-94e6-3bf543c9b0bd.jpg) + + +First we have the Tab layout definitions. They mirror what you see in the screen shots. Tab 1 has 1 Text Element in it. Tab 2 has a Text and an Input Element. + + + tab1_layout = [[sg.T('This is inside tab 1')]] + + tab2_layout = [[sg.T('This is inside tab 2')], + [sg.In(key='in')]] + +The layout for the entire window looks like this: + + layout = [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout), sg.Tab('Tab 2', tab2_layout)]])], + [sg.RButton('Read')]] + +The Window layout has the TabGroup and within the tab Group are the two Tab elements. + +One important thing to notice about all of these container Elements... they all take a "list of lists" at the layout. They all have a layout that starts with `[[` + +You will want to keep this `[[ ]]` construct in your head a you're debugging your tabbed windows. It's easy to overlook one or two necessary ['s + +As mentioned earlier, the old-style Tabs were limited to being at the Window-level only. In other words, the tabs were equal in size to the entire window. This is not the case with the "new-style" tabs. This is why you're not going to be upset when you discover your old code no longer works with the new PySimpleGUI release. It'll be worth the few moments it'll take to convert your code. + +Check out what's possible with the NEW Tabs! + +![tabs tabs tabs](https://user-images.githubusercontent.com/13696193/45993438-fd0fde80-c05c-11e8-9ed0-742f14d3070f.jpg) + + +Check out Tabs 7 and 8. We've got a Window with a Column containing Tabs 5 and 6. On Tab 6 are... Tabs 7 and 8. + +As of Release 3.8.0, not all of *options* shown in the API definitions of the Tab and TabGroup Elements are working. They are there as placeholders. + +The definition of a TabGroup is + + TabGroup(layout, + title_color=None + background_color=None + font=None + pad=None + border_width=None + change_submits = False + key=None + tooltip=None) + +The definition of a Tab Element is + + Tab(title, + layout, + title_color=None, + background_color=None, + size=(None, None),font=None, + pad=None + border_width=None + change_submits=False + key=None + tooltip=None) + + + ## Colors ## +Starting in version 2.5 you can change the background colors for the window and the Elements. + +Your windows can go from this: + +![snap0155](https://user-images.githubusercontent.com/13696193/43273879-a9fdc10a-90cb-11e8-8c20-4f6a244ebe2f.jpg) + + +to this... with one function call... + + +![snap0156](https://user-images.githubusercontent.com/13696193/43273880-aa1955e6-90cb-11e8-94b6-673ecdb2698c.jpg) + + + +While you can do it on an element by element or window level basis, the easiest way, by far, is a call to `SetOptions`. + +Be aware that once you change these options they are changed for the rest of your program's execution. All of your windows will have that look and feel, until you change it to something else (which could be the system default colors. + +This call sets all of the different color options. + + SetOptions(background_color='#9FB8AD', + text_element_background_color='#9FB8AD', + element_background_color='#9FB8AD', + scrollbar_color=None, + input_elements_background_color='#F7F3EC', + progress_meter_color = ('green', 'blue') + button_color=('white','#475841')) + + + +## Global Settings +**Global Settings** +Let's have some fun customizing! Make PySimpleGUI look the way you want it to look. You can set the global settings using the function `PySimpleGUI.SetOptions`. Each option has an optional parameter that's used to set it. + + SetOptions(icon=None + button_color=(None,None) + element_size=(None,None), + margins=(None,None), + element_padding=(None,None) + auto_size_text=None + auto_size_buttons=None + font=None + border_width=None + slider_border_width=None + slider_relief=None + slider_orientation=None + autoclose_time=None + message_box_line_width=None + progress_meter_border_depth=None + progress_meter_style=None + progress_meter_relief=None + progress_meter_color=None + progress_meter_size=None + text_justification=None + text_color=None + background_color=None + element_background_color=None + text_element_background_color=None + input_elements_background_color=None + element_text_color=None + input_text_color=None + scrollbar_color=None, text_color=None + debug_win_size=(None,None) + window_location=(None,None) + tooltip_time = None + +Explanation of parameters + + icon - filename of icon used for taskbar and title bar + button_color - button color (foreground, background) + element_size - element size (width, height) in characters + margins - tkinter margins around outsize + element_padding - tkinter padding around each element + auto_size_text - autosize the elements to fit their text + auto_size_buttons - autosize the buttons to fit their text + font - font used for elements + border_width - amount of bezel or border around sunken or raised elements + slider_border_width - changes the way sliders look + slider_relief - changes the way sliders look + slider_orientation - changes orientation of slider + autoclose_time - time in seconds for autoclose boxes + message_box_line_width - number of characers in a line of text in message boxes + progress_meter_border_depth - amount of border around raised or lowered progress meters + progress_meter_style - style of progress meter as defined by tkinter + progress_meter_relief - relief style + progress_meter_color - color of the bar and background of progress meters + progress_meter_size - size in (characters, pixels) + background_color - Color of the main window's background + element_background_color - Background color of the elements + text_element_background_color - Text element background color + input_elements_background_color - Input fields background color + element_text_color - Text color of elements that have text, like Radio Buttons + input_text_color - Color of the text that you type in + scrollbar_color - Color for scrollbars (may not always work) + text_color - Text element default text color + text_justification - justification to use on Text Elements. Values are strings - 'left', 'right', 'center' + debug_win_size - size of the Print output window + window_location - location on the screen (x,y) of window's top left cornder + tooltip_time - time in milliseconds to wait before showing a tooltip. Default is 400ms + + +These settings apply to all windows `SetOptions`. The Row options and Element options will take precedence over these settings. Settings can be thought of as levels of settings with the window-level being the highest and the Element-level the lowest. Thus the levels are: + + - window level + - Row level + - Element level + +Each lower level overrides the settings of the higher level. Once settings have been changed, they remain changed for the duration of the program (unless changed again). + +## Persistent windows (Window stays open after button click) + +There are 2 ways to keep a window open after the user has clicked a button. One way is to use non-blocking windows (see the next section). The other way is to use buttons that 'read' the window instead of 'close' the window when clicked. The typical buttons you find in windows, including the shortcut buttons, close the window. These include OK, Cancel, Submit, etc. The Button Element also closes the window. + +The `RButton` Element creates a button that when clicked will return control to the user, but will leave the window open and visible. This button is also used in Non-Blocking windows. The difference is in which call is made to read the window. The `Read` call will block, the `ReadNonBlocking` will not block. + + + +## Asynchronous (Non-Blocking) windows +So you want to be a wizard do ya? Well go boldly! + +Use async windows sparingly. It's possible to have a window that appears to be async, but it is not. **Please** try to find other methods before going to async windows. The reason for this plea is that async windows poll tkinter over and over. If you do not have a sleep in your loop, you will eat up 100% of the CPU time. + +When to use a non-blocking window: +* A media file player like an MP3 player +* A status dashboard that's periodically updated +* Progress Meters - when you want to make your own progress meters +* Output using print to a scrolled text element. Good for debugging. + +If your application doesn't follow the basic design pattern at one of those, then it shouldn't be executed as a non-blocking window. + + +### Instead of ReadNonBlocking --- Use `change_submits = True` or return_keyboard_events = True + +Any time you are thinking "I want an X Element to cause a Y Element to do something", then you want to use the `change_submits` option. + +***Instead of polling, try options that cause the window to return to you.*** By using non-blocking windows, you are *polling*. You can indeed create your application by polling. It will work. But you're going to be maxing out your processor and may even take longer to react to an event than if you used another technique. + +**Examples** + +One example is you have an input field that changes as you press buttons on an on-screen keypad. + +![keypad 3](https://user-images.githubusercontent.com/13696193/45260275-a2198e80-b3b0-11e8-85fe-a4ce6484510f.jpg) + + + + +### Periodically Calling`ReadNonBlocking` + +Periodically "refreshing" the visible GUI. The longer you wait between updates to your GUI the more sluggish your windows will feel. It is up to you to make these calls or your GUI will freeze. + +There are 2 methods of interacting with non-blocking windows. +1. Read the window just as you would a normal window +2. "Refresh" the window's values without reading the window. It's a quick operation meant to show the user the latest values + + With asynchronous windows the window is shown, user input is read, but your code keeps right on chugging. YOUR responsibility is to call `PySimpleGUI.ReadNonBlocking` on a periodic basis. Once a second or more will produce a reasonably snappy GUI. + + #### Exiting a Non-Blocking window + +It's important to always provide a "way out" for your user. Make sure you have provided a button or some other mechanism to exit. Also be sure to check for closed windows in your code. It is possible for a window to look closed, but continue running your event loop. + +Typically when reading a window you check `if Button is None` to determine if a window was closed. With NonBlocking windows, buttons will be None unless a button or a key was returned. The way you determine if a window was closed in a non-blocking window is to check **both** the button and the values are None. Since button is normally None, you only need to test for `value is None` in your code. + +The proper code to check if the user has exited the window will be a polling-loop that looks something like this: + + while True: + button, values = window.ReadNonBlocking() + if values is None or button == 'Quit': + break + + +We're going to build an app that does the latter. It's going to update our window with a running clock. + +The basic flow and functions you will be calling are: +Setup + + window = Window() + window_rows = ..... + window.LayoutAndRead(window_rows, non_blocking=True) + + +Periodic refresh + + window.ReadNonBlocking() or window.Refresh() + +If you need to close the window + + window.CloseNonBlocking() + +Rather than the usual `window.LayoutAndRead()` call, we're manually adding the rows (doing the layout) and then showing the window. After the window is shown, you simply call `window.ReadNonBlocking()` every now and then. + +When you are ready to close the window (assuming the window wasn't closed by the user or a button click) you simply call `window.CloseNonBlocking()` + +**Example - Running timer that updates** +See the sample code on the GitHub named Demo Media Player for another example of Async windows. We're going to make a window and update one of the elements of that window every .01 seconds. Here's the entire code to do that. + + + import PySimpleGUI as sg + import time + + # window that doesn't block + # Make a window, but don't use context manager + window = sg.Window('Running Timer', auto_size_text=True) + + # Create the layout + window_rows = [[sg.Text('Non-blocking GUI with updates')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), key='output') ], + [sg.Button('Quit')]] + # Layout the rows of the window and perform a read. Indicate the window is non-blocking! + window.LayoutAndRead(window_rows, non_blocking=True) + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your window every now and then or + # else it won't refresh + # + + for i in range(1, 1000): + window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format(*divmod(int(i / 100), 60), i % 100)) + button, values = window.ReadNonBlocking() + if values is None or button == 'Quit': + break + time.sleep(.01) + else: + window.CloseNonBlocking() + + +What we have here is the same sequence of function calls as in the description. Get a window, add rows to it, show the window, and then refresh it every now and then. + +The new thing in this example is the call use of the Update method for the Text Element. The first thing we do inside the loop is "update" the text element that we made earlier. This changes the value of the text field on the window. The new value will be displayed when `window.ReadNonBlocking()` is called. if you want to have the window reflect your changes immediately, call `window.Refresh()`. + +Note the `else` statement on the for loop. This is needed because we're about to exit the loop while the window is still open. The user has not closed the window using the X nor a button so it's up to the caller to close the window using `CloseNonBlocking`. + +## Updating Elements (changing elements in active window) + +Persistent windows remain open and thus continue to interact with the user after the Read has returned. Often the program wishes to communicate results (output information) or change an Element's values (such as populating a List Element). + +The way this is done is via an Update method that is available for nearly all of the Elements. Here is an example of a program that uses a persistent window that is updated. + +![snap0272](https://user-images.githubusercontent.com/13696193/45260249-ec4e4000-b3af-11e8-853b-9b29d0bf7797.jpg) + + +In some programs these updates happen in response to another Element. This program takes a Spinner and a Slider's input values and uses them to resize a Text Element. The Spinner and Slider are on the left, the Text element being changed is on the right. + + + + + + # Testing async window, see if can have a slider + # that adjusts the size of text displayed + + import PySimpleGUI as sg + fontSize = 12 + layout = [[sg.Spin([sz for sz in range(6, 172)], font=('Helvetica 20'), initial_value=fontSize, change_submits=True, key='spin'), + sg.Slider(range=(6,172), orientation='h', size=(10,20), + change_submits=True, key='slider', font=('Helvetica 20')), + sg.Text("Aa", size=(2, 1), font="Helvetica " + str(fontSize), key='text')]] + + sz = fontSize + window = sg.Window("Font size selector", grab_anywhere=False).Layout(layout) + # Event Loop + while True: + button, values= window.Read() + if button is None: + break + sz_spin = int(values['spin']) + sz_slider = int(values['slider']) + sz = sz_spin if sz_spin != fontSize else sz_slider + if sz != fontSize: + fontSize = sz + font = "Helvetica " + str(fontSize) + window.FindElement('text').Update(font=font) + window.FindElement('slider').Update(sz) + window.FindElement('spin').Update(sz) + + print("Done.") + + +Inside the event loop we read the value of the Spinner and the Slider using those Elements' keys. +For example, `values['slider']` is the value of the Slider Element. + +This program changes all 3 elements if either the Slider or the Spinner changes. This is done with these statements: + + window.FindElement('text').Update(font=font) + window.FindElement('slider').Update(sz) + window.FindElement('spin').Update(sz) + +Remember this design pattern because you will use it OFTEN if you use persistent windows. + +It works as follows. The call to `window.FindElement` returns the Element object represented by they provided `key`. This element is then updated by calling it's `Update` method. This is another example of Python's "chaining" feature. We could write this code using the long-form: + + text_element = window.FindElement('text') + text_element.Update(font=font) + +The takeaway from this exercise is that keys are key in PySimpleGUI's design. They are used to both read the values of the window and also to identify elements. As already mentioned, they are used as targets in Button calls. + + + +## Keyboard & Mouse Capture +Beginning in version 2.10 you can capture keyboard key presses and mouse scroll-wheel events. Keyboard keys can be used, for example, to detect the page-up and page-down keys for a PDF viewer. To use this feature, there's a boolean setting in the Window call `return_keyboard_events` that is set to True in order to get keys returned along with buttons. + +Keys and scroll-wheel events are returned in exactly the same way as buttons. + +For scroll-wheel events, if the mouse is scrolled up, then the `button` text will be `MouseWheel:Up`. For downward scrolling, the text returned is `MouseWheel:Down` + +Keyboard keys return 2 types of key events. For "normal" keys (a,b,c, etc), a single character is returned that represents that key. Modifier and special keys are returned as a string with 2 parts: + + Key Sym:Key Code + +Key Sym is a string such as 'Control_L'. The Key Code is a numeric representation of that key. The left control key, when pressed will return the value 'Control_L:17' + + import PySimpleGUI as sg + + # Recipe for getting keys, one at a time as they are released + # If want to use the space bar, then be sure and disable the "default focus" + + with sg.Window("Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window: + text_elem = sg.Text("", size=(18,1)) + layout = [[sg.Text("Press a key or scroll mouse")], + [text_elem], + [sg.Button("OK")]] + + window.Layout(layout) + # ---===--- Loop taking in user input --- # + while True: + button, value = window.ReadNonBlocking() + + if button == "OK" or (button is None and value is None): + print(button, "exiting") + break + if button is not None: + text_elem.Update(button) + +You want to turn off the default focus so that there no buttons that will be selected should you press the spacebar. + +### Realtime Keyboard Capture +Use realtime keyboard capture by calling + + import PySimpleGUI as sg + + with sg.Window("Realtime Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window: + layout = [[sg.Text("Hold down a key")], + [sg.Button("OK")]] + + window.Layout(layout) + + while True: + button, value = window.ReadNonBlocking() + + if button == "OK": + print(button, value, "exiting") + break + if button is not None: + print(button) + elif value is None: + break + +## Menus + +Beginning in version 3.01 you can add a menubar to your window. You specify the menus in much the same way as you do window layouts, with lists. Menu selections are returned as button clicks, so be aware of your overall naming conventions. If you have an Exit button and also an Exit menu option, then you won't be able to tell the difference when your window.Read returns. Hopefully will not be a problem. + +This definition: + + menu_def = [['File', ['Open', 'Save', 'Exit',]], + ['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],], + ['Help', 'About...'],] + +Note the placement of ',' and of []. It's tricky to get the nested menus correct that implement cascading menus. See how paste has Special and Normal as a list after it. This means that Paste has a cascading menu with items Special and Normal. + +They menu_def layout produced this window: + +![menu](https://user-images.githubusercontent.com/13696193/45306723-56b7cb00-b4eb-11e8-8cbd-faef0c90f8b4.jpg) + + + + +## Updating Elements + +This is a somewhat advanced topic... + +Typically you perform Element updates in response to events from other Elements. An example is that when you click a button some text on the window changes to red. You can change the Element's attributes, or at least some of them, and the Element's value. + +In some source code examples you will find an older techique for updating elements that did not involve keys. If you see a technique in the code that does not use keys, then know that there is a version using keys that is easier. + +Here's the key's version.... +We have an InputText field that we want to update. When the Element was created we used this call: + + sg.Input(key='input') + +To update or change the value for that Input Element, we use this construct: + + window.FindElement('input').Update('new text') + +Using the '.' makes the code shorter. The FindElement call returns an Element. We then call that Element's Update function. + +See the Font Sizer demo for example source code. + +You can use Update to do things like: +* Have one Element (appear to) make a change to another Element +* Disable a button, slider, input field, etc +* Change a button's text +* Change an Element's text or background color +* Add text to a scrolling output window +* Change the choices in a list +* etc + + ### Updating Multiple Elements + If you have a large number of Elements to update, you can call `Window.UpdateElements()`. + +` UpdateElements(key_list, + value_list)` + +`key_list` - list of keys for elements you wish to update +`value_list` - list of values, one for each key + + window.UpdateElements(('name', 'address', 'phone'), ('Fred Flintstone', '123 Rock Quarry Road', '555#')) + + +## Sample Applications + +Use the example programs as a starting basis for your GUI. Copy, paste, modify and run! The demo files are: + + | Source File| Description | +|--|--| +|**Demo_All_Widgets.py**| Nearly all of the Elements shown in a single window +|**Demo_Borderless_Window.py**| Create clean looking windows with no border +|**Demo_Button_States.py**| One way of implementing disabling of buttons +|**Demo_Calendar.py** | Demo of the Calendar Chooser button +|**Demo_Canvas.py** | window with a Canvas Element that is updated outside of the window +|**Demo_Chat.py** | A chat window with scrollable history +|**Demo_Chatterbot.py** | Front-end to Chatterbot Machine Learning project +|**Demo_Color.py** | How to interact with color using RGB hex values and named colors +|**Demo_Columns.py** | Using the Column Element to create more complex windows +|**Demo_Compare_Files.py** | Using a simple GUI front-end to create a compare 2-files utility +|**Demo_Cookbook_Browser.py** | Source code browser for all Recipes in Cookbook +|**Demo_Dictionary.py** | Specifying and using return values in dictionary format +**Demo_DOC_Viewer_PIL.py** | Display a PDF, HTML, ebook file, etc in your window +|**Demo_DisplayHash1and256.py** | Using high level API and custom window to implement a simple display hash code utility +|**Demo_DuplicateFileFinder.py** | High level API used to get a folder that is used by utility that finds duplicate files. Uses progress meter to show progress. 2 lines of code required to add GUI and meter +|**Demo_Fill_Form.py** | How to perform a bulk-fill for a window. Saving and loading a window from disk +|**Demo Font Sizer.py** | Demonstrates Elements updating other Elements +|**Demo_Func_Callback_Simulator.py** | For the Raspberry Pi crowd. Event loop that simulates traditional GUI callback functions should you already have an architecture that uses them +|**Demo_GoodColors.py** | Using some of the pre-defined PySimpleGUI individual colors +|**Demo_HowDoI.py** | This is a utility to be experienced! It will change how you code +|**Demo_Img_Viewer.py** | Display jpg, png,tiff, bmp files +|**Demo_Keyboard.py** | Using blocking keyboard events +|**Demo_Keyboard_Realtime.py** | Using non-blocking / realtime keyboard events +|**Demo_Machine_Learning.py** | A sample Machine Learning front end +|**Demo_Matplotlib.py** | Integrating with Matplotlib to create a single graph +|**Demo_Matplotlib_Animated.py** | Animated Matplotlib line graph +|**Demo_Matplotlib_Animated_Scatter.py** | Animated Matplotlib scatter graph +|**Demo_Matplotlib_Browser.py** | Browse Matplotlib gallery +|**Demo_Media_Player.py** | Non-blocking window with a media player layout. Demonstrates button graphics, Update method +|**Demo_MIDI_Player.py** | GUI wrapper for Mido MIDI package. Functional MIDI player that controls attached MIDI devices +|**Demo_NonBlocking_Form.py** | a basic async window +|**Demo_OpenCV.py** | Integrated with OpenCV +|**Demo_Password_Login** | Password protection using SHA1 +|**Demo_PDF_Viewer.py** | Submitted by a user! Previews PDF documents. Uses keyboard input & mouse scrollwheel to navigate +|**Demo_Pi_LEDs.py** | Control GPIO using buttons +|**Demo_Pi_Robotics.py** | Simulated robot control using realtime buttons +|**Demo_PNG_Vierwer.py** | Uses Image Element to display PNG files +| **Demo_Progress_Meters.py** | Demonstrates using 2 progress meters simultaneously +|**Demo_Recipes.py** | A collection of various Recipes. Note these are not the same as the Recipes in the Recipe Cookbook +|**Demo_Script_Launcher.py** | Demonstrates one way of adding a front-end onto several command line scripts +|**Demo_Script_Parameters.py** | Add a 1-line GUI to the front of your previously command-line only scripts +|**Demo_Tabbed_Form.py** | Using the Tab feature +|**Demo_Table_Simulation.py** | Use input fields to display and edit tables +|**Demo_Timer.py** | Simple non-blocking window + +## Packages Used In Demos + + + While the core PySimpleGUI code does not utilize any 3rd party packages, some of the demos do. They add a GUI to a few popular packages. These packages include: + * [Chatterbot](https://github.com/gunthercox/ChatterBot) + * [Mido](https://github.com/olemb/mido) + * [Matplotlib](https://matplotlib.org/) + * [PyMuPDF](https://github.com/rk700/PyMuPDF) + + +## Creating a Windows .EXE File + +It's possible to create a single .EXE file that can be distributed to Windows users. There is no requirement to install the Python interpreter on the PC you wish to run it on. Everything it needs is in the one EXE file, assuming you're running a somewhat up to date version of Windows. + +Installation of the packages, you'll need to install PySimpleGUI and PyInstaller (you need to install only once) + +``` +pip install PySimpleGUI +pip install PyInstaller + +``` + +To create your EXE file from your program that uses PySimpleGUI, `my_program.py`, enter this command in your Windows command prompt: + +``` +pyinstaller -wF my_program.py + +``` + +You will be left with a single file, `my_program.exe`, located in a folder named `dist` under the folder where you executed the `pyinstaller` command. + +That's all... Run your `my_program.exe` file on the Windows machine of your choosing. + +> "It's just that easy." + +(famous last words that screw up just about anything being referenced) + +Your EXE file should run without creating a "shell window". Only the GUI window should show up on your taskbar. + +If you get a crash with something like: +``` +ValueError: script '.......\src\tkinter' not found +``` + +Then try adding **`--hidden-import tkinter`** to your command + + + +## Fun Stuff +Here are some things to try if you're bored or want to further customize + +**Debug Output** +Be sure and check out the EasyPrint (Print) function described in the high-level API section. Leave your code the way it is, route your stdout and stderror to a scrolling window. + +For a fun time, add these lines to the top of your script + + import PySimpleGUI as sg + print = sg.Print + +This will turn all of your print statements into prints that display in a window on your screen rather than to the terminal. + +**Look and Feel** +Dial in the look and feel that you like with the `SetOptions` function. You can change all of the defaults in one function call. One line of code to customize the entire GUI. +Or beginning in version 2.9 you can choose from a look and feel using pre-defined color schemes. Call ChangeLookAndFeel with a description string. + + sg.ChangeLookAndFeel('GreenTan') + +Valid values for the description string are: + + GreenTan + LightGreen + BluePurple + Purple + BlueMono + GreenMono + BrownBlue + BrightColors + NeutralBlue + Kayak + SandyBeach + TealMono + +To see the latest list of color choices, take a look at the bottom of the `PySimpleGUI.py` file where you'll find the `ChangLookAndFeel` function. + +You can also combine the `ChangeLookAndFeel` function with the `SetOptions` function to quickly modify one of the canned color schemes. Maybe you like the colors but was more depth to your bezels. You can dial in exactly what you want. + +**ObjToString** +Ever wanted to easily display an objects contents easily? Use ObjToString to get a nicely formatted recursive walk of your objects. +This statement: + + print(sg.ObjToSting(x)) + +And this was the output + + + abc = abc + attr12 = 12 + c = + b = + a = + attr1 = 1 + attr2 = 2 + attr3 = three + attr10 = 10 + attrx = x + +You'll quickly wonder how you ever coded without it. + +--- +# Known Issues +While not an "issue" this is a ***stern warning*** + +## **Do not attempt** to call `PySimpleGUI` from multiple threads! It's `tkinter` based and `tkinter` has issues with multiple threads + +**Progress Meters** - the visual graphic portion of the meter may be off. May return to the native tkinter progress meter solution in the future. Right now a "custom" progress meter is used. On the bright side, the statistics shown are extremely accurate and can tell you something about the performance of your code. If you are running 2 or more progress meters at the same time using `OneLineProgressMeter`, you need to close the meter by using the "Cancel" button rather than the X + +**Async windows** - these include the 'easy' windows (`OneLineProgressMeter` and EasyPrint/Print). If you start overlapping having Async windows open with normal windows then things get a littler squirrelly. Still tracking down the issues and am making it more solid every day possible. You'll know there's an issue when you see blank window. + +**EasyPrint** - EasyPrint is a new feature that's pretty awesome. You print and the output goes to a window, with a scroll bar, that you can copy and paste from. Being a new feature, it's got some potential problems. There are known interaction problems with other GUI windows. For example, closing a Print window can also close other windows you have open. For now, don't close your debug print window until other windows are closed too. + +## Contributing + +A MikeTheWatchGuy production... entirely responsible for this code.... unless it causes you trouble in which case I'm not at all responsible. + +## Versions +|Version | Description | +|--|--| +| 1.0.9 | July 10, 2018 - Initial Release | +| 1.0.21 | July 13, 2018 - Readme updates | +| 2.0.0 | July 16, 2018 - ALL optional parameters renamed from CamelCase to all_lower_case +| 2.1.1 | July 18, 2018 - Global settings exposed, fixes +| 2.2.0| July 20, 2018 - Image Elements, Print output +| 2.3.0 | July 23, 2018 - Changed form.Read return codes, Slider Elements, Listbox element. Renamed some methods but left legacy calls in place for now. +| 2.4.0 | July 24, 2018 - Button images. Fixes so can run on Raspberry Pi +| 2.5.0 | July 26, 2018 - Colors. Listbox scrollbar. tkinter Progress Bar instead of homegrown. +| 2.6.0 | July 27, 2018 - auto_size_button setting. License changed to LGPL 3+ +| 2.7.0 | July 30, 2018 - realtime buttons, window_location default setting +| 2.8.0 | Aug 9, 2018 - New None default option for Checkbox element, text color option for all elements, return values as a dictionary, setting focus, binding return key +| 2.9.0 | Aug 16,2018 - Screen flash fix, `do_not_clear` input field option, `autosize_text` defaults to `True` now, return values as ordered dict, removed text target from progress bar, rework of return values and initial return values, removed legacy Form.Refresh() method (replaced by Form.ReadNonBlockingForm()), COLUMN elements!!, colored text defaults +| 2.10.0 | Aug 25, 2018 - Keyboard & Mouse features (Return individual keys as if buttons, return mouse scroll-wheel as button, bind return-key to button, control over keyboard focus), SaveAs Button, Update & Get methods for InputText, Update for Listbox, Update & Get for Checkbox, Get for Multiline, Color options for Text Element Update, Progess bar Update can change max value, Update for Button to change text & colors, Update for Image Element, Update for Slider, Form level text justification, Turn off default focus, scroll bar for Listboxes, Images can be from filename or from in-RAM, Update for Image). Fixes - text wrapping in buttons, msg box, removed slider borders entirely and others +| 2.11.0 | Aug 29, 2018 - Lots of little changes that are needed for the demo programs to work. Buttons have their own default element size, fix for Mac default button color, padding support for all elements, option to immediately return if list box gets selected, FilesBrowse button, Canvas Element, Frame Element, Slider resolution option, Form.Refresh method, better text wrapping, 'SystemDefault' look and feel settin +| 2.20.0 | Sept 4, 2018 - Some sizable features this time around of interest to advanced users. Renaming of the MsgBox functions to Popup. Renaming GetFile, etc, to PopupGetFile. High-level windowing capabilities start with Popup, PopupNoWait/PopupNonblocking, PopupNoButtons, default icon, change_submits option for Listbox/Combobox/Slider/Spin/, New OptionMenu element, updating elements after shown, system defaul color option for progress bars, new button type (Dummy Button) that only closes a window, SCROLLABLE Columns!! (yea, playing in the Big League now), LayoutAndShow function removed, form.Fill - bulk updates to forms, FindElement - find element based on key value (ALL elements have keys now), no longer use grid packing for row elements (a potentially huge change), scrolled text box sizing changed, new look and feel themes (Dark, Dark2, Black, Tan, TanBlue, DarkTanBlue, DarkAmber, DarkBlue, Reds, Green) +| 2.30.0 | Sept 6, 2018 - Calendar Chooser (button), borderless windows, load/save form to disk +| 3.0.0 | Sept 7, 2018 - The "fix for poor choice of 2.x numbers" release. Color Chooser (button), "grab anywhere" windows are on by default, disable combo boxes, Input Element text justification (last part needed for 'tables'), Image Element changes to support OpenCV?, PopupGetFile and PopupGetFolder have better no_window option +| 3.01.01 | Sept 10, 2018 - Menus! (sort of a big deal) +| 3.01.02 | Step 11, 2018 - All Element.Update functions have a `disabled` parameter so they can be disabled. Renamed some parameters in Update function (sorry if I broke your code), fix for bug in Image.Update. Wasn't setting size correctly, changed grab_anywhere logic again,added grab anywhere option to PupupGetText (assumes disabled) +| 3.02.00 | Sept 14, 2018 - New Table Element (Beta release), MsgBox removed entirely, font setting for InputText Element, **packing change** risky change that allows some Elements to be resized,removed command parameter from Menu Element, new function names for ReadNonBlocking (Finalize, PreRead), change to text element autosizing and wrapping (yet again), lots of parameter additions to Popup functions (colors, etc). +| 3.03.00 | New feature - One Line Progress Meters, new display_row_numbers for Table Element, fixed bug in EasyProgresssMeters (function will soon go away), OneLine and Easy progress meters set to grab anywhere but can be turned off. +| 03,04.00 | Sept 18, 2018 - New features - Graph Element, Frame Element, more settings exposed to Popup calls. See notes below for more. +| 03.04.01 | Sept 18, 2018 - See release notes +| 03.05.00 | Sept 20, 2018 - See release notes +| 03.05.01 | Sept 22, 2018 - See release notes +| 03.05.02 | Sept 23, 2018 - See release notes +| 03.06.00 | Sept 23, 2018 - Goodbye FlexForm, hello Window +| 03.08.00 | Sept 25, 2018 - Tab and TabGroup Elements\ +| 01.01.00 for 2.7 | Sept 25, 2018 - First release for 2.7 + + +### Release Notes +2.3 - Sliders, Listbox's and Image elements (oh my!) + +If using Progress Meters, avoid cancelling them when you have another window open. It could lead to future windows being blank. It's being worked on. + +New debug printing capability. `sg.Print` + +2.5 Discovered issue with scroll bar on `Output` elements. The bar will match size of ROW not the size of the element. Normally you never notice this due to where on a form the `Output` element goes. + +Listboxes are still without scrollwheels. The mouse can drag to see more items. The mouse scrollwheel will also scroll the list and will `page up` and `page down` keys. + +2.7 Is the "feature complete" release. Pretty much all features are done and in the code + +2.8 More text color controls. The caller has more control over things like the focus and what buttons should be clicked when enter key is pressed. Return values as a dictionary! (NICE addition) + +2.9 COLUMNS! This is the biggest feature and had the biggest impact on the code base. It was a difficult feature to add, but it was worth it. Can now make even more layouts. Almost any layout is possible with this addition. + +.................. insert releases 2.9 to 2.30 ................. + +3.0 We've come a long way baby! Time for a major revision bump. One reason is that the numbers started to confuse people the latest release was 2.30, but some people read it as 2.3 and thought it went backwards. I kinda messed up the 2.x series of numbers, so why not start with a clean slate. A lot has happened anyway so it's well earned. + +One change that will set PySimpleGUI apart is the parlor trick of being able to move the window by clicking on it anywhere. This is turned on by default. It's not a common way to interact with windows. Normally you have to move using the titlebar. Not so with PySimpleGUI. Now you can drag using any part of the window. You will want to turn this off for windows with sliders. This feature is enabled in the Window call. + +Related to the Grab Anywhere feature is the no_titlebar option, again found in the call to Window. Your window will be a spiffy, borderless window. It's a really interesting effect. Slight problem is that you do not have an icon on the taskbar with these types of windows, so if you don't supply a button to close the window, there's no way to close it other than task manager. + +3.0.2 Still making changes to Update methods with many more ahead in the future. Continue to mess with grab anywhere option. Needed to disable in more places such as the PopupGetText function. Any time these is text input on a form, you generally want to turn off the grab anywhere feature. + +#### 3.2.0 + Biggest change was the addition of the Table Element. Trying to make changes so that form resizing is a possibility but unknown if will work in the long run. Removed all MsgBox, Get* functions and replaced with Popup functions. Popups had multiple new parameters added to change the look and feel of a popup. + +#### 3.3.0 +OneLineProgressMeter function added which gives you not only a one-line solution to progress meters, but it also gives you the ability to have more than 1 running at the same time, something not possible with the EasyProgressMeterCall + +#### 3.4.0 + +* Frame - New Element - a labelled frame for grouping elements. Similar + to Column +* Graph (like a Canvas element except uses the caller's + coordinate system rather than tkinter's). +* initial_folder - sets starting folder for browsing type buttons (browse for file/folder). +* Buttons return key value rather than button text **If** a `key` is specified, +* + OneLineProgressMeter! Replaced EasyProgressMeter (sorry folks that's + the way progress works sometimes) + * Popup - changed ALL of the Popup calls to provide many more customization settings + * Popup + * PopupGetFolder + * PopupGetFile + * PopupGetText + * Popup + * PopupNoButtons + * PopupNonBlocking + * PopupNoTitlebar + * PopupAutoClose + * PopupCancel + * PopupOK + * PopupOKCancel + * PopupYesNo + +#### 3.4.1 +* Button.GetText - Button class method. Returns the current text being shown on a button. +* Menu - Tearoff option. Determines if menus should allow them to be torn off +* Help - Shorcut button. Like Submit, cancel, etc +* ReadButton - shortcut for ReadFormButton + +#### 3.5.0 +* Tool Tips for all elements +* Clickable text +* Text Element relief setting +* Keys as targets for buttons +* New names for buttons: + * Button = SimpleButton + * RButton = ReadButton = ReadFormButton +* Double clickable list entries +* Auto sizing table widths works now +* Feature DELETED - Scaling. Removed from all elements + +#### 3.5.1 +* Bug fix for broken PySimpleGUI if Python version < 3.6 (sorry!) +* LOTS of Readme changes + +#### 3.5.2 +* Made `Finalize()` in a way that it can be chained +* Fixed bug in return values from Frame Element contents + +#### 3.6.0 +* Renamed FlexForm to Window +* Removed LookAndFeel capability from Mac platform. + +#### 3.8.0 +* Tab and TabGroup Elements - awesome new capabilities + +#### 1.0.0 Python 2.7 +It's official. There is a 2.7 version of PySimpleGUI! + +#### 3.8.2 +* Exposed `TKOut` in Output Element +* `DrawText` added to Graph Elements +* Removed `Window.UpdateElements` +* `Window.grab_anywere` defaults to False + +#### 3.8.3 +* Listbox, Slider, Combobox, Checkbox, Spin, Tab Group - if change_submits is set, will return the Element's key rather than '' +* Added change_submits capability to Checkbox, Tab Group +* Combobox - Can set value to an Index into the Values table rather than the Value itself +* Warnings added to Drawing routines for Graph element (rather than crashing) +* Window - can "force top level" window to be used rather than a normal window. Means that instead of calling Tk to get a window, will call TopLevel to get the window +* Window Disable / Enable - Disables events (button clicks, etc) for a Window. Use this when you open a second window and want to disable the first window from doing anything. This will simulate a 'dialog box' +* Tab Group returns a value with Window is Read. Return value is the string of the selected tab +* Turned off grab_anywhere for Popups +* New parameter, default_extension, for PopupGetFile +* Keyboard shortcuts for menu items. Can hold ALT key to select items in men +* Removed old-style Tabs - Risky change because it hit fundamental window packing and creation. Will also break any old code using this style tab (sorry folks this is how progress happens) + + +### Upcoming +Make suggestions people! Future release features + +Port to other graphic engines. Hook up the front-end interface to a backend other than tkinter. Qt, WxPython, etc. WxPython is higher priority. + + + +## Code Condition + + Make it run + Make it right + Make it fast + +It's a recipe for success if done right. PySimpleGUI has completed the "Make it run" phase. It's far from "right" in many ways. These are being worked on. The module is particularly poor for PEP 8 compliance. It was a learning exercise that turned into a somewhat complete GUI solution for lightweight problems. + +While the internals to PySimpleGUI are a tad sketchy, the public interfaces into the SDK are more strictly defined and comply with PEP 8 for the most part. + +Please log bugs and suggestions in the GitHub! It will only make the code stronger and better in the end, a good thing for us all, right? + +## Design + +A moment about the design-spirit of `PySimpleGUI`. From the beginning, this package was meant to take advantage of Python's capabilities with the goal of programming ease. + +**Single File** +While not the best programming practice, the implementation resulted in a single file solution. Only one file is needed, PySimpleGUI.py. You can post this file, email it, and easily import it using one statement. + +**Functions as objects** +In Python, functions behave just like object. When you're placing a Text Element into your form, you may be sometimes calling a function and other times declaring an object. If you use the word Text, then you're getting an object. If you're using `Txt`, then you're calling a function that returns a `Text` object. + +**Lists** +It seemed quite natural to use Python's powerful list constructs when possible. The form is specified as a series of lists. Each "row" of the GUI is represented as a list of Elements. When the form read returns the results to the user, all of the results are presented as a single list. This makes reading a form's values super-simple to do in a single line of Python code. + +**Dictionaries** +Want to view your form's results as a dictionary instead of a list... no problem, just use the `key` keyword on your elements. For complex forms with a lot of values that need to be changed frequently, this is by far the best way of consuming the results. + +You can also look up elements using their keys. This is an excellent way to update elements in reaction to another element. Call `form.FindElement(key)` to get the Element. + + +## Author +MikeTheWatchGuy + +## Demo Code Contributors + + [JorjMcKie](https://github.com/JorjMcKie) - PDF and image viewers (plus a number of code suggestions) +[Otherion](https://github.com/Otherion) - Table Demos Panda & CSV. Loads of suggestions to the core APIs + +## License + +GNU Lesser General Public License (LGPL 3) + + +## Acknowledgments + +* [JorjMcKie](https://github.com/JorjMcKie) was the motivator behind the entire project. His wxsimpleGUI concepts sparked PySimpleGUI into existence +* [Fredrik Lundh](https://wiki.python.org/moin/FredrikLundh) for his work on `tkinter` +* [Ruud van der Ham](https://forum.pythonistacafe.com/u/Ruud) for all the help he's provided as a Python-mentor. Quite a few tricky bits of logic was supplied by Ruud. The dual-purpose return values scheme is Ruud's for example +* **Numerous** users who provided feature suggestions! Many of the cool features were suggested by others. If you were one of them and are willing to take more credit, I'll list you here if you give me permission. Most are too modest +* [moshekaplan](https://github.com/moshekaplan)/**[tkinter_components](https://github.com/moshekaplan/tkinter_components)** wrote the code for the Calendar Chooser Element. It was lifted straight from GitHub +* [Bryan Oakley](https://stackoverflow.com/users/7432/bryan-oakley) for the code that enables the `grab_anywhere` feature. +* [Otherion](https://github.com/Otherion) for help with Tables, being a sounding board for new features, naming functions, ..., all around great help +* [agjunyent](https://github.com/agjunyent) figured out how to properly make tabs and wrote prototype code that demonstrated how to do it +* [jfongattw](https://github.com/jfongattw) huge suggestion... dictionaries. turned out to be +* one of the most critical constructs in PySimpleGUI +* [venim](https://github.com/venim) code to doing Alt-Selections in menus, updating Combobox using index, request to disable windows (a really good idea), checkbox and tab submits on change, returning keys for elements that have change_submits set, ... + + +## How Do I +Finally, I must thank the fine folks at How Do I. +https://github.com/gleitz/howdoi +Their utility has forever changed the way and pace in which I can program. I urge you to try the HowDoI.py application here on GitHub. Trust me, **it's going to be worth the effort!** +Here are the steps to run that application + + Install howdoi: + pip install howdoi + Test your install: + python -m howdoi howdoi.py + To run it: + Python HowDoI.py + +The pip command is all there is to the setup. + +The way HowDoI works is that it uses your search term to look through stack overflow posts. It finds the best answer, gets the code from the answer, and presents it as a response. It gives you the correct answer OFTEN. It's a miracle that it work SO well. +For Python questions, I simply start my query with 'Python'. Let's say you forgot how to reverse a list in Python. When you run HowDoI and ask this question, this is what you'll see. + +![howdoiwithhistory](https://user-images.githubusercontent.com/13696193/45064009-5fd61180-b07f-11e8-8ead-eb0d1ff3a6be.jpg) + + + +In the hands of a competent programmer, this tool is **amazing**. It's a must-try kind of program that has completely changed my programming process. I'm not afraid of asking for help! You just have to be smart about using what you find. + +The PySimpleGUI window that the results are shown in is an 'input' field which means you can copy and paste the results right into your code. + + + diff --git a/docs/tutorial.md b/docs/tutorial.md new file mode 100644 index 000000000..1d3e77292 --- /dev/null +++ b/docs/tutorial.md @@ -0,0 +1,340 @@ + + +# Add GUIs to your programs and scripts easily with PySimpleGUI + +PySimpleGUI now supports BOTH Python 2.7 and Python 3 + +## Introduction +Few people run Python programs by double clicking the .py file as if it were a .exe file. When a typical user (non-programmer types) double clicks an exe file, they expect it to pop open with a window they can interact with. While GUIs, using tkinter, are possible using standard Python installations, it's unlikely many programs do this. + +What if it were easy so to open a Python program into a GUI that complete beginners could do it? Would anyone care? Would anyone use it? It's difficult to answer because to date it's not been "easy" to build a custom GUI. + +There seems to be a gap in the ability to add a GUI onto a Python program/script. Complete beginners are left using only the command line and many advanced programmers don't want to take the time required to code up a tkinter GUI. + + + + +## GUI Frameworks +There is no shortage of GUI frameworks for Python. tkinter, WxPython, Qt, Kivy are a few of the major packages. In addition, there are a good number of dumbed down GUI packages that wrap one of the major packages. These include EasyGUI, PyGUI, Pyforms, ... + +The problem is that beginners (those with experience of less than 6 weeks) are not capable of learning even the simplest of the major packages. That leaves the wrapper-packages. Users will likely find it difficult or impossible to build a custom GUI layout using the smaller packages. + +PySimpleGUI attempts to address these GUI challenges by providing a super-simple, easy to understand interface to GUIs that can be easily customized. Complex GUIs are often less than 20 lines of code when PySimpleGUI is used. + +## The Secret + +What makes PySimpleGUI superior for newcomers is that the package contains the majority of the code that the user is normally expected to write. Button callbacks are handled by PySimpleGUI, not the user's code. Beginners struggle to grasp the concept of a function, expecting them to understand a call-back function in the first few weeks is a stretch. + +With some GUIs arranging the GUI Widgets often requires several lines of code.... at least one or two lines per widget. PySimpleGUI uses an "auto-packer" that creates the layout for the user automatically. There is no concept of a pack nor a grid system needed to layout a GUI Window. + +Finally, PySimpleGUI leverages the Python language constructs in clever ways that shortens the amount of code and returns the GUI data in a straightforward manner. When a Widget is created in a window layout, it is configured in-place, not several lines of code away. Results are returned as a simple list or a dictionary. + +## What is a GUI? + +Most GUIs do one thing.... they collect information from the user and return it. From a programmer's viewpoint a GUI that collects information, like a window, could be summed up as a function call that looks like this: + + button, values = GUI_Display(gui_layout) + +What's expected from most GUIs is the button that was clicked (OK, cancel, save, yes, no, etc), and the values that were input by the user. The essence of a GUI can be boiled down into a single line of code. + +This is exactly how PySimpleGUI works (for these simple kinds of GUIs). When the call is made to display the GUI, execution does no return until a button is clicked that closes the window. + +There are more complex GUIs such as those that don't close after a button is clicked. These resemble a windows program and also be created with PySimpleGUI. A remote control interface for a robot and a chat window are a couple of examples where you want to keep the window open after a button is clicked. + +## The 5-Minute GUI + +When is PySimpleGUI useful? ***Immediately***, anytime you've got a GUI need. It will take under 5 minutes for you to create and try your GUI. With those kinds of times, what do you have to lose trying it? + +The best way to go about making your GUI in under 5 minutes is to copy one of the GUIs from the [PySimpleGUI Cookbook](https://pysimplegui.readthedocs.io/en/latest/cookbook/). Follow these steps: +* Install PySimpleGUI (see short section in readme on installation) +* Find a GUI that looks similar to what you want to create +* Copy code from Cookbook +* Paste into your IDE and run + +Let's look at the first recipe from the book + + import PySimpleGUI as sg + + # Very basic window. Return values as a list + + layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText('name')], + [sg.Text('Address', size=(15, 1)), sg.InputText('address')], + [sg.Text('Phone', size=(15, 1)), sg.InputText('phone')], + [sg.Submit(), sg.Cancel()] + ] + + window = sg.Window('Simple data entry window').Layout(layout) + button, values = window.Read() + + print(button, values[0], values[1], values[2]) + + +It's a reasonably sized window. + + +![super simple 2](https://user-images.githubusercontent.com/13696193/43934091-8100e29a-9c1b-11e8-8d0a-9bd2d13e6d8e.jpg) + +If you only need to collect a few values and they're all basically strings, then you would copy this recipe and modify it to suit your needs. + +### Python 2.7 Differences + +The only noticeable difference between PySimpleGUI code running under Python 2.7 and one running on Python 3 is the import statement. + +Python 3.x: + + import PySimpleGUI as sg + +Python 2.7: + + import PySimpleGUI27 as sg + + +## The 5-line GUI + +Not all GUIs take 5 minutes. Some take 5 lines of code. This is a GUI with a custom layout contained in 5 lines of code. + + import PySimpleGUI as sg + + layout = [ [sg.Text('Enter your name'), sg.InputText()], + [sg.OK()] ] + + window = sg.Window('My first GUI').Layout(layout) + button, (name,) = window.Read() + + +![myfirstgui](https://user-images.githubusercontent.com/13696193/44315412-d2918c80-a3f1-11e8-9eda-0d5d9bfefb0f.jpg) + + + +## Making Your Custom GUI + +If you find a Recipe similar to your project. You may be able to modify the code within 5 minutes in order to get to *your layout*, assuming you've got a straightforward layout. + +Widgets are called Elements in PySimpleGUI. This list of Elements are spelled exactly as you would type it into your Python code. + +### Core Element list +``` + Buttons including these types: + File Browse + Folder Browse + Color chooser + Date picker + Read window + Close window + Realtime + Checkbox + Radio Button + Listbox + Slider + Multi-line Text Input + Scroll-able Output + Progress Bar + Option Menu + Image + Menu + Frame + Column + Graph + Table + Tabbed windows + Redirected Python Output/Errors to scrolling Window +``` + +You can also have short-cut Elements. There are 2 types of shortcuts. One is simply other names for the exact same element (e.g. T instead of Text). The second type configures an Element with particular setting, sparing the programmer from specifying all of the parameters (e.g. Submit is a button with the text "Submit" on it). + +### Shortcut list + + T = Text + Txt = Text + In = InputText + Input = IntputText + Combo = DropDown = Drop = InputCombo + DropDown = InputCombo + Drop = InputCombo + OptionMenu = InputOptionMenu + CB - CBox = Check = Checkbox + RButton = ReadButton + Button = SimpleButton + +A number of common buttons have been implemented as shortcuts. These include: +### Button Shortcuts + FolderBrowse + FileBrowse + FilesBrowse + FileSaveAs + Save + Open + Submit + OK + Ok + Cancel + Quit + Help + Exit + Yes + No + +The more generic button functions, that are also shortcuts +### Generic Buttons + Button + RButton (ReadButton) + RealtimeButton + +These are all of the GUI Widgets you have to choose from. If it's not in this list, it doesn't go in your window layout. (Maybe... unless there's been an update with more features and this tutorial wasn't updated) + +### GUI Design Pattern + +The stuff that tends not to change in GUIs are the calls that setup and show the Window. It's the layout of the Elements that changes from one program to another. This is the code from above with the layout removed: + + import PySimpleGUI as sg + # Define your window here (it's a list of lists) + layout = [[ your layout ]] + window = sg.Window('Simple data entry window').Layout(layout) + button, values = window.Read() + + + The flow for most GUIs is: + * Create the window object + * Define GUI as a list of lists + * Show the GUI and get results + +Some windows act more like Windows programs. These windows have an "Event Loop". Please see the readme for more info on these kinds of windows (Persistent windows) + +These are line for line what you see in design pattern above. + +### GUI Layout + +To create your custom GUI, first break your window down into "rows". You'll be defining your window one row at a time. Then for each for, you'll be placing one Element after another, working from left to right. + +The result is a "list of lists" that looks something like this: + + layout = [ [Text('Row 1')], + [Text('Row 2'), Checkbox('Checkbox 1', OK()), Checkbox('Checkbox 2'), OK()] ] + +The layout produced this window: + +![tutorial2](https://user-images.githubusercontent.com/13696193/44302312-e5259c00-a2f3-11e8-9c17-63e4eb130a9e.jpg) + + +## Display GUI & Get Results + +Once you have your layout complete and you've copied over the lines of code that setup and show the window, it's time to look at how to display the window and get the values from the user. + +First get a window and display it. +``` window = sg.Window('Simple data entry window').Layout(layout) ``` + +Then read the window to get the button clicked and values.: + + button, values = window.Read() + + windows return 2 values, the text of the button that was clicked and a ***list of values*** the user entered into the window. More advanced windows return the values as a **dictionary of values**, + +If the example window was displayed and the user did nothing other than click the OK button, then the results would have been: + + button == 'OK' + values == [False, False] + +Checkbox Elements return a value of True/False. Because these checkboxes defaulted to unchecked, the values returned were both False. + +## Displaying Results + +Once you have the values from the GUI it would be nice to check what values are in the variables. Rather than print them out using a `print` statement, let's stick with the GUI idea and output to a window. + +PySimpleGUI has a number of Popup Windows to choose from. The data passed to the Popup will be displayed in a window. The function takes any number of arguments, just like a print call would. Simply pass in all the variables you would like to see in the call. + +The most-commonly used display window is the `Popup`. To display the results of the previous example, one would write: + + Popup('The GUI returned:', button, values) + +## Putting It All Together + +Now that you know the basics, let's put together a window that contains as many PySimpleGUI's elements as possible. Also, just to give it a nice look, we'll change the "look and feel" to a green and tan color scheme. + + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('GreenTan') + + column1 = [[sg.Text('Column 1', background_color='#d3dfda', 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'), initial_value='Spin Box 2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] + layout = [ + [sg.Text('All graphic widgets in one window!', size=(30, 1), font=("Helvetica", 25))], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text')], + [sg.Checkbox('My first checkbox!'), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True), sg.Radio('My second Radio!', "RADIO1")], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), + sg.Multiline(default_text='A second multi-line', size=(35, 3))], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 3)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), + sg.Column(column1, background_color='#d3dfda')], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder'), sg.FolderBrowse()], + [sg.Submit(), sg.Cancel()] + ] + + window = sg.Window('Everything bagel', default_element_size=(40, 1)).Layout(layout) + button, values = window.Read() + sg.Popup(button, values) + +That may seem like a lot of code, but try coding this same GUI layout using any other GUI framework and it will be lengthier and what you see here.... by a WIDE margin. 10's of times longer. + +![everything for tutorial](https://user-images.githubusercontent.com/13696193/44302997-38531b00-a303-11e8-8c45-698ea62590a8.jpg) + +The last line of code opens a message box. This is how it looks: + +![tutorial results](https://user-images.githubusercontent.com/13696193/44303004-79e3c600-a303-11e8-8311-2f3726d364ad.jpg) + + +Each parameter to the message box call is displayed on a new line. There are actually 2 lines of text in the message box. The second line is very long and wrapped a number of times + +Take a moment and pair up the results values with the GUI to get an understanding of how results are created and returned. + +## Adding a GUI to Your Program or Script +If you have a script that uses the command line, you don't have to abandon it in order to add a GUI. An easy solution is that if there are zero parameters given on the command line, then the GUI is run. Otherwise, execute the command line as you do today. + +This kind of logic is all that's needed: + + if len(sys.argv) == 1: + # collect arguments from GUI + else: + # collect arguements from sys.argv + +Copy one of the Recipes from the Cookbook and run it. See if it resembles something you would like to build: +[PySimpleGUI Cookbook](https://pysimplegui.readthedocs.io/en/latest/cookbook/) + +Have some fun! Spice up the scripts you're tired of running by hand. Spend 5 or 10 minutes playing with the demo scripts. You may find one already exists that does exactly what you need. If not, you will find it's 'simple' to create your own. If you really get lost, you've only invested 10 minutes. + +## Resources + +### Installation + +Requires Python 3 + + pip install PySimpleGUI + +If on a Raspberry Pi or Linux, may need to do this instead: + + sudo pip3 install --upgrade pysimplegui + +Works on all systems that run tkinter, including the Raspberry Pi + +### Documentation +[Main manual](https://pysimplegui.readthedocs.io/en/latest/) + +[Cookbook](https://pysimplegui.readthedocs.io/en/latest/cookbook/) + +[Tutorial](http://tutorial.pysimplegui.org) + +### Home Page (GitHub) + +[www.PySimpleGUI.com](www.PySimpleGUI.com) \ No newline at end of file diff --git a/ping.py b/ping.py new file mode 100644 index 000000000..3df8635dc --- /dev/null +++ b/ping.py @@ -0,0 +1,572 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" + A pure python ping implementation using raw sockets. + + (This is Python 3 port of https://github.com/jedie/python-ping) + (Tested and working with python 2.7, should work with 2.6+) + + Note that ICMP messages can only be sent from processes running as root + (in Windows, you must run this script as 'Administrator'). + + Derived from ping.c distributed in Linux's netkit. That code is + copyright (c) 1989 by The Regents of the University of California. + That code is in turn derived from code written by Mike Muuss of the + US Army Ballistic Research Laboratory in December, 1983 and + placed in the public domain. They have my thanks. + + Bugs are naturally mine. I'd be glad to hear about them. There are + certainly word - size dependencies here. + + Copyright (c) Matthew Dixon Cowles, . + Distributable under the terms of the GNU General Public License + version 2. Provided with no warranties of any sort. + + Original Version from Matthew Dixon Cowles: + -> ftp://ftp.visi.com/users/mdc/ping.py + + Rewrite by Jens Diemer: + -> http://www.python-forum.de/post-69122.html#69122 + + Rewrite by George Notaras: + -> http://www.g-loaded.eu/2009/10/30/python-ping/ + + Enhancements by Martin Falatic: + -> http://www.falatic.com/index.php/39/pinging-with-python + + Enhancements and fixes by Georgi Kolev: + -> http://github.com/jedie/python-ping/ + + Bug fix by Andrejs Rozitis: + -> http://github.com/rozitis/python-ping/ + + Revision history + ~~~~~~~~~~~~~~~~ + May 1, 2014 + ----------- + Little modifications by Mohammad Emami + - Added Python 3 support. For now this project will just support + python 3.x + - Tested with python 3.3 + - version was upped to 0.6 + + March 19, 2013 + -------------- + * Fixing bug to prevent divide by 0 during run-time. + + January 26, 2012 + ---------------- + * Fixing BUG #4 - competability with python 2.x [tested with 2.7] + - Packet data building is different for 2.x and 3.x. + 'cose of the string/bytes difference. + * Fixing BUG #10 - the multiple resolv issue. + - When pinging domain names insted of hosts (for exmaple google.com) + you can get different IP every time you try to resolv it, we should + resolv the host only once and stick to that IP. + * Fixing BUGs #3 #10 - Doing hostname resolv only once. + * Fixing BUG #14 - Removing all 'global' stuff. + - You should not use globul! Its bad for you...and its not thread safe! + * Fix - forcing the use of different times on linux/windows for + more accurate mesurments. (time.time - linux/ time.clock - windows) + * Adding quiet_ping function - This way we'll be able to use this script + as external lib. + * Changing default timeout to 3s. (1second is not enought) + * Switching data syze to packet size. It's easyer for the user to ignore the + fact that the packet headr is 8b and the datasize 64 will make packet with + size 72. + + October 12, 2011 + -------------- + Merged updates from the main project + -> https://github.com/jedie/python-ping + + September 12, 2011 + -------------- + Bugfixes + cleanup by Jens Diemer + Tested with Ubuntu + Windows 7 + + September 6, 2011 + -------------- + Cleanup by Martin Falatic. Restored lost comments and docs. Improved + functionality: constant time between pings, internal times consistently + use milliseconds. Clarified annotations (e.g., in the checksum routine). + Using unsigned data in IP & ICMP header pack/unpack unless otherwise + necessary. Signal handling. Ping-style output formatting and stats. + + August 3, 2011 + -------------- + Ported to py3k by Zach Ware. Mostly done by 2to3; also minor changes to + deal with bytes vs. string changes (no more ord() in checksum() because + >source_string< is actually bytes, added .encode() to data in + send_one_ping()). That's about it. + + March 11, 2010 + -------------- + changes by Samuel Stauffer: + - replaced time.clock with default_timer which is set to + time.clock on windows and time.time on other systems. + + November 8, 2009 + ---------------- + Improved compatibility with GNU/Linux systems. + + Fixes by: + * George Notaras -- http://www.g-loaded.eu + Reported by: + * Chris Hallman -- http://cdhallman.blogspot.com + + Changes in this release: + - Re-use time.time() instead of time.clock(). The 2007 implementation + worked only under Microsoft Windows. Failed on GNU/Linux. + time.clock() behaves differently under the two OSes[1]. + + [1] http://docs.python.org/library/time.html#time.clock + + May 30, 2007 + ------------ + little rewrite by Jens Diemer: + - change socket asterisk import to a normal import + - replace time.time() with time.clock() + - delete "return None" (or change to "return" only) + - in checksum() rename "str" to "source_string" + + December 4, 2000 + ---------------- + Changed the struct.pack() calls to pack the checksum and ID as + unsigned. My thanks to Jerome Poincheval for the fix. + + November 22, 1997 + ----------------- + Initial hack. Doesn't do much, but rather than try to guess + what features I (or others) will want in the future, I've only + put in what I need now. + + December 16, 1997 + ----------------- + For some reason, the checksum bytes are in the wrong order when + this is run under Solaris 2.X for SPARC but it works right under + Linux x86. Since I don't know just what's wrong, I'll swap the + bytes always and then do an htons(). + + =========================================================================== + IP header info from RFC791 + -> http://tools.ietf.org/html/rfc791) + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |Version| IHL |Type of Service| Total Length | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Identification |Flags| Fragment Offset | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Time to Live | Protocol | Header Checksum | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Source Address | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Destination Address | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Options | Padding | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + =========================================================================== + ICMP Echo / Echo Reply Message header info from RFC792 + -> http://tools.ietf.org/html/rfc792 + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Type | Code | Checksum | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Identifier | Sequence Number | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Data ... + +-+-+-+-+- + + =========================================================================== + ICMP parameter info: + -> http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml + + =========================================================================== + An example of ping's typical output: + + PING heise.de (193.99.144.80): 56 data bytes + 64 bytes from 193.99.144.80: icmp_seq=0 ttl=240 time=127 ms + 64 bytes from 193.99.144.80: icmp_seq=1 ttl=240 time=127 ms + 64 bytes from 193.99.144.80: icmp_seq=2 ttl=240 time=126 ms + 64 bytes from 193.99.144.80: icmp_seq=3 ttl=240 time=126 ms + 64 bytes from 193.99.144.80: icmp_seq=4 ttl=240 time=127 ms + + ----heise.de PING Statistics---- + 5 packets transmitted, 5 packets received, 0.0% packet loss + round-trip (ms) min/avg/max/med = 126/127/127/127 + + =========================================================================== +""" + +#=============================================================================# +import argparse +import os, sys, socket, struct, select, time, signal + +__description__ = 'A pure python ICMP ping implementation using raw sockets.' + +if sys.platform == "win32": + # On Windows, the best timer is time.clock() + default_timer = time.clock +else: + # On most other platforms the best timer is time.time() + default_timer = time.time + +NUM_PACKETS = 3 +PACKET_SIZE = 64 +WAIT_TIMEOUT = 3.0 + +#=============================================================================# +# ICMP parameters + +ICMP_ECHOREPLY = 0 # Echo reply (per RFC792) +ICMP_ECHO = 8 # Echo request (per RFC792) +ICMP_MAX_RECV = 2048 # Max size of incoming buffer + +MAX_SLEEP = 1000 + +class MyStats: + thisIP = "0.0.0.0" + pktsSent = 0 + pktsRcvd = 0 + minTime = 999999999 + maxTime = 0 + totTime = 0 + avrgTime = 0 + fracLoss = 1.0 + +myStats = MyStats # NOT Used globally anymore. + +#=============================================================================# +def checksum(source_string): + """ + A port of the functionality of in_cksum() from ping.c + Ideally this would act on the string as a series of 16-bit ints (host + packed), but this works. + Network data is big-endian, hosts are typically little-endian + """ + countTo = (int(len(source_string)/2))*2 + sum = 0 + count = 0 + + # Handle bytes in pairs (decoding as short ints) + loByte = 0 + hiByte = 0 + while count < countTo: + if (sys.byteorder == "little"): + loByte = source_string[count] + hiByte = source_string[count + 1] + else: + loByte = source_string[count + 1] + hiByte = source_string[count] + try: # For Python3 + sum = sum + (hiByte * 256 + loByte) + except: # For Python2 + sum = sum + (ord(hiByte) * 256 + ord(loByte)) + count += 2 + + # Handle last byte if applicable (odd-number of bytes) + # Endianness should be irrelevant in this case + if countTo < len(source_string): # Check for odd length + loByte = source_string[len(source_string)-1] + try: # For Python3 + sum += loByte + except: # For Python2 + sum += ord(loByte) + + sum &= 0xffffffff # Truncate sum to 32 bits (a variance from ping.c, which + # uses signed ints, but overflow is unlikely in ping) + + sum = (sum >> 16) + (sum & 0xffff) # Add high 16 bits to low 16 bits + sum += (sum >> 16) # Add carry from above (if any) + answer = ~sum & 0xffff # Invert and truncate to 16 bits + answer = socket.htons(answer) + + return answer + +#=============================================================================# +def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet = False): + """ + Returns either the delay (in ms) or None on timeout. + """ + delay = None + + try: # One could use UDP here, but it's obscure + mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) + except socket.error as e: + print("failed. (socket error: '%s')" % e.args[1]) + raise # raise the original error + + my_ID = os.getpid() & 0xFFFF + + sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, packet_size) + if sentTime == None: + mySocket.close() + return delay + + myStats.pktsSent += 1 + + recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout) + + mySocket.close() + + if recvTime: + delay = (recvTime-sentTime)*1000 + if not quiet: + print("%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms" % ( + dataSize, socket.inet_ntoa(struct.pack("!I", iphSrcIP)), icmpSeqNumber, iphTTL, delay) + ) + myStats.pktsRcvd += 1 + myStats.totTime += delay + if myStats.minTime > delay: + myStats.minTime = delay + if myStats.maxTime < delay: + myStats.maxTime = delay + else: + delay = None + print("Request timed out.") + + return delay + +#=============================================================================# +def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size): + """ + Send one ping to the given >destIP<. + """ + #destIP = socket.gethostbyname(destIP) + + # Header is type (8), code (8), checksum (16), id (16), sequence (16) + # (packet_size - 8) - Remove header size from packet size + myChecksum = 0 + + # Make a dummy heder with a 0 checksum. + header = struct.pack( + "!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber + ) + + padBytes = [] + startVal = 0x42 + # 'cose of the string/byte changes in python 2/3 we have + # to build the data differnely for different version + # or it will make packets with unexpected size. + if sys.version[:1] == '2': + bytes = struct.calcsize("d") + data = ((packet_size - 8) - bytes) * "Q" + data = struct.pack("d", default_timer()) + data + else: + for i in range(startVal, startVal + (packet_size-8)): + padBytes += [(i & 0xff)] # Keep chars in the 0-255 range + #data = bytes(padBytes) + data = bytearray(padBytes) + + + # Calculate the checksum on the data and the dummy header. + myChecksum = checksum(header + data) # Checksum is in network order + + # Now that we have the right checksum, we put that in. It's just easier + # to make up a new header than to stuff it into the dummy. + header = struct.pack( + "!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber + ) + + packet = header + data + + sendTime = default_timer() + + try: + mySocket.sendto(packet, (destIP, 1)) # Port number is irrelevant for ICMP + except socket.error as e: + print("General failure (%s)" % (e.args[1])) + return + + return sendTime + +#=============================================================================# +def receive_one_ping(mySocket, myID, timeout): + """ + Receive the ping from the socket. Timeout = in ms + """ + timeLeft = timeout/1000 + + while True: # Loop while waiting for packet or timeout + startedSelect = default_timer() + whatReady = select.select([mySocket], [], [], timeLeft) + howLongInSelect = (default_timer() - startedSelect) + if whatReady[0] == []: # Timeout + return None, 0, 0, 0, 0 + + timeReceived = default_timer() + + recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV) + + ipHeader = recPacket[:20] + iphVersion, iphTypeOfSvc, iphLength, \ + iphID, iphFlags, iphTTL, iphProtocol, \ + iphChecksum, iphSrcIP, iphDestIP = struct.unpack( + "!BBHHHBBHII", ipHeader + ) + + icmpHeader = recPacket[20:28] + icmpType, icmpCode, icmpChecksum, \ + icmpPacketID, icmpSeqNumber = struct.unpack( + "!BBHHH", icmpHeader + ) + + if icmpPacketID == myID: # Our packet + dataSize = len(recPacket) - 28 + #print (len(recPacket.encode())) + return timeReceived, (dataSize+8), iphSrcIP, icmpSeqNumber, iphTTL + + timeLeft = timeLeft - howLongInSelect + if timeLeft <= 0: + return None, 0, 0, 0, 0 + +#=============================================================================# +def dump_stats(myStats): + """ + Show stats when pings are done + """ + print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP)) + + if myStats.pktsSent > 0: + myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)/myStats.pktsSent + + print("%d packets transmitted, %d packets received, %0.1f%% packet loss" % ( + myStats.pktsSent, myStats.pktsRcvd, 100.0 * myStats.fracLoss + )) + + if myStats.pktsRcvd > 0: + print("round-trip (ms) min/avg/max = %d/%0.1f/%d" % ( + myStats.minTime, myStats.totTime/myStats.pktsRcvd, myStats.maxTime + )) + + print("") + return + +#=============================================================================# +def signal_handler(signum, frame): + """ + Handle exit via signals + """ + dump_stats() + print("\n(Terminated with signal %d)\n" % (signum)) + sys.exit(0) + +#=============================================================================# +def verbose_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, + packet_size=PACKET_SIZE, path_finder=False): + """ + Send >count< ping to >destIP< with the given >timeout< and display + the result. + """ + signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl-C + if hasattr(signal, "SIGBREAK"): + # Handle Ctrl-Break e.g. under Windows + signal.signal(signal.SIGBREAK, signal_handler) + + myStats = MyStats() # Reset the stats + + mySeqNumber = 0 # Starting value + + try: + destIP = socket.gethostbyname(hostname) + print("\nPYTHON PING %s (%s): %d data bytes" % (hostname, destIP, packet_size)) + except socket.gaierror as e: + print("\nPYTHON PING: Unknown host: %s (%s)" % (hostname, e.args[1])) + print() + return + + myStats.thisIP = destIP + + for i in range(count): + delay = do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size) + + if delay == None: + delay = 0 + + mySeqNumber += 1 + + # Pause for the remainder of the MAX_SLEEP period (if applicable) + if (MAX_SLEEP > delay): + time.sleep((MAX_SLEEP - delay)/1000) + + dump_stats(myStats) + +#=============================================================================# +def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, + packet_size=PACKET_SIZE, path_finder=False): + """ + Same as verbose_ping, but the results are returned as tuple + """ + myStats = MyStats() # Reset the stats + mySeqNumber = 0 # Starting value + + try: + destIP = socket.gethostbyname(hostname) + except socket.gaierror as e: + return False + + myStats.thisIP = destIP + + # This will send packet that we dont care about 0.5 seconds before it starts + # acrutally pinging. This is needed in big MAN/LAN networks where you sometimes + # loose the first packet. (while the switches find the way... :/ ) + if path_finder: + fakeStats = MyStats() + do_one(fakeStats, destIP, hostname, timeout, + mySeqNumber, packet_size, quiet=True) + time.sleep(0.5) + + for i in range(count): + delay = do_one(myStats, destIP, hostname, timeout, + mySeqNumber, packet_size, quiet=True) + + if delay == None: + delay = 0 + + mySeqNumber += 1 + + # Pause for the remainder of the MAX_SLEEP period (if applicable) + if (MAX_SLEEP > delay): + time.sleep((MAX_SLEEP - delay)/1000) + + if myStats.pktsSent > 0: + myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)/myStats.pktsSent + if myStats.pktsRcvd > 0: + myStats.avrgTime = myStats.totTime / myStats.pktsRcvd + + # return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost) + return myStats.maxTime, myStats.minTime, myStats.avrgTime, myStats.fracLoss + +#=============================================================================# +def main(): + + parser = argparse.ArgumentParser(description=__description__) + parser.add_argument('-q', '--quiet', action='store_true', + help='quiet output') + parser.add_argument('-c', '--count', type=int, default=NUM_PACKETS, + help=('number of packets to be sent ' + '(default: %(default)s)')) + parser.add_argument('-W', '--timeout', type=float, default=WAIT_TIMEOUT, + help=('time to wait for a response in seoncds ' + '(default: %(default)s)')) + parser.add_argument('-s', '--packet-size', type=int, default=PACKET_SIZE, + help=('number of data bytes to be sent ' + '(default: %(default)s)')) + parser. add_argument('destination') + # args = parser.parse_args() + + ping = verbose_ping + # if args.quiet: + # ping = quiet_ping + ping('Google.com', timeout=1000) + # ping(args.destination, timeout=args.timeout*1000, count=args.count, + # packet_size=args.packet_size) + +if __name__ == '__main__': + main() diff --git a/readme.md b/readme.md new file mode 100644 index 000000000..9bf329997 --- /dev/null +++ b/readme.md @@ -0,0 +1,2986 @@ + + + + +![pysimplegui_logo](https://user-images.githubusercontent.com/13696193/43165867-fe02e3b2-8f62-11e8-9fd0-cc7c86b11772.png) + +[![Downloads](http://pepy.tech/badge/pysimplegui)](http://pepy.tech/project/pysimplegui) +[![Downloads ](https://pepy.tech/badge/pysimplegui27)](https://pepy.tech/project/pysimplegui27) +![Documentation Status](https://readthedocs.org/projects/pysimplegui/badge/?version=latest) + ![Awesome Meter](https://img.shields.io/badge/Awesome_meter-100-yellow.svg) + ![Python Version](https://img.shields.io/badge/Python-2.7_3.x-yellow.svg) + + + + + + +# PySimpleGUI + + +## Now supports both Python 2.7 & 3 + +![Python Version](https://img.shields.io/badge/PySimpleGUI_For_Python_3_Version-3.8.4-red.svg?longCache=true&style=for-the-badge) + + ![Python Version](https://img.shields.io/badge/PySimpleGUI_For_Python_2.7_Version-1.0.4-blue.svg?longCache=true&style=for-the-badge) + +[Announcements of Latest Developments](https://github.com/MikeTheWatchGuy/PySimpleGUI/issues/142) + +[ReadTheDocs](http://pysimplegui.readthedocs.io/) + +[COOKBOOK!](https://pysimplegui.readthedocs.io/en/latest/cookbook/) + +[Brief Tutorial](https://pysimplegui.readthedocs.io/en/latest/tutorial/) + +[Latest Demos and Master Branch on GitHub](https://github.com/MikeTheWatchGuy/PySimpleGUI) + +Super-simple GUI to use... Powerfully customizable. + +Home of the 1-line custom GUI and 1-line progress meter + +#### Note regarding Python versions +As of 9/25/2018 **both Python 3 and Python 2.7 are supported**! The Python 3 version is named `PySimpleGUI`. The Python 2.7 version is `PySimpleGUI27`. They are installed separately and the imports are different. See instructions in Installation section for more info. + + +------------------------------------------------------------------------ + + +Looking for a GUI package? +* Taking your Python code from the world of command lines and into the convenience of a GUI? * +* Have a Raspberry **Pi** with a touchscreen that's going to waste because you don't have the time to learn a GUI SDK? +* Into Machine Learning and are sick of the command line? +* Would like to distribute your Python code to Windows users as a single .EXE file that launches straight into a GUI, much like a WinForms app? + +Look no further, **you've found your GUI package**. + + import PySimpleGUI as sg + + sg.Popup('Hello From PySimpleGUI!', 'This is the shortest GUI program ever!') + + +![hello world](https://user-images.githubusercontent.com/13696193/44960047-1f7f6380-aec6-11e8-9d5e-12ef935bcade.jpg) + + +Or how about a ***custom GUI*** in 1 line of code? + + import PySimpleGUI as sg + + button, (filename,) = sg.Window('Get filename example'). LayoutAndRead([[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ]) + +![get filename](https://user-images.githubusercontent.com/13696193/44960039-f1018880-aec5-11e8-8a43-3d7f8ff93b67.jpg) + + + Build beautiful customized windows that fit your specific problem. Let PySimpleGUI solve your GUI problem while you solve your real problems. Look through the Cookbook, find a matching recipe, copy, paste, run within minutes. This is the process PySimpleGUI was designed to facilitate. + + +![borderless grayed buttons](https://user-images.githubusercontent.com/13696193/45168664-d848e980-b1c9-11e8-886e-63279ae4017f.jpg) + + + +PySimpleGUI wraps tkinter so that you get all the same widgets as you would tkinter, but you interact with them in a more friendly way. It does the layout and boilerplate code for you and presents you with a simple, efficient interface. + +![everything dark theme](https://user-images.githubusercontent.com/13696193/44959854-b1d23800-aec3-11e8-90b6-5af915a86d15.jpg) + +Perhaps you're looking for a way to interact with your **Raspberry Pi** in a more friendly way. The same for shown as on Pi (roughly the same) + +![raspberry pi everything demo](https://user-images.githubusercontent.com/13696193/44279694-5b58ce80-a220-11e8-9ab6-d6021f5a944f.jpg) + + + +In addition to a primary GUI, you can add a Progress Meter to your code with ONE LINE of code. Slide this line into any of your `for` loops and get a nice meter: + + OneLineProgressMeter('My meter title', current_value, max value, 'key') + + ![easyprogressmeter](https://user-images.githubusercontent.com/13696193/44960065-83099100-aec6-11e8-8aa8-96e4b100a0e4.jpg) + +You can build an async media player GUI with custom buttons in 30 lines of code. + +![media player 2](https://user-images.githubusercontent.com/13696193/44960091-eeebf980-aec6-11e8-884e-80d4447a83cd.jpg) + + +How about embedding a game inside of a GUI? This game of Pong is written in tkinter and then dropped into the PySimpleGUI window creating a game that has an accompanying GUI. + +![pong](https://user-images.githubusercontent.com/13696193/45860012-2d8d0b00-bd33-11e8-9efd-3eaf4c30f324.gif) + + +Combining PySimpleGUI with PyInstaller creates something truly remarkable and special, a Python program that looks like a Windows WinForms application. This application with working menu was created in 20 lines of Python code. It is a single .EXE file that launches straight into the screen you see. And more good news, the only icon you see on the taskbar is the window itself... there is no pesky shell window. + +![menu demo](https://user-images.githubusercontent.com/13696193/45923097-8fbc4c00-beaa-11e8-87d2-01a5331811c8.gif) + + + ## Background +I was frustrated by having to deal with the dos prompt when I had a powerful Windows machine right in front of me. Why is it SO difficult to do even the simplest of input/output to a window in Python?? + +There are a number of 'easy to use' Python GUIs, but they were too limited for my requirements. PySimpleGUI aims for the same simplicity found in packages like `EasyGUI`and `WxSimpleGUI` , both really handy but limited, and adds the ability to define your own layouts. This ability to make your own windows using a large palette of widgets is but one difference between the existing "simple" packages and `PySimpleGUI`. + +With a simple GUI, it becomes practical to "associate" .py files with the python interpreter on Windows. Double click a py file and up pops a GUI window, a more pleasant experience than opening a dos Window and typing a command line. + +The `PySimpleGUI` package is focused on the ***developer***. +> Create a custom GUI with as little and as simple code as possible. + +This was the primary focus used to create PySimpleGUI. + +> "Do it in a Python-like way" + +was the second. + +## Features + +While simple to use, PySimpleGUI has significant depth to be explored by more advanced programmers. The feature set goes way beyond the requirements of a beginner programmer, and into the required features needed for complex GUIs. + + Features of PySimpleGUI include: + Support for versions Python 2.7 and 3 + Text + Single Line Input + Buttons including these types: + File Browse + Files Browse + Folder Browse + SaveAs + Non-closing return + Close window + Realtime + Calendar chooser + Color chooser + Checkboxes + Radio Buttons + Listbox + Option Menu + Slider + Graph + Frame with title + Icons + Multi-line Text Input + Scroll-able Output + Images + Progress Bar Async/Non-Blocking Windows + Tabbed windows + Persistent Windows + Redirect Python Output/Errors to scrolling window + 'Higher level' APIs (e.g. MessageBox, YesNobox, ...) + Single-Line-Of-Code Proress Bar & Debug Print + Complete control of colors, look and feel + Selection of pre-defined palettes + Button images + Return values as dictionary + Set focus + Bind return key to buttons + Group widgets into a column and place into window anywhere + Scrollable columns + Keyboard low-level key capture + Mouse scroll-wheel support + Get Listbox values as they are selected + Get slider, spinner, combo as they are changed + Update elements in a live window + Bulk window-fill operation + Save / Load window to/from disk + Borderless (no titlebar) windows + Always on top windows + Menus + Tooltips + Clickable links + No async programming required (no callbacks to worry about) + + +An example of many widgets used on a single window. A little further down you'll find the 21 lines of code required to create this complex window. Try it if you don't believe it. Install PySimpleGUI then : + +>Start Python, copy and paste the code below into the >>> prompt and hit enter. This will pop up... +> + +![everything example](https://user-images.githubusercontent.com/13696193/43097412-0a4652aa-8e8a-11e8-8e09-939484e3c568.jpg) + + + + import PySimpleGUI as sg + + layout = [[sg.Text('All graphic widgets in one window!', size=(30, 1), font=("Helvetica", 25), text_color='blue')], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText()], + [sg.Checkbox('My first checkbox!'), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True), sg.Radio('My second Radio!', "RADIO1")], + [sg.Multiline(default_text='This is the default Text shoulsd you decide not to type anything',)], + [sg.InputCombo(['Combobox 1', 'Combobox 2'], size=(20, 3)), + sg.Slider(range=(1, 100), orientation='h', size=(35, 20), default_value=85)], + [sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6)), + sg.Slider(range=(1, 100), orientation='v', size=(10, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(10, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(10, 20), default_value=10)], + [sg.Text('_' * 100, size=(70, 1))], + [sg.Text('Choose Source and Destination Folders', size=(35, 1))], + [sg.Text('Source Folder', size=(15, 1), auto_size_text=False, justification='right'), sg.InputText('Source'), + sg.FolderBrowse()], + [sg.Text('Destination Folder', size=(15, 1), auto_size_text=False, justification='right'), sg.InputText('Dest'), + sg.FolderBrowse()], + [sg.Submit(), sg.Cancel(), sg.Button('Customized', button_color=('white', 'green'))]] + + button, values = sg.Window('Everything bagel', auto_size_text=True, default_element_size=(40, 1)).LayoutAndRead(layout) + + + +--- +### Design Goals + +> Copy, Paste, Run. + +`PySimpleGUI's` goal with the API is to be easy on the programmer, and to function in a Python-like way. Since GUIs are visual, it was desirable for the code to visually match what's on the screen. By providing a significant amount of documentation and an easy to use Cookbook, it's possible to see your first GUI within 5 minutes of beginning the installation. + + > Be Pythonic + + Be Pythonic... Attempted to use language constructs in a natural way and to exploit some of Python's interesting features. Python's lists and optional parameters make PySimpleGUI work smoothly. + + - windows are represented as Python lists. + - A window is a list of rows + - A row is a list of elements +- Return values are a list of button presses and input values. +- Return values can also be represented as a dictionary +- The SDK calls collapse down into a single line of Python code that presents a custom GUI and returns values +- Linear programming instead of callbacks + + #### Lofty Goals + +> Change Python + +The hope is not that ***this*** package will become part of the Python Standard Library. + +The hope is that Python will become ***the*** go-to language for creating GUI programs that run on Windows, Mac, and Linux *for all levels of developer*. + +The hope is that beginners that are interested in graphic design will have an easy way to express themselves, right from the start of their Python experience. + +There is a noticeable gap in the Python GUI solution. Fill that gap and who knows what will happen. + +Maybe there's no "there there". ***Or*** maybe a simple GUI API will enable Python to dominate yet another computing discipline like it has so many others. This is my attempt to find out. + + + ----- +## Getting Started with PySimpleGUI + +### Installing Python 3 + + pip install --upgrade PySimpleGUI + +On some systems you need to run pip3. + + pip3 install --upgrade PySimpleGUI + +On a Raspberry Pi, this is should work: + + sudo pip3 install --upgrade pysimplegui + +Some users have found that upgrading required using an extra flag on the pip `--no-cache-dir`. + + pip install --upgrade --no-cache-dir + +On some versions of Linux you will need to first install pip. Need the Chicken before you can get the Egg (get it... Egg?) + +`sudo apt install python3-pip ` + +If for some reason you are unable to install using `pip`, don't worry, you can still import PySimpleGUI by downloading the file PySimleGUI.py and placing it in your folder along with the application that is importing it. + +`tkinter` is a requirement for PySimpleGUI (the only requirement). Some OS variants, such as Ubuntu, do not some with `tkinter` already installed. If you get an error similar to: +``` +ImportError: No module named tkinter +``` +then yosudou need to install `tkinter`. Be sure and get the Python 3 version. +` +```sudo apt-get install python3-tk ``` + + +### Installing for Python 2.7 + + pip install --upgrade PySimpleGUI27 + +Python 2.7 support is relatively new and the bugs are still being worked out. I'm unsure what may need to be done to install tkinter for Python 2.7. Will update this readme when more info is available + +Like above, you may have to install either pip or tkinter. To do this on Python 2.7: + +`sudo apt install python-pip` + +`sudo apt install python-tkinter` + +### Testing your installation + +Once you have installed, or copied the .py file to your app folder, you can test the installation using python. At the command prompt start up Python. + +#### Instructions for Python 2.7: +``` +python +>>> import PySimpleGUI27 +>>> PySimpleGUI27.main() +``` + +#### Instructions for Python 3: + +``` +python3 +>>> import PySimpleGUI +>>> PySimpleGUI.main() +``` + +You will see a sample window in the center of your screen. If it's not installed correctly you are likely to get an error message during one of those commands + +Here is the window you should see: + +![sample window](https://user-images.githubusercontent.com/13696193/46097669-79efa500-c190-11e8-885c-e5d4d5d09ea6.jpg) + + + +### Prerequisites +Python 2.7 or Python 3 +tkinter + +PySimpleGUI Runs on all Python3 platforms that have tkinter running on them. It has been tested on Windows, Mac, Linux, Raspberry Pi. Even runs on `pypy3`. + +### EXE file creation + +If you wish to create an EXE from your PySimpleGUI application, you will need to install `PyInstaller`. There are instructions on how to create an EXE at the bottom of this ReadMe + + +## Using - Python 3 + +To use in your code, simply import.... + `import PySimpleGUI as sg` + +Then use either "high level" API calls or build your own windows. + + sg.Popup('This is my first Popup') + +![first popup](https://user-images.githubusercontent.com/13696193/44957300-c7813680-ae9e-11e8-9a8c-c70198db7907.jpg) + + +Yes, it's just that easy to have a window appear on the screen using Python. With PySimpleGUI, making a custom window appear isn't much more difficult. The goal is to get you running on your GUI within ***minutes***, not hours nor days. + +## Using - Python 2.7 + +Those using Python 2.7 will import a different module name + `import PySimpleGUI27 as sg` + +## Code Samples Assume Python 3 + +While all of the code examples you will see in this Readme and the Cookbook assume Python 3 and thus have an `import PySimpleGUI` at the top, you can run ***all*** of this code on Python 2.7 by changing the import statement to `import PySimpleGUI27` + +--- +## APIs + +PySimpleGUI can be broken down into 2 types of API's: + * High Level single call functions (The `Popup` calls) + * Custom window functions + + +### Python Language Features + + There are a number of Python language features that PySimpleGUI utilizes heavily for API access that should be understood... + * Variable number of arguments to a function call + * Optional parameters to a function call + * Dictionaries + +#### Variable Number of Arguments + + The "High Level" API calls that *output* values take a variable number of arguments so that they match a "print" statement as much as possible. The idea is to make it simple for the programmer to output as many items as desired and in any format. The user need not convert the variables to be output into the strings. The PySimpleGUI functions do that for the user. + + sg.Popup('Variable number of parameters example', var1, var2, "etc") + +Each new item begins on a new line in the Popup + + ![snap0179](https://user-images.githubusercontent.com/13696193/43658129-f6ca49c6-9725-11e8-9317-1f77443eb04a.jpg) + + + +#### Optional Parameters to a Function Call + +This feature of the Python language is utilized ***heavily*** as a method of customizing windows and window Elements. Rather than requiring the programmer to specify every possible option for a widget, instead only the options the caller wants to override are specified. + +Here is the function definition for the Popup function. The details aren't important. What is important is seeing that there is a long list of potential tweaks that a caller can make. However, they don't *have* to be specified on each and every call. + + def Popup(*args, + button_color=None, + button_type=MSG_BOX_OK, + auto_close=False, + auto_close_duration=None, + icon=DEFAULT_WINDOW_ICON, + line_width=MESSAGE_BOX_LINE_WIDTH, + font=None): + +If the caller wanted to change the button color to be black on yellow, the call would look something like this: + + sg.Popup('This box has a custom button color', button_color=('black', 'yellow')) + + +![snap0180](https://user-images.githubusercontent.com/13696193/43658171-13a72bfe-9726-11e8-8c7a-0a46e46fb202.jpg) + + +#### Dictionaries + +Dictionaries are used by more advanced PySimpleGUI users. You'll know that dictionaries are being used if you see a `key` parameter on any Element. Dictionaries are used in 2 ways: +1. To identify values when a window is read +2. To identify Elements so that they can be "updated" + +--- + +### High Level API Calls - Popup's + +"High level calls" are those that start with "Popup". They are the most basic form of communications with the user. They are named after the type of window they create, a pop-up window. These windows are meant to be short lived while, either delivering information or collecting it, and then quickly disappearing. + +### Popup Output + +Think of the `Popup` call as the GUI equivalent of a `print` statement. It's your way of displaying results to a user in the windowed world. Each call to Popup will create a new Popup window. + +`Popup` calls are normally blocking. your program will stop executing until the user has closed the Popup window. A non-blocking window of Popup discussed in the async section. + +Just like a print statement, you can pass any number of arguments you wish. They will all be turned into strings and displayed in the popup window. + +There are a number of Popup output calls, each with a slightly different look (e.g. different button labels). + +The list of Popup output functions are + + Popup + PopupOk + PopupYesNo + PopupCancel + PopupOkCancel + PopupError + PopupTimed, PopupAutoClose + PopupNoWait, PopupNonBlocking + +The trailing portion of the function name after Popup indicates what buttons are shown. `PopupYesNo` shows a pair of button with Yes and No on them. `PopupCancel` has a Cancel button, etc. + +While these are "output" windows, they do collect input in the form of buttons. The Popup functions return the button that was clicked. If the Ok button was clicked, then Popup returns the string 'Ok'. If the user clicked the X button to close the window, then the button value returned is `None`. + +The function `PopupTimed` or `PopupAutoClose` are popup windows that will automatically close after come period of time. + +Here is a quick-reference showing how the Popup calls look. + + + sg.Popup('Popup') + sg.PopupOk('PopupOk') + sg.PopupYesNo('PopupYesNo') + sg.PopupCancel('PopupCancel') + sg.PopupOkCancel('PopupOkCancel') + sg.PopupError('PopupError') + sg.PopupTimed('PopupTimed') + sg.PopupAutoClose('PopupAutoClose') + + + +![snap0256](https://user-images.githubusercontent.com/13696193/44957394-1380ab00-aea0-11e8-98b1-1ab7d7bd5b37.jpg) + +![snap0257](https://user-images.githubusercontent.com/13696193/44957400-167b9b80-aea0-11e8-9d42-2314f24e62de.jpg) + +![snap0258](https://user-images.githubusercontent.com/13696193/44957399-154a6e80-aea0-11e8-9580-e716f839d400.jpg) + +![snap0259](https://user-images.githubusercontent.com/13696193/44957398-14b1d800-aea0-11e8-9e88-c2b36a248447.jpg) + +![snap0260](https://user-images.githubusercontent.com/13696193/44957397-14b1d800-aea0-11e8-950b-6d0b4f33841a.jpg) + +![snap0261](https://user-images.githubusercontent.com/13696193/44957396-14194180-aea0-11e8-8eef-bb2e1193ecfa.jpg) + +![snap0264](https://user-images.githubusercontent.com/13696193/44957595-9e15da00-aea1-11e8-8909-6b6121b74509.jpg) + +#### Scrolled Output +There is a scrolled version of Popups should you have a lot of information to display. + + sg.PopupScrolled(my_text) + +![scrolledtextbox 2](https://user-images.githubusercontent.com/13696193/43667324-712aa0d4-9745-11e8-83a9-a0d0570d0865.jpg) + + +The `PopupScrolled` will auto-fit the window size to the size of the text. Specify `None` in the height field of a `size` parameter to get auto-sized height. + +This call will create a scrolled box 80 characters wide and a height dependent upon the number of lines of text. + +sg.PopupScrolled(my_text, size=(80, None)) + +Note that the default max number of lines before scrolling happens is set to 50. At 50 lines the scrolling will begin. + +### PopupNoWait + +The Popup call PopupNoWait or PopupNonBlocking will create a popup window and then immediately return control back to you. All other popup functions will block, waiting for the user to close the popup window. + +This function is very handy for when you're **debugging** and want to display something as output but don't want to change the programs's overall timing by blocking. Think of it like a `print` statement + +A word of ***caution***... Windows that are created after the NoWait Popup are "slaves" to the NoWait'd popup. If you close the Popup, it will also lose the window the you created after the Popup. A good rule of thumb is to leave the popup open while you're interacting with the rest of your program until you understand what happens when you close the NoWaitPopup. + + + +### Popup Input + +There are Popup calls for single-item inputs. These follow the pattern of `Popup` followed by `Get` and then the type of item to get. + + - `PopupGetString` - get a single line of text + - `PopupGetFile` - get a filename + - `PopupGetFolder` - get a folder name + +Rather than make a custom window to get one data value, call the Popup input function to get the item from the user. + + + import PySimpleGUI as sg + + text = sg.PopupGetText('Title', 'Please input something') + sg.Popup('Results', 'The value returned from PopupGetText', text) + + ![popupgettext](https://user-images.githubusercontent.com/13696193/44957281-8721b880-ae9e-11e8-98cd-d06369f4187e.jpg) + +![popup gettext response](https://user-images.githubusercontent.com/13696193/44957282-8721b880-ae9e-11e8-84ae-dc8bb30504a0.jpg) + + + text = sg.PopupGetFile('Please enter a file name') + sg.Popup('Results', 'The value returned from PopupGetFile', text) + +![popupgetfile](https://user-images.githubusercontent.com/13696193/44957857-2fd31680-aea5-11e8-8eb7-f6b91c202cc8.jpg) + +The window created to get a folder name looks the same as the get a file name. The difference is in what the browse button does. `PopupGetFile` shows an Open File dialog box while `PopupGetFolder` shows an Open Folder dialog box. + + text = sg.PopupGetFolder('Please enter a folder name') + sg.Popup('Results', 'The value returned from PopupGetFolder', text) + +![popupgetfolder](https://user-images.githubusercontent.com/13696193/44957861-45484080-aea5-11e8-926c-cf607a45251c.jpg) + +#### Progress Meters! +We all have loops in our code. 'Isn't it joyful waiting, watching a counter scrolling past in a text window? How about one line of code to get a progress meter, that contains statistics about your code? + + + OneLineProgressMeter(title, + current_value, + max_value, + key, + *args, + orientation=None, + bar_color=DEFAULT_PROGRESS_BAR_COLOR, + button_color=None, + size=DEFAULT_PROGRESS_BAR_SIZE, + border_width=DEFAULT_PROGRESS_BAR_BORDER_WIDTH): + +Here's the one-line Progress Meter in action! + + for i in range(1,10000): + sg.OneLineProgressMeter('My Meter', i+1, 10000, 'key','Optional message') + +That line of code resulted in this window popping up and updating. + +![preogress meter](https://user-images.githubusercontent.com/13696193/43667625-d47da702-9746-11e8-91e6-e5177883abae.jpg) + +A meter AND fun statistics to watch while your machine grinds away, all for the price of 1 line of code. +With a little trickery you can provide a way to break out of your loop using the Progress Meter window. The cancel button results in a `False` return value from `OneLineProgressMeter`. It normally returns `True`. + +***Be sure and add one to your loop counter*** so that your counter goes from 1 to the max value. If you do not add one, your counter will never hit the max value. Instead it will go from 0 to max-1. + +#### Debug Output +Another call in the 'Easy' families of APIs is `EasyPrint`. It will output to a debug window. If the debug window isn't open, then the first call will open it. No need to do anything but stick a 'print' call in your code. You can even replace your 'print' calls with calls to EasyPrint by simply sticking the statement + + print = sg.EasyPrint + +at the top of your code. +There are a number of names for the same EasyPrint function. `Print` is one of the better ones to use as it's easy to remember. It is simply `print` with a capital P. + + import PySimpleGUI as sg + + for i in range(100): + sg.Print(i) + +![snap0125](https://user-images.githubusercontent.com/13696193/43114979-a696189e-8ecf-11e8-83c7-473fcf0ccc66.jpg) +Or if you didn't want to change your code: + + import PySimpleGUI as sg + + print=sg.Print + for i in range(100): + print(i) + +Just like the standard print call, `EasyPrint` supports the `sep` and `end` keyword arguments. Other names that can be used to call `EasyPrint` include Print, `eprint`, If you want to close the window, call the function `EasyPrintClose`. + +A word of caution. There are known problems when multiple PySimpleGUI windows are opened, particularly if the user closes them in an unusual way. Not a reason to stay away from using it. Just something to keep in mind if you encounter a problem. + +You can change the size of the debug window using the `SetOptions` call with the `debug_win_size` parameter. + +--- +# Custom window API Calls (Your First window) + +This is the FUN part of the programming of this GUI. In order to really get the most out of the API, you should be using an IDE that supports auto complete or will show you the definition of the function. This will make customizing go smoother. + +This first section on custom windows is for your typical, blocking, non-persistant window. By this I mean, when you "show" the window, the function will not return until the user has clicked a button or closed the window. When this happens, the window will be automatically closed. + +Two other types of windows exist. +1. Persistent window - rather than closing on button clicks, the show window function returns and the window continues to be visible. This is good for applications like a chat window. +2. Asynchronous window - the trickiest of the lot. Great care must be exercised. Examples are an MP3 player or status dashboard. Async windows are updated (refreshed) on a periodic basis. + +It's both not enjoyable nor helpful to immediately jump into tweaking each and every little thing available to you. + +## The window Designer +The good news to newcomers to GUI programming is that PySimpleGUI has a window designer. Better yet, the window designer requires no training and everyone knows how to use it. + +![gui0_1](https://user-images.githubusercontent.com/13696193/44159598-e2257400-a085-11e8-9b02-343e72cc75c3.JPG) + +It's a manual process, but if you follow the instructions, it will take only a minute to do and the result will be a nice looking GUI. The steps you'll take are: +1. Sketch your GUI on paper +2. Divide your GUI up into rows +3. Label each Element with the Element name +4. Write your Python code using the labels as pseudo-code + +Let's take a couple of examples. + +**Enter a number**.... Popular beginner programs are often based on a game or logic puzzle that requires the user to enter something, like a number. The "high-low" answer game comes to mind where you try to guess the number based on high or low tips. + +**Step 1- Sketch the GUI** +![gui1_1](https://user-images.githubusercontent.com/13696193/44160127-6a584900-a087-11e8-8fec-09099a8e16f6.JPG) + +**Step 2 - Divide into rows** + +![gui2_1](https://user-images.githubusercontent.com/13696193/44160128-6a584900-a087-11e8-9973-af866fb94c56.JPG) + +Step 3 - Label elements + +![gui6_1](https://user-images.githubusercontent.com/13696193/44160116-64626800-a087-11e8-8b57-671c0461b508.JPG) + +Step 4 - Write the code +The code we're writing is the layout of the GUI itself. This tutorial only focuses on getting the window code written, not the stuff to display it, get results. + +We have only 1 element on the first row, some text. Rows are written as a "list of elements", so we'll need [ ] to make a list. Here's the code for row 1 + + [ sg.Text('Enter a number') ] + +Row 2 has 1 elements, an input field. + + [ sg.Input() ] +Row 3 has an OK button + + [ sg.OK() ] + +Now that we've got the 3 rows defined, they are put into a list that represents the entire window. + + layout = [ [sg.Text('Enter a Number')], + [sg.Input()], + [sg.OK()] ] + +Finally we can put it all together into a program that will display our window. + + import PySimpleGUI as sg + + layout = [[sg.Text('Enter a Number')], + [sg.Input()], + [sg.OK()] ] + + button, (number,) = sg.Window('Enter a number example').LayoutAndRead(layout) + + sg.Popup(button, number) + +### Example 2 - Get a filename +Let's say you've got a utility you've written that operates on some input file and you're ready to use a GUI to enter than filename rather than the command line. Follow the same steps as the previous example - draw your window on paper, break it up into rows, label the elements. + +![gui4_1](https://user-images.githubusercontent.com/13696193/44160132-6a584900-a087-11e8-862f-7d791a67ee5d.JPG) +![gui5_1](https://user-images.githubusercontent.com/13696193/44160133-6af0df80-a087-11e8-9dec-bb4d4c59393d.JPG) + +Writing the code for this one is just as straightforward. There is one tricky thing, that browse for a file button. Thankfully PySimpleGUI takes care of associating it with the input field next to it. As a result, the code looks almost exactly like the window on the paper. + + import PySimpleGUI as sg + + layout = [[sg.Text('Filename')], + [sg.Input(), sg.FileBrowse()], + [sg.OK(), sg.Cancel()] ] + + button, (number,) = sg.Window('Get filename example').LayoutAndRead(layout) + + sg.Popup(button, number) + + +Read on for detailed instructions on the calls that show the window and return your results. + + + +# Copy these design patterns! + +All of your PySimpleGUI programs will utilize one of these 3 design patterns depending on the type of window you're implementing. + + +## Pattern 1 - Single read windows + +This is the most basic design pattern. Use this for windows that are shown to the user 1 time. The input values are gathered and returned to the program + + window_rows = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')], + [sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('SHA-1 & 256 Hash') + + button, (source_filename,) = window.LayoutAndRead(window_rows) + + ---- + +## Pattern 2 - Single-read window "chained" + +Python has a ***beautiful*** way of compacting code known as "chaining". You take the output from one function and feed it as input to the next. Notice in the first example how a window is first obtained by calling Window and then that window is then read. It's possible to combine the creation of the window with the read. This design pattern does exactly that, chain together the window creation and the window reading. + + window_rows = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')], + [sg.InputText(), sg.FileBrowse()], + [sg.Submit(), sg.Cancel()]] + + button, (source_filename,) = sg.Window('SHA-1 & 256 Hash').LayoutAndRead(window_rows) + + +## Pattern 3 - Persistent window (multiple reads) + +Some of the more advanced programs operate with the window remaining visible on the screen. Input values are collected, but rather than closing the window, it is kept visible acting as a way to both output information to the user and gather input data. + +This is done by splitting the LayoutAndRead call apart into a Layout call and a Read call. Note how chaining is again used. In this case a window is created by calling Window which is then passed on to the Layout method. The Layout method returns the window value so that it can be stored and used later in the program to Read the window. + + import PySimpleGUI as sg + + layout = [[sg.Text('Persistent window')], + [sg.RButton('Turn LED On')], + [sg.RButton('Turn LED Off')], + [sg.Exit()]] + + window = sg.Window('Raspberry Pi GUI').Layout(layout) + + while True: + button, values = window.Read() + if button is None: + break + + +### How GUI Programming in Python Should Look? At least for beginners + +Why is Python such a great teaching language and yet no GUI framework exists that lends itself to the basic building blocks of Python, the list or dictionary? PySimpleGUI set out to be a Pythonic solution to the GUI problem. Whether it achieved this goal is debatable, but it was an attempt just the same. + +The key to custom windows in PySimpleGUI is to view windows as ROWS of Elements. Each row is specified as a list of these Elements. Put the rows together and you've got a window. + + Let's dissect this little program + + import PySimpleGUI as sg + + layout = [[sg.Text('Rename files or folders')], + [sg.Text('Source for Folders', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Text('Source for Files ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Submit(), sg.Cancel()]] + + window = sg.Window('Rename Files or Folders') + + button, (folder_path, file_path) = window.LayoutAndRead(layout) + + + +![snap0131](https://user-images.githubusercontent.com/13696193/43417007-df6d8408-9407-11e8-9986-30f0415f08a5.jpg) + +Let's agree the window has 4 rows. + +The first row only has **text** that reads `Rename files or folders` + +The second row has 3 elements in it. First the **text** `Source for Folders`, then an **input** field, then a **browse** button. + +Now let's look at how those 2 rows and the other two row from Python code: + + layout = [[sg.Text('Rename files or folders')], + [sg.Text('Source for Folders', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Text('Source for Files ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()], + [sg.Submit(), sg.Cancel()]] + +See how the source code mirrors the layout? You simply make lists for each row, then submit that table to PySimpleGUI to show and get values from. + +And what about those return values? Most people simply want to show a window, get the input values and do something with them. So why break up the code into button callbacks, etc, when I simply want my window's input values to be given to me. + +For return values the window is scanned from top to bottom, left to right. Each field that's an input field will occupy a spot in the return values. + +In our example window, there are 2 fields, so the return values from this window will be a list with 2 values in it. + + button, (folder_path, file_path) = window.LayoutAndRead(layout) + +In the statement that shows and reads the window, the two input fields are directly assigned to the caller's variables `folder_path` and `file_path`, ready to use. No parsing no callbacks. + +Isn't this what almost every Python programmer looking for a GUI wants?? Something easy to work with to get the values and move on to the rest of the program, where the real action is taking place. Why write pages of GUI code when the same layout can be achieved with PySimpleGUI in 3 or 4 lines of code. 4 lines or 40? I chose 4. + + +## Return values + + As of version 2.8 there are 2 forms of return values, list and dictionary. + +### Return values as a list + + By default return values are a list of values, one entry for each input field. + + Return information from Window, SG's primary window builder interface, is in this format: + + button, (value1, value2, ...) + +Each of the Elements that are Input Elements will have a value in the list of return values. You can unpack your GUI directly into the variables you want to use. + + button, (filename, folder1, folder2, should_overwrite) = window.LayoutAndRead(window_rows) + + Or, you can unpack the return results separately. + + button, values = window.LayoutAndRead(window_rows) + filename, folder1, folder2, should_overwrite = values + +If you have a SINGLE value being returned, it is written this way: + + button, (value1,) = window.LayoutAndRead(window_rows) + + + Another way of parsing the return values is to store the list of values into a variable representing the list of values and then index each individual value. This is not the preferred way of doing it. + + button, value_list = window.LayoutAndRead(window_rows) + value1 = value_list[0] + value2 = value_list[1] + ... + +### Return values as a dictionary + +For windows longer than 3 or 4 fields you will want to use a dictionary to help you organize your return values. In almost all (if not all) of the demo programs you'll find the return values being passed as a dictionary. It is not a difficult concept to grasp, the syntax is easy to understand, and it makes for very readable code. + +The most common window read statement you'll encounter looks something like this: + + button, values = window.LayoutAndRead(layout) + +or + + button, values = window.Read() + +All of your return values will be stored in the variable `values`. When using the dictionary return values, the `values` variable is a dictionary. + + To use a dictionary, you will need to: + * Mark each input element you wish to be in the dictionary with the keyword `key`. + +If **any** element in the window has a `key`, then **all** of the return values are returned via a dictionary. If some elements do not have a key, then they are numbered starting at zero. + +Let's take a look at your first dictionary-based window. + + import PySimpleGUI as sg + window = sg.Window('Simple data entry window') + layout = [ + [sg.Text('Please enter your Name, Address, Phone')], + [sg.Text('Name', size=(15, 1)), sg.InputText('1', key='name')], + [sg.Text('Address', size=(15, 1)), sg.InputText('2', key='address')], + [sg.Text('Phone', size=(15, 1)), sg.InputText('3', key='phone')], + [sg.Submit(), sg.Cancel()] + ] + + button, values = window.LayoutAndRead(layout) + + sg.Popup(button, values, values['name'], values['address'], values['phone']) + +To get the value of an input field, you use whatever value used as the `key` value as the index value. Thus to get the value of the name field, it is written as + + values['name'] + +You will find the key field used quite heavily in most PySimpleGUI windows unless the window is very simple. + +### Button Return Values + +The button value from a Read call will be one of 3 values: +1. The Button's text +2. The Button's key +3. None + +If a button has a key set for it when it's created, then that key will be returned. If no key is set, then the button text is returned. If no button was clicked, but the window returned anyway, the button value is None. + +None is returned when the user clicks the X to close a window. + +If your window has an event loop where it is read over and over, remember to give your user an "out". You should always check for a None value and it's a good practice to provide an Exit button of some kind. Thus design patterns often resemble this Event Loop: + + while True: + button, values= window.Read() + if button is None or button == 'Quit': + break + +## The Event Loop / Callback Functions + +All GUIs have one thing in common, an "event loop" or some kind. If your program shows a single window, collects the data and then executes the primary code of the program then you likely don't need an event loop. + +Event Loops are used in programs where the window ***stays open*** after button presses. The program processes button clicks and user input in a loop called the event loop. You often hear the term event loop when discussing embedded systems or on a Raspberry Pi. + +Let's take a Pi demo program as an example. This program shows a GUI window, gets button presses, and uses them to control some LEDs. It loops, reading user input and doing something with it. + +This little program has a typical Event Loop + +![pi leds](https://user-images.githubusercontent.com/13696193/45448517-8cea7b80-b6a0-11e8-8dbe-eeefea2e93c1.jpg) + + + + import PySimpleGUI as sg + layout = [[sg.T('Raspberry Pi LEDs')], + [sg.RButton('Turn LED On')], + [sg.RButton('Turn LED Off')], + [sg.Exit()]] + + window = sg.Window('Raspberry Pi).Layout(layout) + + # ---- Event Loop ---- # + while True: + button, values = window.Read() + + # ---- Process Button Clicks ---- # + if button is None or button == 'Exit': + break + if button == 'Turn LED Off': + turn_LED_off() + elif button == 'Turn LED On': + turn_LED_on() + + # ---- After Event Loop ---- # + sg.Popup('Done... exiting') + + + +In the Event Loop we are reading the window and then doing a series of button compares to determine what to do based on the button that was clicks (value of `button` variable) + +The way buttons are presented to the caller in PySimpleGUI is ***not*** how *most* GUI frameworks handle button clicks. Most GUI frameworks, including tkinter, use ***callback*** functions, a function you define would be called when a button is clicked. This requires you to write code where data is shared. + +There is a more communications that have to happen between parts of your program when using callbacks. Callbacks can break your program's logic apart and scatter it. One of the larger hurdles for beginners to GUI programming are these callback functions. + +PySimpleGUI was specifically designed in a way that callbacks would not be required. There is no coordination between one function and another required. You simply read your button click and take appropriate action at the same location as when you . + +Whether or not this is a "proper" design for GUI programs can be debated. It's not a terrible trade-off to run your own event loop and having a functioning GUI application versus one that maybe never gets written because callback functions were too much to grasp. + +--- + +## All Widgets / Elements + +This code utilizes as many of the elements in one window as possible. + + import PySimpleGUI as sg + + sg.ChangeLookAndFeel('GreenTan') + + # ------ Menu Definition ------ # + menu_def = [['File', ['Open', 'Save', 'Exit', 'Properties']], + ['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ], + ['Help', 'About...'], ] + + # ------ Column Definition ------ # + column1 = [[sg.Text('Column 1', background_color='#F7F3EC', 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'), initial_value='Spin Box 2')], + [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] + + layout = [ + [sg.Menu(menu_def, tearoff=True)], + [sg.Text('All graphic widgets in one window!', size=(30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)], + [sg.Text('Here is some text.... and a place to enter text')], + [sg.InputText('This is my text')], + [sg.Frame(layout=[ + [sg.Checkbox('Checkbox', size=(10,1)), sg.Checkbox('My second checkbox!', default=True)], + [sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10,1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')], + [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), + sg.Multiline(default_text='A second multi-line', size=(35, 3))], + [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)), + sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], + [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], + [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), + sg.Frame('Labelled Group',[[ + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), + sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), + sg.Column(column1, background_color='#F7F3EC')]])], + [sg.Text('_' * 80)], + [sg.Text('Choose A Folder', size=(35, 1))], + [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), + sg.InputText('Default Folder'), sg.FolderBrowse()], + [sg.Submit(tooltip='Click to submit this window'), sg.Cancel()] + ] + + + window = sg.Window('Everything bagel', default_element_size=(40, 1), grab_anywhere=False).Layout(layout) + + button, values = window.Read() + + sg.Popup('Title', + 'The results of the window.', + 'The button clicked was "{}"'.format(button), + 'The values are', values) + +This is a somewhat complex window with quite a bit of custom sizing to make things line up well. This is code you only have to write once. When looking at the code, remember that what you're seeing is a list of lists. Each row contains a list of Graphical Elements that are used to create the window. + + ![everything bagel](https://user-images.githubusercontent.com/13696193/45914128-87163800-be0e-11e8-9a83-7ee5960e88b9.jpg) + +Clicking the Submit button caused the window call to return. The call to Popup resulted in this dialog box. + +![everything bagel reseults](https://user-images.githubusercontent.com/13696193/45914129-87aece80-be0e-11e8-8aae-9a483a9ad4a6.jpg) + + +**`Note, button value can be None`**. The value for `button` will be the text that is displayed on the button element when it was created. If the user closed the window using something other than a button, then `button` will be `None`. + +You can see in the Popup that the values returned are a list. Each input field in the window generates one item in the return values list. All input fields return a `string` except for Check Boxes and Radio Buttons. These return `bool`. + +--- +# Building Custom windows + +You will find it much easier to write code using PySimpleGUI if you use an IDE such as PyCharm. The features that show you documentation about the API call you are making will help you determine which settings you want to change, if any. In PyCharm, two commands are particularly helpful. + + Control-Q (when cursor is on function name) brings up a box with the function definition + Control-P (when cursor inside function call "()") shows a list of parameters and their default values + +## Synchronous windows +The most common use of PySimpleGUI is to display and collect information from the user. The most straightforward way to do this is using a "blocking" GUI call. Execution is "blocked" while waiting for the user to close the GUI window/dialog box. +You've already seen a number of examples above that use blocking windows. Anytime you see a context manager used (see the `with` statement) it's most likely a blocking window. You can examine the show calls to be sure. If the window is a non-blocking window, it must indicate that in the call to `window.show`. + +NON-BLOCKING window call: + + window.Show(non_blocking=True) + +### Beginning a window +The first step is to create the window object using the desired window customization. + + with Window('Everything bagel', auto_size_text=True, default_element_size=(30,1)) as window: + +This is the definition of the Window object: + + def Window(title, + default_element_size=(DEFAULT_ELEMENT_SIZE[0], DEFAULT_ELEMENT_SIZE[1]), + default_button_element_size = (None, None), + auto_size_text=None, + auto_size_buttons=None, + location=(None, None), + font=None, + button_color=None,Font=None, + progress_bar_color=(None,None), + background_color=None + border_depth=None, + auto_close=False, + auto_close_duration=DEFAULT_AUTOCLOSE_TIME, + icon=DEFAULT_WINDOW_ICON, + force_toplevel=False + return_keyboard_events=False, + use_default_focus=True, + text_justification=None, + no_titlebar=False, + grab_anywhere=False + keep_on_top=False): + + +Parameter Descriptions. You will find these same parameters specified for each `Element` and some of them in `Row` specifications. The `Element` specified value will take precedence over the `Row` and `window` values. + + default_element_size - Size of elements in window in characters (width, height) + default_button_element_size - Size of buttons on this window + auto_size_text - Bool. True if elements should size themselves according to contents. Defaults to True + auto_size_buttons - Bool. True if button elements should size themselves according to their text label + location - (x,y) Location to place window in pixels + font - Font name and size for elements of the window + button_color - Default color for buttons (foreground, background). Can be text or hex + progress_bar_color - Foreground and background colors for progress bars + background_color - Color of the window background + border_depth - Amount of 'bezel' to put on input boxes, buttons, etc. + auto_close - Bool. If True window will autoclose + auto_close_duration - Duration in seconds before window closes + icon - .ICO file that will appear on the Task Bar and end of Title Bar + force_top_level - Bool. If set causes a tk.Tk window to be used as primary window rather than tk.TopLevel. Used to get around Matplotlib problem + return_keyboard_events - if True key presses are returned as buttons + use_default_focus - if True and no focus set, then automatically set a focus + text_justification - Justification to use for Text Elements in this window + no_titlebar - Create window without a titlebar + grab_anywhere - Grab any location on the window to move the window + keep_on_top - if True then window will always stop on top of other windows on the screen. Great for floating toolbars. + + +#### Window Location +PySimpleGUI computes the exact center of your window and centers the window on the screen. If you want to locate your window elsewhere, such as the system default of (0,0), if you have 2 ways of doing this. The first is when the window is created. Use the `location` parameter to set where the window. The second way of doing this is to use the `SetOptions` call which will set the default window location for all windows in the future. + +#### Sizes +Note several variables that deal with "size". Element sizes are measured in characters. A Text Element with a size of 20,1 has a size of 20 characters wide by 1 character tall. + +The default Element size for PySimpleGUI is `(45,1)`. + +Sizes can be set at the element level, or in this case, the size variables apply to all elements in the window. Setting `size=(20,1)` in the window creation call will set all elements in the window to that size. + +There are a couple of widgets where one of the size values is in pixels rather than characters. This is true for Progress Meters and Sliders. The second parameter is the 'height' in pixels. + +#### No Titlebar + +Should you wish to create cool looking windows that are clean with no windows titlebar, use the no_titlebar option when creating the window. + +Be sure an provide your user an "exit" button or they will not be able to close the window! When no titlebar is enabled, there will be no icon on your taskbar for the window. Without an exit button you will need to kill via taskmanager... not fun. + +Windows with no titlebar rely on the grab anywhere option to be enabled or else you will be unable to move the window. + +Windows without a titlebar can be used to easily create a floating launcher. + + +![floating launcher](https://user-images.githubusercontent.com/13696193/45258246-71bafb80-b382-11e8-9f5e-79421e6c00bb.jpg) + + +#### Grab Anywhere + +This is a feature unique to PySimpleGUI. The default is ENABLED.... unless the window is a non-blocking window. + +It is turned off for non-blocking because there is a warning message printed out if the user closes a non-blocking window using a button with grab_anywhere enabled. There is no harm in these messages, but it may be distressing to the user. Should you wish to enable for a non-blocking window, simply get grab_anywhere = True when you create the window. + +#### Always on top + +To keep a window on top of all other windows on the screen, set keep_on_top = True when the window is created. This feature makes for floating toolbars that are very helpful and always visible on your desktop. + +### Window Methods (things you can do with a Window object) + +There are a few methods (functions) that you will see in this document that act on Windows. The ones you will primarily be calling are: + + window.Layout(layout) - Turns your definition of the Window into Window + window.Finalize() - creates the tkinter objects for the Window. Normally you do not call this + window.Read() - Read the Windows values and get the button / key that caused the Read to return + window.ReadNonBlocking() - Same as Read but will return right away + window.Refresh() - Use if updating elements and want to show the updates prior to the nex Read + window.Fill(values_dict) - Fill each Element with entry from the dictionary passed in + window.SaveToDisk(filename) - Save the Window's values to disk + window.LoadFromDisk(filename) - Load the Window's values from disk + window.CloseNonBlocking() - When done, for good, reading a non-blocking window + window.Disable() - Use to disable the window inpurt when opening another window on top of the primnary Window + window.Enable() - Re-enable a Disabled window + window.FindElement(key) - Returns the element that has a matching key value + + + +## Elements +"Elements" are the building blocks used to create windows. Some GUI APIs use the term "Widget" to describe these graphic elements. + + Text + Single Line Input + Buttons including these types: + File Browse + Folder Browse + Calendar picker + Date Chooser + Read window + Close window + Realtime + Checkboxes + Radio Buttons + Listbox + Slider + Multi-line Text Input + Scroll-able Output + Progress Bar + Option Menu + Menu + Frame + Column + Graph + Image + Table + Tab, TabGroup + Async/Non-Blocking Windows + Tabbed windows + Persistent Windows + Redirect Python Output/Errors to scrolling Window + "Higher level" APIs (e.g. MessageBox, YesNobox, ...) + +#### Common Parameters +Some parameters that you will see on almost all Elements are: +key +tooltip + +#### Tooltip +Tooltips are text boxes that popup next to an element if you hold your mouse over the top of it. If you want to be extra kind to your window's user, then you can create tooltips for them by setting the parameter `tooltip` to some text string. You will need to supply your own line breaks / text wrapping. If you don't want to manually add them, then take a look at the standard library package `textwrap`. + +Tooltips are one of those "polish" items that really dress-up a GUI and show's a level of sophistication. Go ahead, impress people, throw some tooltips into your GUI. + + + +### Output Elements +Building a window is simply making lists of Elements. Each list is a row in the overall GUI dialog box. The definition looks something like this: + + layout = [ [row 1 element, row 1 element], + [row 2 element, row 2 element, row 2 element] ] +The code is a crude representation of the GUI, laid out in text. + +#### Text Element + + layout = [[sg.Text('This is what a Text Element looks like')]] + + ![simple text](https://user-images.githubusercontent.com/13696193/44959877-e9d97b00-aec3-11e8-9d24-b4405ee4a148.jpg) + + +The most basic element is the Text element. It simply displays text. Many of the 'options' that can be set for a Text element are shared by other elements. + + Text(text + size=(None, None) + auto_size_text=None + click_submits=None + relief=None + font=None + text_color=None + background_color=None + justification=None + pad=None + key=None + tooltip=None) + +. + + Text - The text that's displayed + size - Element's size + click_submits - if clicked will cause a read call to return they key value as the button + relief - relief to use around the text + auto_size_text - Bool. Change width to match size of text + font - Font name and size to use + text_color - text color + background_color - background color + justification - Justification for the text. String - 'left', 'right', 'center' + pad - (x,y) amount of padding in pixels to use around element when packing + key - used to identify element. This value will return as button if click_submits True + tooltip - string representing tooltip + +Some commonly used elements have 'shorthand' versions of the functions to make the code more compact. The functions `T` and `Txt` are the same as calling `Text`. + +**Fonts** in PySimpleGUI are always in this format: + + (font_name, point_size) + +The default font setting is + + ("Helvetica", 10) + +**Color** in PySimpleGUI are in one of two format. They can be a single color or a color pair. Buttons are an example of a color pair. + + (foreground, background) + + Individual colors are specified using either the color names as defined in tkinter or an RGB string of this format: + + "#RRGGBB" + +**auto_size_text** +A `True` value for `auto_size_text`, when placed on Text Elements, indicates that the width of the Element should be shrunk do the width of the text. The default setting is True. + + - [ ] List item + + +**Shortcut functions** +The shorthand functions for `Text` are `Txt` and `T` + +#### Multiline Text Element + + layout = [[sg.Multiline('This is what a Multi-line Text Element looks like', size=(45,5))]] + +![multiline](https://user-images.githubusercontent.com/13696193/44959853-b139a180-aec3-11e8-972f-f52188510c88.jpg) + +This Element doubles as both an input and output Element. The `DefaultText` optional parameter is used to indicate what to output to the window. + + Multiline(default_text='', + enter_submits = False, + size=(None, None), + auto_size_text=None) +. + + default_text - Text to display in the text box + enter_submits - Bool. If True, pressing Enter key submits window + size - Element's size + auto_size_text - Bool. Change width to match size of text + +#### Output Element +Output re-routes `Stdout` to a scrolled text box. It's used with Async windows. More on this later. + + window.AddRow(gg.Output(size=(100,20))) + +![output](https://user-images.githubusercontent.com/13696193/44959863-b72f8280-aec3-11e8-8caa-7bc743149953.jpg) + + Output(size=(None, None)) +. + + size - Size of element (width, height) in characters + +### Input Elements + These make up the majority of the window definition. Optional variables at the Element level override the window level values (e.g. `size` is specified in the Element). All input Elements create an entry in the list of return values. A Text Input Element creates a string in the list of items returned. + +#### Text Input Element + + layout = [[sg.InputText('Default text')]] + +![inputtext 2](https://user-images.githubusercontent.com/13696193/44959861-b5fe5580-aec3-11e8-8040-53ec241b5079.jpg) + + + def InputText(default_text = '', + size=(None, None), + auto_size_text=None, + password_char='', + background_color=None, + text_color=None, + do_not_clear=False, + key=None, + focus=False + +. + + default_text - Text initially shown in the input box + size - (width, height) of element in characters + auto_size_text- Bool. True is element should be sized to fit text + password_char - Character that will be used to replace each entered character. Setting to a value indicates this field is a password entry field + background_color - color to use for the input field background + text_color - color to use for the typed text + do_not_clear - Bool. Normally windows clear when read, turn off clearing with this flag. + key = Dictionary key to use for return values + focus = Bool. True if this field should capture the focus (moves cursor to this field) + + There are two methods that can be called: + + InputText.Update(new_Value) - sets the input value + Input.Text(Get() - returns the current value of the field. + + +Shorthand functions that are equivalent to `InputText` are `Input` and `In` + + +#### Combo Element +Also known as a drop-down list. Only required parameter is the list of choices. The return value is a string matching what's visible on the GUI. + + layout = [[sg.InputCombo(['choice 1', 'choice 2'])]] + +![combobox](https://user-images.githubusercontent.com/13696193/44959860-b565bf00-aec3-11e8-82fe-dbe41252458b.jpg) + + InputCombo(values, , + default_value=None + size=(None, None) + auto_size_text=None + background_color=None + text_color=None + change_submits=False + disabled=False + key=None + pad=None + tooltip=None +. + + values - Choices to be displayed. List of strings + default_value - which value should be initially chosen + size - (width, height) of element in characters + auto_size_text - Bool. True if size should fit the text length + background_color - color to use for the input field background + text_color - color to use for the typed text + change_submits - Bool. If set causes Read to immediately return if the selected value changes + disabled - Bool. If set will disable changes + key - Dictionary key to use for return values + pad - (x,y) Amount of padding to put around element in pixels + tooltip - Text string. If set, hovering over field will popup the text + +#### Listbox Element +The standard listbox like you'll find in most GUIs. Note that the return values from this element will be a ***list of results, not a single result***. This is because the user can select more than 1 item from the list (if you set the right mode). + + layout = [[sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6))]] + +![listbox 2](https://user-images.githubusercontent.com/13696193/44959859-b4cd2880-aec3-11e8-881c-1e369d5c6337.jpg) + + + Listbox(values + default_values=None + select_mode=None + change_submits=False + bind_return_key=False + size=(None, None) + auto_size_text=None + font=None + background_color=None + text_color=None + key=None + pad=None + tooltip=None): + +. + + values - Choices to be displayed. List of strings + select_mode - Defines how to list is to operate. + Choices include constants or strings: + Constants version: + LISTBOX_SELECT_MODE_BROWSE + LISTBOX_SELECT_MODE_EXTENDED + LISTBOX_SELECT_MODE_MULTIPLE + LISTBOX_SELECT_MODE_SINGLE - the default + Strings version: + 'browse' + 'extended' + 'multiple' + 'single' + change_submits - if True, the window read will return with a button value of '' + bind_return_key - if the focus is on the listbox and the user presses return key, or if the user double clicks an item, then the read will return + size - (width, height) of element in characters + auto_size_text - Bool. True if size should fit the text length + background_color - color to use for the input field background + font - font to use for items in list + text_color - color to use for the typed text + key - Dictionary key to use for return values and to find element + pad - amount of padding to use when packing + tooltip - tooltip text + +The `select_mode` option can be a string or a constant value defined as a variable. Generally speaking strings are used for these kinds of options. + +ListBoxes can cause a window to return from a Read call. If the flag change_submits is set, then when a user makes a selection, the Read immediately returns. +Another way ListBoxes can cause Reads to return is if the flag bind_return_key is set. If True, then if the user presses the return key while an entry is selected, then the Read returns. Also, if this flag is set, if the user double-clicks an entry it will return from the Read. + +#### Slider Element + +Sliders have a couple of slider-specific settings as well as appearance settings. Examples include the `orientation` and `range` settings. + + layout = [[sg.Slider(range=(1,500), default_value=222, size=(20,15), orientation='horizontal', font=('Helvetica', 12))]] + +![slider](https://user-images.githubusercontent.com/13696193/44959858-b4349200-aec3-11e8-9e25-c0fcf025d19e.jpg) + + Slider(range=(None,None), + default_value=None, + orientation=None, + border_width=None, + relief=None, + size=(None, None), + font=None, + background_color = None, + change_submits = False, + text_color = None, + key = None) ): +. + + range - (min, max) slider's range + default_value - default setting (within range) + orientation - 'horizontal' or 'vertical' ('h' or 'v' work) + border_width - how deep the widget looks + relief - relief style. Values are same as progress meter relief values. Can be a constant or a string: + RELIEF_RAISED= 'raised' + RELIEF_SUNKEN= 'sunken' + RELIEF_FLAT= 'flat' + RELIEF_RIDGE= 'ridge' + RELIEF_GROOVE= 'groove' + RELIEF_SOLID = 'solid' + size - (width, height) of element in characters + auto_size_text - Bool. True if size should fit the text + background_color - color to use for the input field background + text_color - color to use for the typed text + change_submits - causes window read to immediately return if the checkbox value changes + key = Dictionary key to use for return values + +#### Radio Button Element + +Creates one radio button that is assigned to a group of radio buttons. Only 1 of the buttons in the group can be selected at any one time. + + layout = [[sg.Radio('My first Radio!', "RADIO1", default=True), sg.Radio('My second radio!', "RADIO1")]] + +![radio](https://user-images.githubusercontent.com/13696193/44959857-b4349200-aec3-11e8-8e2d-e6a49ffbd0b6.jpg) + + Radio(text, + group_id, + default=False, + size=(None, None), + auto_size_text=None, + font=None, + background_color = None, + text_color = None, + key = None) + +. + + text - Text to display next to button + group_id - Groups together multiple Radio Buttons. Can be any value + default - Bool. Initial state + size- (width, height) size of element in characters + auto_size_text - Bool. True if should size width to fit text + font - Font type and size for text display + background_color - color to use for the background + text_color - color to use for the text + key = Dictionary key to use for return values + + +#### Checkbox Element +Checkbox elements are like Radio Button elements. They return a bool indicating whether or not they are checked. + + layout = [[sg.Checkbox('My first Checkbox!', default=True), sg.Checkbox('My second Checkbox!')]] + + +![checkbox](https://user-images.githubusercontent.com/13696193/44959906-6f5d2b00-aec4-11e8-9c8a-962c787f0286.jpg) + + + Checkbox(text, + default=False, + size=(None, None), + auto_size_text=None, + font=None, + background_color = None, + text_color = None, + change_submits = False + key = None): +. + + text - Text to display next to checkbox + default- Bool + None. Initial state. True = Checked, False = unchecked, None = Not available (grayed out) + size - (width, height) size of element in characters + auto_size_text- Bool. True if should size width to fit text + font- Font type and size for text display + background_color - color to use for the background + text_color - color to use for the typed text + change_submits - causes window read to immediately return if the checkbox value changes + key = Dictionary key to use for return values + + +#### Spin Element + +An up/down spinner control. The valid values are passed in as a list. + + layout = [[sg.Spin([i for i in range(1,11)], initial_value=1), sg.Text('Volume level')]] + +![spinner](https://user-images.githubusercontent.com/13696193/44959855-b1d23800-aec3-11e8-9f51-afb2109879da.jpg) + + Spin(values, + intiial_value=None, + size=(None, None), + auto_size_text=None, + font=None, + background_color = None, + text_color = None, + key = None): +. + + values - List of valid values + initial_value - String with initial value + size - (width, height) size of element in characters + auto_size_text - Bool. True if should size width to fit text + font - Font type and size for text display + background_color - color to use for the background + text_color - color to use for the typed text + change_submits - causes window read to immediately return if the spinner value changes + key = Dictionary key to use for return values + +### Button Element + +Buttons are the most important element of all! They cause the majority of the action to happen. After all, it's a button press that will get you out of a window, whether it be Submit or Cancel, one way or another a button is involved in all windows. The only exception is to this is when the user closes the window using the "X" in the upper corner which means no button was involved. + +The Types of buttons include: +* Folder Browse +* File Browse +* Files Browse +* File SaveAs +* File Save +* Close window (normal button) +* Read window +* Realtime +* Calendar Chooser +* Color Chooser + + + Close window - Normal buttons like Submit, Cancel, Yes, No, etc, are "Close window" buttons. They cause the input values to be read and then the window is ***closed***, returning the values to the caller. + +Folder Browse - When clicked a folder browse dialog box is opened. The results of the Folder Browse dialog box are written into one of the input fields of the window. + +File Browse - Same as the Folder Browse except rather than choosing a folder, a single file is chosen. + +Calendar Chooser - Opens a graphical calendar to select a date. + +Color Chooser - Opens a color chooser dialog + +Read window - This is a window button that will read a snapshot of all of the input fields, but does not close the window after it's clicked. + +Realtime - This is another async window button. Normal button clicks occur after a button's click is released. Realtime buttons report a click the entire time the button is held down. + +Most programs will use a combination of shortcut button calls (Submit, Cancel, etc), plain buttons that close the window, and ReadForm buttons that keep the window open but returns control back to the caller. + +Sometimes there are multiple names for the same function. This is simply to make the job of the programmer quicker and easier. + +The 3 primary windows of PySimpleGUI buttons and their names are: + + 1. `Button` = `SimpleButton` + 2. `ReadButton` = `RButton` = `ReadFormButton` (old style... use ReadButton instead) + 3. `RealtimeButton` + +You will find the long-form in the older programs. + +The most basic Button element call to use is `Button` + + Button(button_text='' + button_type=BUTTON_TYPE_CLOSES_WIN + target=(None, None) + tooltip=None + file_types=(("ALL Files", "*.*"),) + initial_folder=None + image_filename=None + image_size=(None, None) + image_subsample=None + border_width=None + size=(None, None) + auto_size_button=None + button_color=None + default_value = None + font=None + bind_return_key=False + focus=False + pad=None + key=None): + +Parameters + + button_text - Text to be displayed on the button + button_type - You should NOT be setting this directly + target - key or (row,col) target for the button + tooltip - tooltip text for the button + file_types - the filetypes that will be used to match files + initial_folder - starting path for folders and files + image_filename - image filename if there is a button image + image_size - size of button image in pixels + image_subsample - amount to reduce the size of the image + border_width - width of border around button in pixels + size - size in characters + auto_size_button - True if button size is determined by button text + button_color - (text color, backound color) + default_value - initial value for buttons that hold information + font - font to use for button text + bind_return_key - If True the return key will cause this button to fire + focus - if focus should be set to this button + pad - (x,y) padding in pixels for packing the button + key - key used for finding the element + +#### Pre-defined Buttons +These Pre-made buttons are some of the most important elements of all because they are used so much. They all basically do the same thing, set the button text to match the function name and set the parameters to commonly used values. If you find yourself needing to create a custom button often because it's not on this list, please post a request on GitHub. . They include: + + OK + Ok + Submit + Cancel + Yes + No + Exit + Quit + Help + Save + SaveAs + FileBrowse + FilesBrowse + FileSaveAs + FolderBrowse +. + layout = [[sg.OK(), sg.Cancel()]] + +![ok cancel 3](https://user-images.githubusercontent.com/13696193/44959927-aa5f5e80-aec4-11e8-86e1-5dc0b3a2b803.jpg) + + #### Button targets + +The `FileBrowse`, `FolderBrowse`, `FileSaveAs` , `FilesSaveAs`, `CalendarButton`, `ColorChooserButton` buttons all fill-in values into another element located on the window. The target can be a Text Element or an InputText Element. The location of the element is specified by the `target` variable in the function call. + +The Target comes in two forms. +1. Key +2. (row, column) + +Targets that are specified using a key will find its target element by using the target's key value. This is the "preferred" method. + +If the Target is specified using (row, column) then it utilizes a grid system. The rows in your GUI are numbered starting with 0. The target can be specified as a hard coded grid item or it can be relative to the button. + +The (row, col) targeting can only target elements that are in the same "container". Containers are the Window, Column and Frame Elements. A File Browse button located inside of a Column is unable to target elements outside of that Column. + +The default value for `target` is `(ThisRow, -1)`. `ThisRow` is a special value that tells the GUI to use the same row as the button. The Y-value of -1 means the field one value to the left of the button. For a File or Folder Browse button, the field that it fills are generally to the left of the button is most cases. (ThisRow, -1) means the Element to the left of the button, on the same row. + +If a value of `(None, None)` is chosen for the target, then the button itself will hold the information. Later the button can be queried for the value by using the button's key. + +Let's examine this window as an example: + + +![file browse](https://user-images.githubusercontent.com/13696193/44959944-d1b62b80-aec4-11e8-8a68-9d79d37b2c81.jpg) + + +The `InputText` element is located at (1,0)... row 1, column 0. The `Browse` button is located at position (2,0). The Target for the button could be any of these values: + + Target = (1,0) + Target = (-1,0) + +The code for the entire window could be: + + layout = [[sg.T('Source Folder')], + [sg.In()], + [sg.FolderBrowse(target=(-1, 0)), sg.OK()]] + +or if using keys, then the code would be: + + layout = [[sg.T('Source Folder')], + [sg.In(key='input')], + [sg.FolderBrowse(target='input'), sg.OK()]] + +See how much easier the key method is? + +**Save & Open Buttons** + +There are 3 different types of File/Folder open dialog box available. If you are looking for a file to open, the `FileBrowse` is what you want. If you want to save a file, `SaveAs` is the button. If you want to get a folder name, then `FolderBrowse` is the button to use. To open several files at once, use the `FilesBrowse` button. It will create a list of files that are separated by ';' + + +![open](https://user-images.githubusercontent.com/13696193/45243804-2b529780-b2c3-11e8-90dc-6c9061db2a1e.jpg) + + +![folder](https://user-images.githubusercontent.com/13696193/45243805-2b529780-b2c3-11e8-95ee-fec3c0b11319.jpg) + + +![saveas](https://user-images.githubusercontent.com/13696193/45243807-2beb2e00-b2c3-11e8-8549-ba71cdc05951.jpg) + + + +**Calendar Buttons** + +These buttons pop up a calendar chooser window. The chosen date is returned as a string. + +![calendar](https://user-images.githubusercontent.com/13696193/45243374-99965a80-b2c1-11e8-8311-49777835ca40.jpg) + +**Color Chooser Buttons** + +These buttons pop up a standard color chooser window. The result is returned as a tuple. One of the returned values is an RGB hex representation. + +![color](https://user-images.githubusercontent.com/13696193/45243375-99965a80-b2c1-11e8-9779-b71bed85fab6.jpg) + + +**Custom Buttons** +Not all buttons are created equal. A button that closes a window is different that a button that returns from the window without closing it. If you want to define your own button, you will generally do this with the Button Element `Button`, which closes the window when clicked. + +layout = [[sg.Button('My Button')]] + +![button](https://user-images.githubusercontent.com/13696193/44959862-b696ec00-aec3-11e8-9e88-4b9af0338a03.jpg) + +All buttons can have their text changed by changing the `button_text` variable in the button call. It is this text that is returned when a window is read. This text will be what tells you which button is called so make it unique. Most of the convenience buttons (Submit, Cancel, Yes, etc) are all Buttons. Some that are not are `FileBrowse` , `FolderBrowse`, `FileSaveAs`. They clearly do not close the window. Instead they bring up a file or folder browser dialog box. + +**Button Images** +Now this is an exciting feature not found in many simplified packages.... images on buttons! You can make a pretty spiffy user interface with the help of a few button images. + +Your button images need to be in PNG or GIF format. When you make a button with an image, set the button background to the same color as the background. There's a button color TRANSPARENT_BUTTON that you can set your button color to in order for it to blend into the background. Note that this value is currently the same as the color as the default system background on Windows. + +This example comes from the `Demo Media Player.py` example program. Because it's a non-blocking button, it's defined as `RButton`. You also put images on blocking buttons by using `Button`. + + + sg.RButton('Restart Song', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0) + +Three parameters are used for button images. + + image_filename - Filename. Can be a relative path + image_size - Size of image file in pixels + image_subsample - Amount to divide the size by. 2 means your image will be 1/2 the size. 3 means 1/3 + +Here's an example window made with button images. + +![media file player](https://user-images.githubusercontent.com/13696193/43161977-9ee7cace-8f57-11e8-8ff8-3ea24b69dab9.jpg) + +You'll find the source code in the file Demo Media Player. Here is what the button calls look like to create media player window + + sg.RButton('Pause', button_color=sg.TRANSPARENT_BUTTON, + image_filename=image_pause, image_size=(50, 50), image_subsample=2, border_width=0) + +This is one you'll have to experiment with at this point. Not up for an exhaustive explanation. + + **Realtime Buttons** + + Normally buttons are considered "clicked" when the mouse button is let UP after a downward click on the button. What about times when you need to read the raw up/down button values. A classic example for this is a robotic remote control. Building a remote control using a GUI is easy enough. One button for each of the directions is a start. Perhaps something like this: + +![robot remote](https://user-images.githubusercontent.com/13696193/44959958-ff9b7000-aec4-11e8-99ea-7450926409be.jpg) + + +This window has 2 button types. There's the normal "Simple Button" (Quit) and 4 "Realtime Buttons". + +Here is the code to make, show and get results from this window: + + window = sg.Window('Robotics Remote Control', auto_size_text=True) + + window_rows = [[sg.Text('Robotics Remote Control')], + [sg.T(' '*10), sg.RealtimeButton('Forward')], + [ sg.RealtimeButton('Left'), sg.T(' '*15), sg.RealtimeButton('Right')], + [sg.T(' '*10), sg.RealtimeButton('Reverse')], + [sg.T('')], + [sg.Quit(button_color=('black', 'orange'))] + ] + + window.LayoutAndRead(window_rows, non_blocking=True) + +Somewhere later in your code will be your main event loop. This is where you do your polling of devices, do input/output, etc. It's here that you will read your window's buttons. + + while (True): + # This is the code that reads and updates your window + button, values = window.ReadNonBlocking() + if button is not None: + sg.Print(button) + if button == 'Quit' or values is None: + break + time.sleep(.01) + +This loop will read button values and print them. When one of the Realtime buttons is clicked, the call to `window.ReadNonBlocking` will return a button name matching the name on the button that was depressed. It will continue to return values as long as the button remains depressed. Once released, the ReadNonBlocking will return None for buttons until a button is again clicked. + +**File Types** +The `FileBrowse` & `SaveAs` buttons have an additional setting named `file_types`. This variable is used to filter the files shown in the file dialog box. The default value for this setting is + + FileTypes=(("ALL Files", "*.*"),) + +This code produces a window where the Browse button only shows files of type .TXT + + layout = [[sg.In() ,sg.FileBrowse(file_types=(("Text Files", "*.txt"),))]] + + ***The ENTER key*** + The ENTER key is an important part of data entry for windows. There's a long tradition of the enter key being used to quickly submit windows. PySimpleGUI implements this by tying the ENTER key to the first button that closes or reads a window. + +The Enter Key can be "bound" to a particular button so that when the key is pressed, it causes the window to return as if the button was clicked. This is done using the `bind_return_key` parameter in the button calls. +If there are more than 1 button on a window, the FIRST button that is of type Close window or Read window is used. First is determined by scanning the window, top to bottom and left to right. + + --- +#### ProgressBar +The `ProgressBar` element is used to build custom Progress Bar windows. It is HIGHLY recommended that you use OneLineProgressMeter that provides a complete progress meter solution for you. Progress Meters are not easy to work with because the windows have to be non-blocking and they are tricky to debug. + +The **easiest** way to get progress meters into your code is to use the `OneLineProgressMeter` API. This consists of a pair of functions, `OneLineProgressMeter` and `OneLineProgressMeterCancel`. You can easily cancel any progress meter by calling it with the current value = max value. This will mark the meter as expired and close the window. +You've already seen OneLineProgressMeter calls presented earlier in this readme. + + sg.OneLineProgressMeter('My Meter', i+1, 1000, 'key', 'Optional message') + +The return value for `OneLineProgressMeter` is: +`True` if meter updated correctly +`False` if user clicked the Cancel button, closed the window, or vale reached the max value. + +#### Progress Mater in Your window +Another way of using a Progress Meter with PySimpleGUI is to build a custom window with a `ProgressBar` Element in the window. You will need to run your window as a non-blocking window. When you are ready to update your progress bar, you call the `UpdateBar` method for the `ProgressBar` element itself. + +![progress custom](https://user-images.githubusercontent.com/13696193/45243969-c3508100-b2c3-11e8-82bc-927d0307e093.jpg) + + import PySimpleGUI as sg + + # layout the window + layout = [[sg.Text('A custom progress meter')], + [sg.ProgressBar(10000, orientation='h', size=(20, 20), key='progressbar')], + [sg.Cancel()]] + + # create the window` + window = sg.Window('Custom Progress Meter').Layout(layout) + progress_bar = window.FindElement('progressbar') + # loop that would normally do something useful + for i in range(10000): + # check to see if the cancel button was clicked and exit loop if clicked + button, values = window.ReadNonBlocking() + if button == 'Cancel' or values == None: + break + # update bar with loop value +1 so that bar eventually reaches the maximum + progress_bar.UpdateBar(i + 1) + # done with loop... need to destroy the window as it's still open + window.CloseNonBlocking()) + + +#### Output +The Output Element is a re-direction of Stdout. Anything "printed" will be displayed in this element. + + Output(size=(None, None)) + +Here's a complete solution for a chat-window using an Async window with an Output Element + + import PySimpleGUI as sg + + # Blocking window that doesn't close + def ChatBot(): + layout = [[(sg.Text('This is where standard out is being routed', size=[40, 1]))], + [sg.Output(size=(80, 20))], + [sg.Multiline(size=(70, 5), enter_submits=True), + sg.RButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0])), + sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]] + + window = sg.Window('Chat Window', default_element_size=(30, 2)).Layout(layout) + + # ---===--- Loop taking in user input and using it to query HowDoI web oracle --- # + while True: + button, value = window.Read() + if button == 'SEND': + print(value) + else: + break + + ChatBot() + +------------------- +## Columns +Starting in version 2.9 you'll be able to do more complex layouts by using the Column Element. Think of a Column as a window within a window. And, yes, you can have a Column within a Column if you want. + +Columns are specified in exactly the same way as a window is, as a list of lists. + + def Column(layout - the list of rows that define the layout + background_color - color of background + size - size of visible portion of column + pad - element padding to use when packing + scrollable - bool. True if should add scrollbars + + +Columns are needed when you have an element that has a height > 1 line on the left, with single-line elements on the right. Here's an example of this kind of layout: + + +![column](https://user-images.githubusercontent.com/13696193/44959988-66b92480-aec5-11e8-9c26-316ed24a68c0.jpg) + + +This code produced the above window. + + + import PySimpleGUI as sg + + # Demo of how columns work + # window has on row 1 a vertical slider followed by a COLUMN with 7 rows + # Prior to the Column element, this layout was not possible + # Columns layouts look identical to window layouts, they are a list of lists of elements. + + window = sg.Window('Columns') # blank window + + # Column layout + col = [[sg.Text('col Row 1')], + [sg.Text('col Row 2'), sg.Input('col input 1')], + [sg.Text('col Row 3'), sg.Input('col input 2')], + [sg.Text('col Row 4'), sg.Input('col input 3')], + [sg.Text('col Row 5'), sg.Input('col input 4')], + [sg.Text('col Row 6'), sg.Input('col input 5')], + [sg.Text('col Row 7'), sg.Input('col input 6')]] + + layout = [[sg.Slider(range=(1,100), default_value=10, orientation='v', size=(8,20)), sg.Column(col)], + [sg.In('Last input')], + [sg.OK()]] + + # Display the window and get values + # If you're willing to not use the "context manager" design pattern, then it's possible + # to collapse the window display and read down to a single line of code. + button, values = sg.Window('Compact 1-line window with column').LayoutAndRead(layout) + + sg.Popup(button, values, line_width=200) + +The Column Element has 1 required parameter and 1 optional (the layout and the background color). Setting the background color has the same effect as setting the window's background color, except it only affects the column rectangle. + + Column(layout, background_color=None) + +The default background color for Columns is the same as the default window background color. If you change the look and feel of the window, the column background will match the window background automatically. + + + +---- +## Frames (Labelled Frames, Frames with a title) + +Frames work exactly the same way as Columns. You create layout that is then used to initialize the Frame. + + def Frame(title - the label / title to put on frame + layout - list of rows of elements the frame contains + title_color - color of the title text + background_color - color of background + title_location - locations to put the title + relief - type of relief to use + size - size of Frame in characters. Do not use if you want frame to autosize + font - font to use for title + pad - element padding to use when packing + border_width - how thick the line going around frame should be + key - key used to location the element + tooltip - tooltip text + + + +This code creates a window with a Frame and 2 buttons. + + frame_layout = [ + [sg.T('Text inside of a frame')], + [sg.CB('Check 1'), sg.CB('Check 2')], + ] + layout = [ + [sg.Frame('My Frame Title', frame_layout, font='Any 12', title_color='blue')], + [sg.Submit(), sg.Cancel()] + ] + + window = sg.Window('Frame with buttons', font=("Helvetica", 12)).Layout(layout) + + +![frame element](https://user-images.githubusercontent.com/13696193/45889173-c2245700-bd8d-11e8-8f73-1e5f1be3ddb1.jpg) + + + +Notice how the Frame layout looks identical to a window layout. A window works exactly the same way as a Column and a Frame. They all are "container elements". Elements that contain other elements. + +*These container Elements can be nested as deep as you want.* That's a pretty spiffy feature, right? Took a lot of work so be appreciative. Recursive code isn't trivial. + +## Canvas Element + +In my opinion, the tkinter Canvas Widget is the most powerful of the tkinter widget. While I try my best to completely isolate the user from anything that is tkinter related, the Canvas Element is the one exception. It enables integration with a number of other packages, often with spectacular results. + +### Matplotlib, Pyplot Integration + +One such integration is with Matploplib and Pyplot. There is a Demo program written that you can use as a design pattern to get an understanding of how to use the Canvas Widget once you get it. + + def Canvas(canvas - a tkinter canvasf if you created one. Normally not set + background_color - canvas color + size - size in pixels + pad - element padding for packing + key - key used to lookup element + tooltip - tooltip text + +The order of operations to obtain a tkinter Canvas Widget is: + + figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds + # define the window layout + layout = [[sg.Text('Plot test')], + [sg.Canvas(size=(figure_w, figure_h), key='canvas')], + [sg.OK(pad=((figure_w / 2, 0), 3), size=(4, 2))]] + + # create the window and show it without the plot + window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize() + + + # add the plot to the window + fig_photo = draw_figure(window.FindElement('canvas').TKCanvas, fig) + + # show it all again and get buttons + button, values = window.Read() + +To get a tkinter Canvas Widget from PySimpleGUI, follow these steps: +* Add Canvas Element to your window +* Layout your window +* Call `window.Finalize()` - this is a critical step you must not forget +* Find the Canvas Element by looking up using key +* Your Canvas Widget Object will be the found_element.TKCanvas +* Draw on your canvas to your heart's content +* Call `window.Read()` - Nothing will appear on your canvas until you call Read + +See `Demo_Matplotlib.py` for a Recipe you can copy. + + +## Graph Element + +All you math fans will enjoy this Element... and all you non-math fans will enjoy it too. + +I've found nothing to be less fun than dealing with a graphic's coordinate system from a GUI Framework. It's always upside down from what I want. (0,0) is in the upper left hand corner. In short, it's a **pain in the ass**. + +Graph Element to the rescue. A Graph Element creates a pixel addressable canvas using YOUR coordinate system. *You* get to define the units on the X and Y axis. + +There are 3 values you'll need to supply the Graph Element. They are: +* Size of the canvas in pixels +* The lower left (x,y) coordinate of your coordinate system +* The upper right (x,y) coordinate of your coordinate system + +After you supply those values you can scribble all of over your graph by creating Graph Figures. Graph Figures are created, and a Figure ID is obtained by calling: +* DrawCircle +* DrawLine +* DrawPoint +* DrawRectangle +* DrawOval + +You can move your figures around on the canvas by supplying the Figure ID the x,y amount to move. + + graph.MoveFigure(my_circle, 10, 10) + +This Element is relatively new and may have some parameter additions or deletions. It shouldn't break your code however. + + def Graph( canvas_size - size of canvas in pixels + graph_bottom_left - the x,y location of your coordinate system's bottom left point + graph_top_right - the x,y location of your coordinate system's top right point + background_color - color to use for background + pad - element padding for pack + key - key used to lookup element + tooltip - tooltip text + + + +## Table Element + +Let me say up front that the Table Element has Beta status. The reason is that some of the parameters are not quite right and will change. Be warned one or two parameters may change. The `size` parameter in particular is gong to change. Currently the number of rows to allocate for the table is set by the height parameter of size. The problem is that the width is not used. The plan is to instead have a parameter named `number_of_rows` or something like it. + + def Table(values - Your table's array + headings - list of strings representing your headings, if you have any + visible_column_map - list of bools. If True, column in that position is shown. Defaults to all columns + col_widths - list of column widths + def_col_width - default column width. defaults to 10 + auto_size_columns - bool. If True column widths are determined by table contents + max_col_width - maximum width of a column. defaults to 25 + select_mode - table rows can be selected, but doesn't currently do anything + display_row_numbers - bool. If True shows numbers next to rows + scrollable - if True table will be scrolled + font - font for table entries + justification - left, right, center + text_color - color of text + background_color - cell background color + size - (None, number of rows). + pad - element padding for packing + key - key used to lookup element + tooltip - tooltip text + + + + +## Tab and Tab Group Elements + +Tabs have been a part of PySimpleGUI since the initial release. However, the initial implementation applied tabs at the top level only. The entire window had to be tabbed. There with other limitations that came along with that implementation. That all changed in version 3.8.0 with the new elements - Tab and TabGroup. The old implementation of Tabs was removed in version 3.8.0 as well. + +Tabs are another "Container Element". The other Container Elements include: +* Frame +* Column + +You layout a Frame in exactly the same way as a Frame or Column elements, by passing in a list of elements. + +How you place a Tab into a Window is different than Graph or Frame elements. You cannot place a tab directly into a Window's layout. It much first be placed into a TabGroup. The TabGroup can then be placed into the Window. + +Let's look at this Window as an example: + +![tabbed 1](https://user-images.githubusercontent.com/13696193/45992808-b10f6a80-c059-11e8-9746-ac71afd4d3d6.jpg) + +View of second tab: + +![tabbed 2](https://user-images.githubusercontent.com/13696193/45992809-b10f6a80-c059-11e8-94e6-3bf543c9b0bd.jpg) + + +First we have the Tab layout definitions. They mirror what you see in the screen shots. Tab 1 has 1 Text Element in it. Tab 2 has a Text and an Input Element. + + + tab1_layout = [[sg.T('This is inside tab 1')]] + + tab2_layout = [[sg.T('This is inside tab 2')], + [sg.In(key='in')]] + +The layout for the entire window looks like this: + + layout = [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout), sg.Tab('Tab 2', tab2_layout)]])], + [sg.RButton('Read')]] + +The Window layout has the TabGroup and within the tab Group are the two Tab elements. + +One important thing to notice about all of these container Elements... they all take a "list of lists" at the layout. They all have a layout that starts with `[[` + +You will want to keep this `[[ ]]` construct in your head a you're debugging your tabbed windows. It's easy to overlook one or two necessary ['s + +As mentioned earlier, the old-style Tabs were limited to being at the Window-level only. In other words, the tabs were equal in size to the entire window. This is not the case with the "new-style" tabs. This is why you're not going to be upset when you discover your old code no longer works with the new PySimpleGUI release. It'll be worth the few moments it'll take to convert your code. + +Check out what's possible with the NEW Tabs! + +![tabs tabs tabs](https://user-images.githubusercontent.com/13696193/45993438-fd0fde80-c05c-11e8-9ed0-742f14d3070f.jpg) + + +Check out Tabs 7 and 8. We've got a Window with a Column containing Tabs 5 and 6. On Tab 6 are... Tabs 7 and 8. + +As of Release 3.8.0, not all of *options* shown in the API definitions of the Tab and TabGroup Elements are working. They are there as placeholders. + +The definition of a TabGroup is + + TabGroup(layout, + title_color=None + background_color=None + font=None + pad=None + border_width=None + change_submits = False + key=None + tooltip=None) + +The definition of a Tab Element is + + Tab(title, + layout, + title_color=None, + background_color=None, + size=(None, None),font=None, + pad=None + border_width=None + change_submits=False + key=None + tooltip=None) + + + ## Colors ## +Starting in version 2.5 you can change the background colors for the window and the Elements. + +Your windows can go from this: + +![snap0155](https://user-images.githubusercontent.com/13696193/43273879-a9fdc10a-90cb-11e8-8c20-4f6a244ebe2f.jpg) + + +to this... with one function call... + + +![snap0156](https://user-images.githubusercontent.com/13696193/43273880-aa1955e6-90cb-11e8-94b6-673ecdb2698c.jpg) + + + +While you can do it on an element by element or window level basis, the easiest way, by far, is a call to `SetOptions`. + +Be aware that once you change these options they are changed for the rest of your program's execution. All of your windows will have that look and feel, until you change it to something else (which could be the system default colors. + +This call sets all of the different color options. + + SetOptions(background_color='#9FB8AD', + text_element_background_color='#9FB8AD', + element_background_color='#9FB8AD', + scrollbar_color=None, + input_elements_background_color='#F7F3EC', + progress_meter_color = ('green', 'blue') + button_color=('white','#475841')) + + + +## Global Settings +**Global Settings** +Let's have some fun customizing! Make PySimpleGUI look the way you want it to look. You can set the global settings using the function `PySimpleGUI.SetOptions`. Each option has an optional parameter that's used to set it. + + SetOptions(icon=None + button_color=(None,None) + element_size=(None,None), + margins=(None,None), + element_padding=(None,None) + auto_size_text=None + auto_size_buttons=None + font=None + border_width=None + slider_border_width=None + slider_relief=None + slider_orientation=None + autoclose_time=None + message_box_line_width=None + progress_meter_border_depth=None + progress_meter_style=None + progress_meter_relief=None + progress_meter_color=None + progress_meter_size=None + text_justification=None + text_color=None + background_color=None + element_background_color=None + text_element_background_color=None + input_elements_background_color=None + element_text_color=None + input_text_color=None + scrollbar_color=None, text_color=None + debug_win_size=(None,None) + window_location=(None,None) + tooltip_time = None + +Explanation of parameters + + icon - filename of icon used for taskbar and title bar + button_color - button color (foreground, background) + element_size - element size (width, height) in characters + margins - tkinter margins around outsize + element_padding - tkinter padding around each element + auto_size_text - autosize the elements to fit their text + auto_size_buttons - autosize the buttons to fit their text + font - font used for elements + border_width - amount of bezel or border around sunken or raised elements + slider_border_width - changes the way sliders look + slider_relief - changes the way sliders look + slider_orientation - changes orientation of slider + autoclose_time - time in seconds for autoclose boxes + message_box_line_width - number of characers in a line of text in message boxes + progress_meter_border_depth - amount of border around raised or lowered progress meters + progress_meter_style - style of progress meter as defined by tkinter + progress_meter_relief - relief style + progress_meter_color - color of the bar and background of progress meters + progress_meter_size - size in (characters, pixels) + background_color - Color of the main window's background + element_background_color - Background color of the elements + text_element_background_color - Text element background color + input_elements_background_color - Input fields background color + element_text_color - Text color of elements that have text, like Radio Buttons + input_text_color - Color of the text that you type in + scrollbar_color - Color for scrollbars (may not always work) + text_color - Text element default text color + text_justification - justification to use on Text Elements. Values are strings - 'left', 'right', 'center' + debug_win_size - size of the Print output window + window_location - location on the screen (x,y) of window's top left cornder + tooltip_time - time in milliseconds to wait before showing a tooltip. Default is 400ms + + +These settings apply to all windows `SetOptions`. The Row options and Element options will take precedence over these settings. Settings can be thought of as levels of settings with the window-level being the highest and the Element-level the lowest. Thus the levels are: + + - window level + - Row level + - Element level + +Each lower level overrides the settings of the higher level. Once settings have been changed, they remain changed for the duration of the program (unless changed again). + +## Persistent windows (Window stays open after button click) + +There are 2 ways to keep a window open after the user has clicked a button. One way is to use non-blocking windows (see the next section). The other way is to use buttons that 'read' the window instead of 'close' the window when clicked. The typical buttons you find in windows, including the shortcut buttons, close the window. These include OK, Cancel, Submit, etc. The Button Element also closes the window. + +The `RButton` Element creates a button that when clicked will return control to the user, but will leave the window open and visible. This button is also used in Non-Blocking windows. The difference is in which call is made to read the window. The `Read` call will block, the `ReadNonBlocking` will not block. + + + +## Asynchronous (Non-Blocking) windows +So you want to be a wizard do ya? Well go boldly! + +Use async windows sparingly. It's possible to have a window that appears to be async, but it is not. **Please** try to find other methods before going to async windows. The reason for this plea is that async windows poll tkinter over and over. If you do not have a sleep in your loop, you will eat up 100% of the CPU time. + +When to use a non-blocking window: +* A media file player like an MP3 player +* A status dashboard that's periodically updated +* Progress Meters - when you want to make your own progress meters +* Output using print to a scrolled text element. Good for debugging. + +If your application doesn't follow the basic design pattern at one of those, then it shouldn't be executed as a non-blocking window. + + +### Instead of ReadNonBlocking --- Use `change_submits = True` or return_keyboard_events = True + +Any time you are thinking "I want an X Element to cause a Y Element to do something", then you want to use the `change_submits` option. + +***Instead of polling, try options that cause the window to return to you.*** By using non-blocking windows, you are *polling*. You can indeed create your application by polling. It will work. But you're going to be maxing out your processor and may even take longer to react to an event than if you used another technique. + +**Examples** + +One example is you have an input field that changes as you press buttons on an on-screen keypad. + +![keypad 3](https://user-images.githubusercontent.com/13696193/45260275-a2198e80-b3b0-11e8-85fe-a4ce6484510f.jpg) + + + + +### Periodically Calling`ReadNonBlocking` + +Periodically "refreshing" the visible GUI. The longer you wait between updates to your GUI the more sluggish your windows will feel. It is up to you to make these calls or your GUI will freeze. + +There are 2 methods of interacting with non-blocking windows. +1. Read the window just as you would a normal window +2. "Refresh" the window's values without reading the window. It's a quick operation meant to show the user the latest values + + With asynchronous windows the window is shown, user input is read, but your code keeps right on chugging. YOUR responsibility is to call `PySimpleGUI.ReadNonBlocking` on a periodic basis. Once a second or more will produce a reasonably snappy GUI. + + #### Exiting a Non-Blocking window + +It's important to always provide a "way out" for your user. Make sure you have provided a button or some other mechanism to exit. Also be sure to check for closed windows in your code. It is possible for a window to look closed, but continue running your event loop. + +Typically when reading a window you check `if Button is None` to determine if a window was closed. With NonBlocking windows, buttons will be None unless a button or a key was returned. The way you determine if a window was closed in a non-blocking window is to check **both** the button and the values are None. Since button is normally None, you only need to test for `value is None` in your code. + +The proper code to check if the user has exited the window will be a polling-loop that looks something like this: + + while True: + button, values = window.ReadNonBlocking() + if values is None or button == 'Quit': + break + + +We're going to build an app that does the latter. It's going to update our window with a running clock. + +The basic flow and functions you will be calling are: +Setup + + window = Window() + window_rows = ..... + window.LayoutAndRead(window_rows, non_blocking=True) + + +Periodic refresh + + window.ReadNonBlocking() or window.Refresh() + +If you need to close the window + + window.CloseNonBlocking() + +Rather than the usual `window.LayoutAndRead()` call, we're manually adding the rows (doing the layout) and then showing the window. After the window is shown, you simply call `window.ReadNonBlocking()` every now and then. + +When you are ready to close the window (assuming the window wasn't closed by the user or a button click) you simply call `window.CloseNonBlocking()` + +**Example - Running timer that updates** +See the sample code on the GitHub named Demo Media Player for another example of Async windows. We're going to make a window and update one of the elements of that window every .01 seconds. Here's the entire code to do that. + + + import PySimpleGUI as sg + import time + + # window that doesn't block + # Make a window, but don't use context manager + window = sg.Window('Running Timer', auto_size_text=True) + + # Create the layout + window_rows = [[sg.Text('Non-blocking GUI with updates')], + [sg.Text('', size=(8, 2), font=('Helvetica', 20), key='output') ], + [sg.Button('Quit')]] + # Layout the rows of the window and perform a read. Indicate the window is non-blocking! + window.LayoutAndRead(window_rows, non_blocking=True) + + # + # Some place later in your code... + # You need to perform a ReadNonBlocking on your window every now and then or + # else it won't refresh + # + + for i in range(1, 1000): + window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format(*divmod(int(i / 100), 60), i % 100)) + button, values = window.ReadNonBlocking() + if values is None or button == 'Quit': + break + time.sleep(.01) + else: + window.CloseNonBlocking() + + +What we have here is the same sequence of function calls as in the description. Get a window, add rows to it, show the window, and then refresh it every now and then. + +The new thing in this example is the call use of the Update method for the Text Element. The first thing we do inside the loop is "update" the text element that we made earlier. This changes the value of the text field on the window. The new value will be displayed when `window.ReadNonBlocking()` is called. if you want to have the window reflect your changes immediately, call `window.Refresh()`. + +Note the `else` statement on the for loop. This is needed because we're about to exit the loop while the window is still open. The user has not closed the window using the X nor a button so it's up to the caller to close the window using `CloseNonBlocking`. + +## Updating Elements (changing elements in active window) + +Persistent windows remain open and thus continue to interact with the user after the Read has returned. Often the program wishes to communicate results (output information) or change an Element's values (such as populating a List Element). + +The way this is done is via an Update method that is available for nearly all of the Elements. Here is an example of a program that uses a persistent window that is updated. + +![snap0272](https://user-images.githubusercontent.com/13696193/45260249-ec4e4000-b3af-11e8-853b-9b29d0bf7797.jpg) + + +In some programs these updates happen in response to another Element. This program takes a Spinner and a Slider's input values and uses them to resize a Text Element. The Spinner and Slider are on the left, the Text element being changed is on the right. + + + + + + # Testing async window, see if can have a slider + # that adjusts the size of text displayed + + import PySimpleGUI as sg + fontSize = 12 + layout = [[sg.Spin([sz for sz in range(6, 172)], font=('Helvetica 20'), initial_value=fontSize, change_submits=True, key='spin'), + sg.Slider(range=(6,172), orientation='h', size=(10,20), + change_submits=True, key='slider', font=('Helvetica 20')), + sg.Text("Aa", size=(2, 1), font="Helvetica " + str(fontSize), key='text')]] + + sz = fontSize + window = sg.Window("Font size selector", grab_anywhere=False).Layout(layout) + # Event Loop + while True: + button, values= window.Read() + if button is None: + break + sz_spin = int(values['spin']) + sz_slider = int(values['slider']) + sz = sz_spin if sz_spin != fontSize else sz_slider + if sz != fontSize: + fontSize = sz + font = "Helvetica " + str(fontSize) + window.FindElement('text').Update(font=font) + window.FindElement('slider').Update(sz) + window.FindElement('spin').Update(sz) + + print("Done.") + + +Inside the event loop we read the value of the Spinner and the Slider using those Elements' keys. +For example, `values['slider']` is the value of the Slider Element. + +This program changes all 3 elements if either the Slider or the Spinner changes. This is done with these statements: + + window.FindElement('text').Update(font=font) + window.FindElement('slider').Update(sz) + window.FindElement('spin').Update(sz) + +Remember this design pattern because you will use it OFTEN if you use persistent windows. + +It works as follows. The call to `window.FindElement` returns the Element object represented by they provided `key`. This element is then updated by calling it's `Update` method. This is another example of Python's "chaining" feature. We could write this code using the long-form: + + text_element = window.FindElement('text') + text_element.Update(font=font) + +The takeaway from this exercise is that keys are key in PySimpleGUI's design. They are used to both read the values of the window and also to identify elements. As already mentioned, they are used as targets in Button calls. + + + +## Keyboard & Mouse Capture +Beginning in version 2.10 you can capture keyboard key presses and mouse scroll-wheel events. Keyboard keys can be used, for example, to detect the page-up and page-down keys for a PDF viewer. To use this feature, there's a boolean setting in the Window call `return_keyboard_events` that is set to True in order to get keys returned along with buttons. + +Keys and scroll-wheel events are returned in exactly the same way as buttons. + +For scroll-wheel events, if the mouse is scrolled up, then the `button` text will be `MouseWheel:Up`. For downward scrolling, the text returned is `MouseWheel:Down` + +Keyboard keys return 2 types of key events. For "normal" keys (a,b,c, etc), a single character is returned that represents that key. Modifier and special keys are returned as a string with 2 parts: + + Key Sym:Key Code + +Key Sym is a string such as 'Control_L'. The Key Code is a numeric representation of that key. The left control key, when pressed will return the value 'Control_L:17' + + import PySimpleGUI as sg + + # Recipe for getting keys, one at a time as they are released + # If want to use the space bar, then be sure and disable the "default focus" + + with sg.Window("Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window: + text_elem = sg.Text("", size=(18,1)) + layout = [[sg.Text("Press a key or scroll mouse")], + [text_elem], + [sg.Button("OK")]] + + window.Layout(layout) + # ---===--- Loop taking in user input --- # + while True: + button, value = window.ReadNonBlocking() + + if button == "OK" or (button is None and value is None): + print(button, "exiting") + break + if button is not None: + text_elem.Update(button) + +You want to turn off the default focus so that there no buttons that will be selected should you press the spacebar. + +### Realtime Keyboard Capture +Use realtime keyboard capture by calling + + import PySimpleGUI as sg + + with sg.Window("Realtime Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window: + layout = [[sg.Text("Hold down a key")], + [sg.Button("OK")]] + + window.Layout(layout) + + while True: + button, value = window.ReadNonBlocking() + + if button == "OK": + print(button, value, "exiting") + break + if button is not None: + print(button) + elif value is None: + break + +## Menus + +Beginning in version 3.01 you can add a menubar to your window. You specify the menus in much the same way as you do window layouts, with lists. Menu selections are returned as button clicks, so be aware of your overall naming conventions. If you have an Exit button and also an Exit menu option, then you won't be able to tell the difference when your window.Read returns. Hopefully will not be a problem. + +This definition: + + menu_def = [['File', ['Open', 'Save', 'Exit',]], + ['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],], + ['Help', 'About...'],] + +Note the placement of ',' and of []. It's tricky to get the nested menus correct that implement cascading menus. See how paste has Special and Normal as a list after it. This means that Paste has a cascading menu with items Special and Normal. + +They menu_def layout produced this window: + +![menu](https://user-images.githubusercontent.com/13696193/45306723-56b7cb00-b4eb-11e8-8cbd-faef0c90f8b4.jpg) + + + + +## Updating Elements + +This is a somewhat advanced topic... + +Typically you perform Element updates in response to events from other Elements. An example is that when you click a button some text on the window changes to red. You can change the Element's attributes, or at least some of them, and the Element's value. + +In some source code examples you will find an older techique for updating elements that did not involve keys. If you see a technique in the code that does not use keys, then know that there is a version using keys that is easier. + +Here's the key's version.... +We have an InputText field that we want to update. When the Element was created we used this call: + + sg.Input(key='input') + +To update or change the value for that Input Element, we use this construct: + + window.FindElement('input').Update('new text') + +Using the '.' makes the code shorter. The FindElement call returns an Element. We then call that Element's Update function. + +See the Font Sizer demo for example source code. + +You can use Update to do things like: +* Have one Element (appear to) make a change to another Element +* Disable a button, slider, input field, etc +* Change a button's text +* Change an Element's text or background color +* Add text to a scrolling output window +* Change the choices in a list +* etc + + ### Updating Multiple Elements + If you have a large number of Elements to update, you can call `Window.UpdateElements()`. + +` UpdateElements(key_list, + value_list)` + +`key_list` - list of keys for elements you wish to update +`value_list` - list of values, one for each key + + window.UpdateElements(('name', 'address', 'phone'), ('Fred Flintstone', '123 Rock Quarry Road', '555#')) + + +## Sample Applications + +Use the example programs as a starting basis for your GUI. Copy, paste, modify and run! The demo files are: + + | Source File| Description | +|--|--| +|**Demo_All_Widgets.py**| Nearly all of the Elements shown in a single window +|**Demo_Borderless_Window.py**| Create clean looking windows with no border +|**Demo_Button_States.py**| One way of implementing disabling of buttons +|**Demo_Calendar.py** | Demo of the Calendar Chooser button +|**Demo_Canvas.py** | window with a Canvas Element that is updated outside of the window +|**Demo_Chat.py** | A chat window with scrollable history +|**Demo_Chatterbot.py** | Front-end to Chatterbot Machine Learning project +|**Demo_Color.py** | How to interact with color using RGB hex values and named colors +|**Demo_Columns.py** | Using the Column Element to create more complex windows +|**Demo_Compare_Files.py** | Using a simple GUI front-end to create a compare 2-files utility +|**Demo_Cookbook_Browser.py** | Source code browser for all Recipes in Cookbook +|**Demo_Dictionary.py** | Specifying and using return values in dictionary format +**Demo_DOC_Viewer_PIL.py** | Display a PDF, HTML, ebook file, etc in your window +|**Demo_DisplayHash1and256.py** | Using high level API and custom window to implement a simple display hash code utility +|**Demo_DuplicateFileFinder.py** | High level API used to get a folder that is used by utility that finds duplicate files. Uses progress meter to show progress. 2 lines of code required to add GUI and meter +|**Demo_Fill_Form.py** | How to perform a bulk-fill for a window. Saving and loading a window from disk +|**Demo Font Sizer.py** | Demonstrates Elements updating other Elements +|**Demo_Func_Callback_Simulator.py** | For the Raspberry Pi crowd. Event loop that simulates traditional GUI callback functions should you already have an architecture that uses them +|**Demo_GoodColors.py** | Using some of the pre-defined PySimpleGUI individual colors +|**Demo_HowDoI.py** | This is a utility to be experienced! It will change how you code +|**Demo_Img_Viewer.py** | Display jpg, png,tiff, bmp files +|**Demo_Keyboard.py** | Using blocking keyboard events +|**Demo_Keyboard_Realtime.py** | Using non-blocking / realtime keyboard events +|**Demo_Machine_Learning.py** | A sample Machine Learning front end +|**Demo_Matplotlib.py** | Integrating with Matplotlib to create a single graph +|**Demo_Matplotlib_Animated.py** | Animated Matplotlib line graph +|**Demo_Matplotlib_Animated_Scatter.py** | Animated Matplotlib scatter graph +|**Demo_Matplotlib_Browser.py** | Browse Matplotlib gallery +|**Demo_Media_Player.py** | Non-blocking window with a media player layout. Demonstrates button graphics, Update method +|**Demo_MIDI_Player.py** | GUI wrapper for Mido MIDI package. Functional MIDI player that controls attached MIDI devices +|**Demo_NonBlocking_Form.py** | a basic async window +|**Demo_OpenCV.py** | Integrated with OpenCV +|**Demo_Password_Login** | Password protection using SHA1 +|**Demo_PDF_Viewer.py** | Submitted by a user! Previews PDF documents. Uses keyboard input & mouse scrollwheel to navigate +|**Demo_Pi_LEDs.py** | Control GPIO using buttons +|**Demo_Pi_Robotics.py** | Simulated robot control using realtime buttons +|**Demo_PNG_Vierwer.py** | Uses Image Element to display PNG files +| **Demo_Progress_Meters.py** | Demonstrates using 2 progress meters simultaneously +|**Demo_Recipes.py** | A collection of various Recipes. Note these are not the same as the Recipes in the Recipe Cookbook +|**Demo_Script_Launcher.py** | Demonstrates one way of adding a front-end onto several command line scripts +|**Demo_Script_Parameters.py** | Add a 1-line GUI to the front of your previously command-line only scripts +|**Demo_Tabbed_Form.py** | Using the Tab feature +|**Demo_Table_Simulation.py** | Use input fields to display and edit tables +|**Demo_Timer.py** | Simple non-blocking window + +## Packages Used In Demos + + + While the core PySimpleGUI code does not utilize any 3rd party packages, some of the demos do. They add a GUI to a few popular packages. These packages include: + * [Chatterbot](https://github.com/gunthercox/ChatterBot) + * [Mido](https://github.com/olemb/mido) + * [Matplotlib](https://matplotlib.org/) + * [PyMuPDF](https://github.com/rk700/PyMuPDF) + + +## Creating a Windows .EXE File + +It's possible to create a single .EXE file that can be distributed to Windows users. There is no requirement to install the Python interpreter on the PC you wish to run it on. Everything it needs is in the one EXE file, assuming you're running a somewhat up to date version of Windows. + +Installation of the packages, you'll need to install PySimpleGUI and PyInstaller (you need to install only once) + +``` +pip install PySimpleGUI +pip install PyInstaller + +``` + +To create your EXE file from your program that uses PySimpleGUI, `my_program.py`, enter this command in your Windows command prompt: + +``` +pyinstaller -wF my_program.py + +``` + +You will be left with a single file, `my_program.exe`, located in a folder named `dist` under the folder where you executed the `pyinstaller` command. + +That's all... Run your `my_program.exe` file on the Windows machine of your choosing. + +> "It's just that easy." + +(famous last words that screw up just about anything being referenced) + +Your EXE file should run without creating a "shell window". Only the GUI window should show up on your taskbar. + +If you get a crash with something like: +``` +ValueError: script '.......\src\tkinter' not found +``` + +Then try adding **`--hidden-import tkinter`** to your command + + + +## Fun Stuff +Here are some things to try if you're bored or want to further customize + +**Debug Output** +Be sure and check out the EasyPrint (Print) function described in the high-level API section. Leave your code the way it is, route your stdout and stderror to a scrolling window. + +For a fun time, add these lines to the top of your script + + import PySimpleGUI as sg + print = sg.Print + +This will turn all of your print statements into prints that display in a window on your screen rather than to the terminal. + +**Look and Feel** +Dial in the look and feel that you like with the `SetOptions` function. You can change all of the defaults in one function call. One line of code to customize the entire GUI. +Or beginning in version 2.9 you can choose from a look and feel using pre-defined color schemes. Call ChangeLookAndFeel with a description string. + + sg.ChangeLookAndFeel('GreenTan') + +Valid values for the description string are: + + GreenTan + LightGreen + BluePurple + Purple + BlueMono + GreenMono + BrownBlue + BrightColors + NeutralBlue + Kayak + SandyBeach + TealMono + +To see the latest list of color choices, take a look at the bottom of the `PySimpleGUI.py` file where you'll find the `ChangLookAndFeel` function. + +You can also combine the `ChangeLookAndFeel` function with the `SetOptions` function to quickly modify one of the canned color schemes. Maybe you like the colors but was more depth to your bezels. You can dial in exactly what you want. + +**ObjToString** +Ever wanted to easily display an objects contents easily? Use ObjToString to get a nicely formatted recursive walk of your objects. +This statement: + + print(sg.ObjToSting(x)) + +And this was the output + + + abc = abc + attr12 = 12 + c = + b = + a = + attr1 = 1 + attr2 = 2 + attr3 = three + attr10 = 10 + attrx = x + +You'll quickly wonder how you ever coded without it. + +--- +# Known Issues +While not an "issue" this is a ***stern warning*** + +## **Do not attempt** to call `PySimpleGUI` from multiple threads! It's `tkinter` based and `tkinter` has issues with multiple threads + +**Progress Meters** - the visual graphic portion of the meter may be off. May return to the native tkinter progress meter solution in the future. Right now a "custom" progress meter is used. On the bright side, the statistics shown are extremely accurate and can tell you something about the performance of your code. If you are running 2 or more progress meters at the same time using `OneLineProgressMeter`, you need to close the meter by using the "Cancel" button rather than the X + +**Async windows** - these include the 'easy' windows (`OneLineProgressMeter` and EasyPrint/Print). If you start overlapping having Async windows open with normal windows then things get a littler squirrelly. Still tracking down the issues and am making it more solid every day possible. You'll know there's an issue when you see blank window. + +**EasyPrint** - EasyPrint is a new feature that's pretty awesome. You print and the output goes to a window, with a scroll bar, that you can copy and paste from. Being a new feature, it's got some potential problems. There are known interaction problems with other GUI windows. For example, closing a Print window can also close other windows you have open. For now, don't close your debug print window until other windows are closed too. + +## Contributing + +A MikeTheWatchGuy production... entirely responsible for this code.... unless it causes you trouble in which case I'm not at all responsible. + +## Versions +|Version | Description | +|--|--| +| 1.0.9 | July 10, 2018 - Initial Release | +| 1.0.21 | July 13, 2018 - Readme updates | +| 2.0.0 | July 16, 2018 - ALL optional parameters renamed from CamelCase to all_lower_case +| 2.1.1 | July 18, 2018 - Global settings exposed, fixes +| 2.2.0| July 20, 2018 - Image Elements, Print output +| 2.3.0 | July 23, 2018 - Changed form.Read return codes, Slider Elements, Listbox element. Renamed some methods but left legacy calls in place for now. +| 2.4.0 | July 24, 2018 - Button images. Fixes so can run on Raspberry Pi +| 2.5.0 | July 26, 2018 - Colors. Listbox scrollbar. tkinter Progress Bar instead of homegrown. +| 2.6.0 | July 27, 2018 - auto_size_button setting. License changed to LGPL 3+ +| 2.7.0 | July 30, 2018 - realtime buttons, window_location default setting +| 2.8.0 | Aug 9, 2018 - New None default option for Checkbox element, text color option for all elements, return values as a dictionary, setting focus, binding return key +| 2.9.0 | Aug 16,2018 - Screen flash fix, `do_not_clear` input field option, `autosize_text` defaults to `True` now, return values as ordered dict, removed text target from progress bar, rework of return values and initial return values, removed legacy Form.Refresh() method (replaced by Form.ReadNonBlockingForm()), COLUMN elements!!, colored text defaults +| 2.10.0 | Aug 25, 2018 - Keyboard & Mouse features (Return individual keys as if buttons, return mouse scroll-wheel as button, bind return-key to button, control over keyboard focus), SaveAs Button, Update & Get methods for InputText, Update for Listbox, Update & Get for Checkbox, Get for Multiline, Color options for Text Element Update, Progess bar Update can change max value, Update for Button to change text & colors, Update for Image Element, Update for Slider, Form level text justification, Turn off default focus, scroll bar for Listboxes, Images can be from filename or from in-RAM, Update for Image). Fixes - text wrapping in buttons, msg box, removed slider borders entirely and others +| 2.11.0 | Aug 29, 2018 - Lots of little changes that are needed for the demo programs to work. Buttons have their own default element size, fix for Mac default button color, padding support for all elements, option to immediately return if list box gets selected, FilesBrowse button, Canvas Element, Frame Element, Slider resolution option, Form.Refresh method, better text wrapping, 'SystemDefault' look and feel settin +| 2.20.0 | Sept 4, 2018 - Some sizable features this time around of interest to advanced users. Renaming of the MsgBox functions to Popup. Renaming GetFile, etc, to PopupGetFile. High-level windowing capabilities start with Popup, PopupNoWait/PopupNonblocking, PopupNoButtons, default icon, change_submits option for Listbox/Combobox/Slider/Spin/, New OptionMenu element, updating elements after shown, system defaul color option for progress bars, new button type (Dummy Button) that only closes a window, SCROLLABLE Columns!! (yea, playing in the Big League now), LayoutAndShow function removed, form.Fill - bulk updates to forms, FindElement - find element based on key value (ALL elements have keys now), no longer use grid packing for row elements (a potentially huge change), scrolled text box sizing changed, new look and feel themes (Dark, Dark2, Black, Tan, TanBlue, DarkTanBlue, DarkAmber, DarkBlue, Reds, Green) +| 2.30.0 | Sept 6, 2018 - Calendar Chooser (button), borderless windows, load/save form to disk +| 3.0.0 | Sept 7, 2018 - The "fix for poor choice of 2.x numbers" release. Color Chooser (button), "grab anywhere" windows are on by default, disable combo boxes, Input Element text justification (last part needed for 'tables'), Image Element changes to support OpenCV?, PopupGetFile and PopupGetFolder have better no_window option +| 3.01.01 | Sept 10, 2018 - Menus! (sort of a big deal) +| 3.01.02 | Step 11, 2018 - All Element.Update functions have a `disabled` parameter so they can be disabled. Renamed some parameters in Update function (sorry if I broke your code), fix for bug in Image.Update. Wasn't setting size correctly, changed grab_anywhere logic again,added grab anywhere option to PupupGetText (assumes disabled) +| 3.02.00 | Sept 14, 2018 - New Table Element (Beta release), MsgBox removed entirely, font setting for InputText Element, **packing change** risky change that allows some Elements to be resized,removed command parameter from Menu Element, new function names for ReadNonBlocking (Finalize, PreRead), change to text element autosizing and wrapping (yet again), lots of parameter additions to Popup functions (colors, etc). +| 3.03.00 | New feature - One Line Progress Meters, new display_row_numbers for Table Element, fixed bug in EasyProgresssMeters (function will soon go away), OneLine and Easy progress meters set to grab anywhere but can be turned off. +| 03,04.00 | Sept 18, 2018 - New features - Graph Element, Frame Element, more settings exposed to Popup calls. See notes below for more. +| 03.04.01 | Sept 18, 2018 - See release notes +| 03.05.00 | Sept 20, 2018 - See release notes +| 03.05.01 | Sept 22, 2018 - See release notes +| 03.05.02 | Sept 23, 2018 - See release notes +| 03.06.00 | Sept 23, 2018 - Goodbye FlexForm, hello Window +| 03.08.00 | Sept 25, 2018 - Tab and TabGroup Elements\ +| 01.01.00 for 2.7 | Sept 25, 2018 - First release for 2.7 + + +### Release Notes +2.3 - Sliders, Listbox's and Image elements (oh my!) + +If using Progress Meters, avoid cancelling them when you have another window open. It could lead to future windows being blank. It's being worked on. + +New debug printing capability. `sg.Print` + +2.5 Discovered issue with scroll bar on `Output` elements. The bar will match size of ROW not the size of the element. Normally you never notice this due to where on a form the `Output` element goes. + +Listboxes are still without scrollwheels. The mouse can drag to see more items. The mouse scrollwheel will also scroll the list and will `page up` and `page down` keys. + +2.7 Is the "feature complete" release. Pretty much all features are done and in the code + +2.8 More text color controls. The caller has more control over things like the focus and what buttons should be clicked when enter key is pressed. Return values as a dictionary! (NICE addition) + +2.9 COLUMNS! This is the biggest feature and had the biggest impact on the code base. It was a difficult feature to add, but it was worth it. Can now make even more layouts. Almost any layout is possible with this addition. + +.................. insert releases 2.9 to 2.30 ................. + +3.0 We've come a long way baby! Time for a major revision bump. One reason is that the numbers started to confuse people the latest release was 2.30, but some people read it as 2.3 and thought it went backwards. I kinda messed up the 2.x series of numbers, so why not start with a clean slate. A lot has happened anyway so it's well earned. + +One change that will set PySimpleGUI apart is the parlor trick of being able to move the window by clicking on it anywhere. This is turned on by default. It's not a common way to interact with windows. Normally you have to move using the titlebar. Not so with PySimpleGUI. Now you can drag using any part of the window. You will want to turn this off for windows with sliders. This feature is enabled in the Window call. + +Related to the Grab Anywhere feature is the no_titlebar option, again found in the call to Window. Your window will be a spiffy, borderless window. It's a really interesting effect. Slight problem is that you do not have an icon on the taskbar with these types of windows, so if you don't supply a button to close the window, there's no way to close it other than task manager. + +3.0.2 Still making changes to Update methods with many more ahead in the future. Continue to mess with grab anywhere option. Needed to disable in more places such as the PopupGetText function. Any time these is text input on a form, you generally want to turn off the grab anywhere feature. + +#### 3.2.0 + Biggest change was the addition of the Table Element. Trying to make changes so that form resizing is a possibility but unknown if will work in the long run. Removed all MsgBox, Get* functions and replaced with Popup functions. Popups had multiple new parameters added to change the look and feel of a popup. + +#### 3.3.0 +OneLineProgressMeter function added which gives you not only a one-line solution to progress meters, but it also gives you the ability to have more than 1 running at the same time, something not possible with the EasyProgressMeterCall + +#### 3.4.0 + +* Frame - New Element - a labelled frame for grouping elements. Similar + to Column +* Graph (like a Canvas element except uses the caller's + coordinate system rather than tkinter's). +* initial_folder - sets starting folder for browsing type buttons (browse for file/folder). +* Buttons return key value rather than button text **If** a `key` is specified, +* + OneLineProgressMeter! Replaced EasyProgressMeter (sorry folks that's + the way progress works sometimes) + * Popup - changed ALL of the Popup calls to provide many more customization settings + * Popup + * PopupGetFolder + * PopupGetFile + * PopupGetText + * Popup + * PopupNoButtons + * PopupNonBlocking + * PopupNoTitlebar + * PopupAutoClose + * PopupCancel + * PopupOK + * PopupOKCancel + * PopupYesNo + +#### 3.4.1 +* Button.GetText - Button class method. Returns the current text being shown on a button. +* Menu - Tearoff option. Determines if menus should allow them to be torn off +* Help - Shorcut button. Like Submit, cancel, etc +* ReadButton - shortcut for ReadFormButton + +#### 3.5.0 +* Tool Tips for all elements +* Clickable text +* Text Element relief setting +* Keys as targets for buttons +* New names for buttons: + * Button = SimpleButton + * RButton = ReadButton = ReadFormButton +* Double clickable list entries +* Auto sizing table widths works now +* Feature DELETED - Scaling. Removed from all elements + +#### 3.5.1 +* Bug fix for broken PySimpleGUI if Python version < 3.6 (sorry!) +* LOTS of Readme changes + +#### 3.5.2 +* Made `Finalize()` in a way that it can be chained +* Fixed bug in return values from Frame Element contents + +#### 3.6.0 +* Renamed FlexForm to Window +* Removed LookAndFeel capability from Mac platform. + +#### 3.8.0 +* Tab and TabGroup Elements - awesome new capabilities + +#### 1.0.0 Python 2.7 +It's official. There is a 2.7 version of PySimpleGUI! + +#### 3.8.2 +* Exposed `TKOut` in Output Element +* `DrawText` added to Graph Elements +* Removed `Window.UpdateElements` +* `Window.grab_anywere` defaults to False + +#### 3.8.3 +* Listbox, Slider, Combobox, Checkbox, Spin, Tab Group - if change_submits is set, will return the Element's key rather than '' +* Added change_submits capability to Checkbox, Tab Group +* Combobox - Can set value to an Index into the Values table rather than the Value itself +* Warnings added to Drawing routines for Graph element (rather than crashing) +* Window - can "force top level" window to be used rather than a normal window. Means that instead of calling Tk to get a window, will call TopLevel to get the window +* Window Disable / Enable - Disables events (button clicks, etc) for a Window. Use this when you open a second window and want to disable the first window from doing anything. This will simulate a 'dialog box' +* Tab Group returns a value with Window is Read. Return value is the string of the selected tab +* Turned off grab_anywhere for Popups +* New parameter, default_extension, for PopupGetFile +* Keyboard shortcuts for menu items. Can hold ALT key to select items in men +* Removed old-style Tabs - Risky change because it hit fundamental window packing and creation. Will also break any old code using this style tab (sorry folks this is how progress happens) + + +### Upcoming +Make suggestions people! Future release features + +Port to other graphic engines. Hook up the front-end interface to a backend other than tkinter. Qt, WxPython, etc. WxPython is higher priority. + + + +## Code Condition + + Make it run + Make it right + Make it fast + +It's a recipe for success if done right. PySimpleGUI has completed the "Make it run" phase. It's far from "right" in many ways. These are being worked on. The module is particularly poor for PEP 8 compliance. It was a learning exercise that turned into a somewhat complete GUI solution for lightweight problems. + +While the internals to PySimpleGUI are a tad sketchy, the public interfaces into the SDK are more strictly defined and comply with PEP 8 for the most part. + +Please log bugs and suggestions in the GitHub! It will only make the code stronger and better in the end, a good thing for us all, right? + +## Design + +A moment about the design-spirit of `PySimpleGUI`. From the beginning, this package was meant to take advantage of Python's capabilities with the goal of programming ease. + +**Single File** +While not the best programming practice, the implementation resulted in a single file solution. Only one file is needed, PySimpleGUI.py. You can post this file, email it, and easily import it using one statement. + +**Functions as objects** +In Python, functions behave just like object. When you're placing a Text Element into your form, you may be sometimes calling a function and other times declaring an object. If you use the word Text, then you're getting an object. If you're using `Txt`, then you're calling a function that returns a `Text` object. + +**Lists** +It seemed quite natural to use Python's powerful list constructs when possible. The form is specified as a series of lists. Each "row" of the GUI is represented as a list of Elements. When the form read returns the results to the user, all of the results are presented as a single list. This makes reading a form's values super-simple to do in a single line of Python code. + +**Dictionaries** +Want to view your form's results as a dictionary instead of a list... no problem, just use the `key` keyword on your elements. For complex forms with a lot of values that need to be changed frequently, this is by far the best way of consuming the results. + +You can also look up elements using their keys. This is an excellent way to update elements in reaction to another element. Call `form.FindElement(key)` to get the Element. + + +## Author +MikeTheWatchGuy + +## Demo Code Contributors + + [JorjMcKie](https://github.com/JorjMcKie) - PDF and image viewers (plus a number of code suggestions) +[Otherion](https://github.com/Otherion) - Table Demos Panda & CSV. Loads of suggestions to the core APIs + +## License + +GNU Lesser General Public License (LGPL 3) + + +## Acknowledgments + +* [JorjMcKie](https://github.com/JorjMcKie) was the motivator behind the entire project. His wxsimpleGUI concepts sparked PySimpleGUI into existence +* [Fredrik Lundh](https://wiki.python.org/moin/FredrikLundh) for his work on `tkinter` +* [Ruud van der Ham](https://forum.pythonistacafe.com/u/Ruud) for all the help he's provided as a Python-mentor. Quite a few tricky bits of logic was supplied by Ruud. The dual-purpose return values scheme is Ruud's for example +* **Numerous** users who provided feature suggestions! Many of the cool features were suggested by others. If you were one of them and are willing to take more credit, I'll list you here if you give me permission. Most are too modest +* [moshekaplan](https://github.com/moshekaplan)/**[tkinter_components](https://github.com/moshekaplan/tkinter_components)** wrote the code for the Calendar Chooser Element. It was lifted straight from GitHub +* [Bryan Oakley](https://stackoverflow.com/users/7432/bryan-oakley) for the code that enables the `grab_anywhere` feature. +* [Otherion](https://github.com/Otherion) for help with Tables, being a sounding board for new features, naming functions, ..., all around great help +* [agjunyent](https://github.com/agjunyent) figured out how to properly make tabs and wrote prototype code that demonstrated how to do it +* [jfongattw](https://github.com/jfongattw) huge suggestion... dictionaries. turned out to be +* one of the most critical constructs in PySimpleGUI +* [venim](https://github.com/venim) code to doing Alt-Selections in menus, updating Combobox using index, request to disable windows (a really good idea), checkbox and tab submits on change, returning keys for elements that have change_submits set, ... + + +## How Do I +Finally, I must thank the fine folks at How Do I. +https://github.com/gleitz/howdoi +Their utility has forever changed the way and pace in which I can program. I urge you to try the HowDoI.py application here on GitHub. Trust me, **it's going to be worth the effort!** +Here are the steps to run that application + + Install howdoi: + pip install howdoi + Test your install: + python -m howdoi howdoi.py + To run it: + Python HowDoI.py + +The pip command is all there is to the setup. + +The way HowDoI works is that it uses your search term to look through stack overflow posts. It finds the best answer, gets the code from the answer, and presents it as a response. It gives you the correct answer OFTEN. It's a miracle that it work SO well. +For Python questions, I simply start my query with 'Python'. Let's say you forgot how to reverse a list in Python. When you run HowDoI and ask this question, this is what you'll see. + +![howdoiwithhistory](https://user-images.githubusercontent.com/13696193/45064009-5fd61180-b07f-11e8-8ead-eb0d1ff3a6be.jpg) + + + +In the hands of a competent programmer, this tool is **amazing**. It's a must-try kind of program that has completely changed my programming process. I'm not afraid of asking for help! You just have to be smart about using what you find. + +The PySimpleGUI window that the results are shown in is an 'input' field which means you can copy and paste the results right into your code. + + +