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 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)
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 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 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 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 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 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 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 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 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 __init__(self, title=__title__): sg.ChangeLookAndFeel("Reddit") self.layout = [] self.transition = None self.title = title self.window = None self.close = None self.events = []
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 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 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
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 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 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 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 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 ****')
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()
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)
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 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 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 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 __init__(self, title=__title__): super(WStarting, self).__init__(title) self.seconds = 24 self.paused = False self.layout = [[ sg.Frame(title="Additional options:", layout=[[ sg.Button(button_text="Watch Live", key="watch_live", size=(10, 1), font=("wingdings", 14)), sg.Button(button_text="Load File", key="load_file", size=(10, 1), font=("wingdings", 14)), ]], size=(25, 3), relief=sg.RELIEF_SUNKEN) ], [ sg.Button(button_text="Start Component", key="start_component", size=(16, 1), font=("wingdings", 14)) ], [ sg.Text("The component will start automatically", auto_size_text=True, justification="left") ], [ sg.ProgressBar(max_value=self.seconds, key="countdown", orientation="h", size=(20, 20)) ], [ sg.Button(button_text="Exit", key="Exit", size=(10, 1), font=("verdana", 14)), ]] self.window = None self.progress_bar = None
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()