def main(ServerName): #main window layout for managing clients window = sg.Window(ServerName, mainLayout) exit = 0 while not exit: window = sg.Window(ServerName, mainLayout) if not parseWindow(window): exit = 1 window.Close() pass window.Close() pass
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() 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
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()
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 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
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)
def creategui(): sg.ChangeLookAndFeel('BlueMono') frame_layout = [ [sg.T('Elapsed', size=(60, 1), key='-ELAPSED-')], [sg.Multiline('', size=(60, 12), autoscroll=True, key='-ML-')], ] # define the window layout layout = [[ sg.Text('OMRON HVC P2 Demo GUI', size=(50, 1), justification='center', font='Helvetica 20') ], [sg.Image(filename='', key='image'), sg.Frame('Result', frame_layout)], [ sg.ReadButton('Exit', size=(10, 1), pad=((0, 0), 3), font='Helvetica 14'), sg.RButton('Pause', key='-RUN-PAUSE-', size=(10, 1), font='Any 14') ]] # create the window and show it without the plot window = sg.Window('OMRON HVC P2 Demo Application', location=(400, 200)) #window.Layout(layout).Finalize() window.Layout(layout) return window
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)
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)
def startup(): layout = [[sg.Text('Please enter the name of your server:')], [sg.InputText()], [sg.Submit(), sg.Cancel()]] window = sg.Window('Project0', layout) event, values = window.Read() window.Close() ServerName = values[0] return ServerName
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)
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 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 openFileBox(): layout = [[sg.T('Source Folder')], [sg.In()], [sg.FileBrowse(target=(-1, 0)), sg.OK()]] window = sg.Window("Choose File", layout) event, values = window.Read() if event == "OK": return values else: return 0
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
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()
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)
def start_app(): layout = [[ sg.Text('Enter the last four of your phone number', size=(75, 1), justification='center', font=("Helvetica", 18)) ], [ sg.Text('', size=(35, 1)), sg.InputText(font=("Helvetica", 18), justification='center', size=(30, 1), key='input_box') ], [ sg.Text('', size=(35, 1)), sg.ReadButton('Submit'), sg.Text('', size=(18, 1)), sg.ReadButton('Clear') ], [sg.Exit(key='Exit')]] window = sg.Window('Log In/Out', auto_size_buttons=False, return_keyboard_events=True).Layout(layout) while True: button, values = window.Read() if button == 'Exit' or values is None: break elif button == 'Clear': element = window.FindElement('input_box') element.Update('') elif button == 'Submit' or ord(str(button)) == 13: phone_number = values['input_box'] try: int(phone_number) if int(phone_number) > 9999: sg.Popup('Enter last four of your phone number.') elif len(phone_number) < 4: sg.Popup('Enter last four of your phone number.') else: failed = fetch_user(phone_number) if failed: sg.Popup('Invalid phone number.') element = window.FindElement('input_box') element.Update('') except: sg.Popup('Number values only.') element = window.FindElement('input_box') element.Update('')
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)
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 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 addClient(): layout = [ [sg.Text('Please enter the IP address and email')], [sg.Text('IP Address:', size=(15, 1)), sg.InputText('', key='_IP_')], [sg.Text('Email:', size=(15, 1)), sg.InputText('', key='_EMAIL_')], [sg.Submit(), sg.Cancel()] ] window = sg.Window('Add Account', layout) event, values = window.Read() window.Close() if (sg.PopupYesNo("Are you sure?") == "Yes"): return values else: pass
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)
def getEvent(): # variables database = '/Users/DavidBailey/db/pythonsqlite.db' table = "events_pt" value = 'urban' # connect to sqlite conn = sqlite3.connect(database) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, database) with sqlite3.connect(db_path) as db: # gui layout sg.SetOptions( button_color=sg.COLOR_SYSTEM_DEFAULT , text_color=sg.COLOR_SYSTEM_DEFAULT ) layout = [[sg.Text('Enter text here', size=(40, 1), font=800)], [sg.Text('What type of event?', size=(15, 1), font=800), # values in event column in database sg.InputCombo(('urban', 'outdoors - hike', 'outdoors - no hike', 'outdoors - hard hike', '13er', '14er', 'backpacking'), size=(20, 1))], [sg.Button('Submit')]] window = sg.Window('Digital Bucket').Layout(layout) button, values = window.Read() value = ''.join(values) # select query on database cursor = conn.cursor() cursor.execute("SELECT event FROM %s where complete = 'N' and type = '%s'" % (table, value)) event_list = [] for record in cursor: event_list.append(record) main_value_list = random.choice(event_list) main_value = ''.join(main_value_list) print value print main_value # update query on database cursor.execute("UPDATE %s SET complete = 'Y' where event = '%s' and type = '%s'" % (table, main_value, value)) conn.commit() # show value in gui popup sg.Popup('You are going to....', main_value, font='800', size=(40, 1))
def addAccount(): #add email account to the "Available" section layout = [[sg.Text('Please enter the email address and password')], [ sg.Text('Email Address:', size=(15, 1)), sg.InputText('', key='_EMAIL_') ], [ sg.Text('Password:'******'', key='_PASSWORD_') ], [sg.Submit(), sg.Cancel()]] window = sg.Window('Add Account', layout) event, values = window.Read() window.Close() if (sg.PopupYesNo("Are you sure?") == "Yes"): return values else: pass
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 user_info(json_data): layout = [[ sg.Text(time.asctime(time.localtime(time.time())), font=("Helvetica", 18), justification='center', size=(25, 1)) ], [ sg.Text('Name: ', size=(10, 1), font=("Helvetica", 18)), sg.Text(json_data['name'], font=("Helvetica", 18)) ], [ sg.Text('Number: ', size=(10, 1), font=("Helvetica", 18)), sg.Text(json_data['phone'], font=("Helvetica", 18)) ], [ sg.Text('Is logged in? ', size=(10, 1), font=("Helvetica", 18)), sg.Text(str(json_data['signedIN']), font=("Helvetica", 18)) ], [sg.Button('Log In', key='logger'), sg.Button('Cancel')]] window = sg.Window('User Information').Layout(layout) while True: button, values = window.ReadNonBlocking() if json_data['signedIN']: element = window.FindElement('logger') element.Update(text='Log Out') if button == 'Cancel': return json_data elif button == 'Log In' or values is None: json_data['signedIN'] = True json_data['timeLogs'].append( time.asctime(time.localtime(time.time()))) return json_data elif button == 'Log Out' or values is None: json_data['signedIN'] = False json_data['timeLogs'].append( time.asctime(time.localtime(time.time()))) return json_data
def TestMenus(): import PySimpleGUI as sg sg.ChangeLookAndFeel('LightGreen') sg.SetOptions(element_padding=(0, 0)) # ------ Menu Definition ------ # menu_def = [ ['File', ['Open', 'Save', 'Properties']], [ 'Edit', ['Paste', [ 'Special', 'Normal', ], 'Undo'], ], ['Help', 'About...'], ] # ------ GUI Defintion ------ # layout = [[sg.Menu(menu_def, tearoff=True)], [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...': sg.Popup('About this program', 'Version 1.0', 'PySimpleGUI rocks...') elif button == 'Open': filename = sg.PopupGetFile('file to open', no_window=True) print(filename) elif button == 'Properties': SecondForm()
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 parseWindow( window): #parses all buttons,checkboxes, etc. for the selected window event, values = window.Read() event, values = window.Read() if event is None or event == "Exit": return 0 elif event == "Open Config": fileName = openFileBox() os.system("gnome-terminal -e nano " + fileName) return 1 elif event == "Add Account": addAccount() return 1 elif event == "Add Client": addClient() return 1 elif event == "Add Module": addModule() return 1 elif event == "About": help = open(currentDir + "/../../README.md", "r").read() sg.PopupScrolled(help) return 1 else: print event, values if event == "Execute": if values[1] == "Checkup": fullCheckup() return 1 elif values[1] == "Single Account Checkup": layoutSingleAccountCheckup = [[ sg.Listbox(values=(accounts.values()), size=(50, 20)) ], [sg.Button("OK")]] windowSingleAccountCheckup = sg.Window("Check on which account?", layoutSingleAccountCheckup) eventSC, valuesSC = windowSingleAccountCheckup.Read() #print valuesSC #print valuesSC[0][0][0] #print valuesSC[0][0][1] singleAccount(valuesSC[0][0][0], valuesSC[0][0][1]) else: print(event, values) return 1