'Pyplot Scatter With Legend': PyplotScatterWithLegend, 'Artist Customized Box Plots': PyplotArtistBoxPlots, 'Artist Customized Box Plots 2': ArtistBoxplot2, 'Pyplot Histogram': PyplotHistogram } sg.theme('LightGreen') figure_w, figure_h = 650, 650 # define the form layout listbox_values = list(fig_dict) col_listbox = [[ sg.Listbox(values=listbox_values, change_submits=True, size=(28, len(listbox_values)), key='-LISTBOX-') ], [sg.Text(' ' * 12), sg.Exit(size=(5, 2))]] col_multiline = sg.Col([[sg.MLine(size=(70, 35), key='-MULTILINE-')]]) col_canvas = sg.Col([[sg.Canvas(size=(figure_w, figure_h), key='-CANVAS-')]]) col_instructions = sg.Col([ [sg.Pane([col_canvas, col_multiline], size=(800, 600))], [ sg.Text( 'Grab square above and slide upwards to view source code for graph' ) ] ]) layout = [ [sg.Text('Matplotlib Plot Test', font=('ANY 18'))], [sg.Col(col_listbox), col_instructions],
except Exception: delta = DELTA delta = int(value) if isinteger else delta isvalid = MIN_DELTA <= delta <= MAX_DELTA delta = delta if isvalid else DELTA return delta, isinteger and isvalid LAYOUT = [[sg.Image(key='-IMAGE-')], [ sg.Checkbox('Correct aspect ratio', key='-RESIZE-', enable_events=True), sg.Button('Reload', key='-RELOAD-'), sg.Button('Save', key='-SAVE-'), sg.Exit() ], [ sg.Checkbox('Auto-reload every (seconds):', key='-AUTORELOAD-', default=True), sg.Input(DELTA, key='-DELTA-', size=(3, 1), justification='right'), sg.Button('Set', key='-UPDATE_DELTA-') ]] def main(layout): """Run event loop."""
def make_window(self, caption, gui_left_upper, gui_right_upper=None, bounce=True, fps=None): """ Create the window, including sg.Graph, the drawing surface. """ # --------------------- PySimpleGUI window layout and creation -------------------- bounce_checkbox_line = '' if bounce is not None: bounce_checkbox_line = [ sg.Checkbox( 'Bounce?', key='Bounce?', default=bounce, tooltip='Bounce back from the edges of the screen?') ] fps_combo_line = '' if fps: fps_combo_line = [ sg.Text('Frames/second', tooltip='The maximum frames/second.', pad=((0, 10), (10, 0))), sg.Combo(key='fps', values=FPS_VALUES, background_color='limegreen', default_value=fps, tooltip='The maximum frames/second.', pad=((0, 0), (10, 0))) ] setup_go_line = [ sg.Button(self.SETUP, pad=((0, 10), (10, 0))), sg.Button(self.GO_ONCE, disabled=True, button_color=('white', 'green'), pad=((0, 10), (10, 0))), sg.Button(self.GO, disabled=True, button_color=('white', 'green'), pad=((0, 30), (10, 0)), key=self.GOSTOP) ] exit_button_line = [ sg.Exit(button_color=('white', 'firebrick4'), key=self.EXIT, pad=((70, 0), (10, 0))) ] col1 = [ *gui_left_upper, gui.HOR_SEP(), setup_go_line, bounce_checkbox_line, fps_combo_line, gui.HOR_SEP(), exit_button_line ] lower_left_pixel_xy = (0, self.screen_shape_width_height[1] - 1) upper_right_pixel_xy = (self.screen_shape_width_height[0] - 1, 0) if gui_right_upper is None: gui_right_upper = [[]] # graph is a drawing area, a screen on which the model is portrayed, i.e., the patches and the agents. # It consists mainly of a TKCanvas. graph = sg.Graph(self.screen_shape_width_height, lower_left_pixel_xy, upper_right_pixel_xy, background_color='black', key='-GRAPH-', enable_events=True) col2 = gui_right_upper + [[graph]] # layout is the actual layout of the window. The stuff above organizes it into component parts. # col1 is the control buttons, sliders, etc. # col2 is the graph plus whatever the user wasnts to put above it. # layout is a single "GUI line" with these two components in sequence. layout = [[sg.Column(col1), sg.Column(col2)]] # window is a window with that layout. window = sg.Window(caption, layout, margins=(5, 20), use_default_focus=False, grab_anywhere=True, return_keyboard_events=True, finalize=True) # -------------- Magic code to integrate PyGame with tkinter ------- w_id = graph.TKCanvas.winfo_id() os.environ['SDL_WINDOWID'] = str(w_id) os.environ[ 'SDL_VIDEODRIVER'] = 'windib' # change this to 'x11' to make it work on Linux return window
addsitedir(sitepkg) gui = [[ sg.Text('Input GDB', size=(20, 1)), sg.InputText(size=(70, 1)), sg.FolderBrowse() ], [ sg.Text('BOM Output Location:', size=(20, 1)), sg.InputText(size=(70, 1)), sg.FolderBrowse() ], [ sg.Text('OLT(s) Comma Separated:', size=(20, 1)), sg.InputText(size=(70, 1)) ], [sg.Submit(), sg.Exit()]] window = sg.Window('Clarity BOM (Simplified)').Layout(gui) # check if scratch.gdb exists on users machine, if not make one. scratchExists = os.path.exists( os.path.join(r'C:\Users', getpass.getuser(), 'Documents', 'ArcGIS', 'scratch.gdb')) if scratchExists == False: arcpy.CreateFileGDB_management( os.path.join(r'C:\Users', getpass.getuser(), 'Documents', 'ArcGIS'), 'scratch.gdb') else: pass scratch = os.path.join(r'C:\Users', getpass.getuser(), 'Documents', 'ArcGIS', 'scratch.gdb')
3. At the top of your app's Event Loop add: imwatchingyou.refresh(locals(), globals()) """ layout = [ [sg.T('A typical PSG application')], [sg.In(key='_IN_')], [sg.T(' ', key='_OUT_')], [ sg.Radio('a', 1, key='_R1_'), sg.Radio('b', 1, key='_R2_'), sg.Radio('c', 1, key='_R3_') ], [sg.Combo(['c1', 'c2', 'c3'], size=(6, 3), key='_COMBO_')], [sg.Output(size=(50, 6))], [sg.Ok(), sg.Exit(), sg.B('Debug')], ] window = sg.Window('This is your Application Window', layout) counter = 0 timeout = 100 debug_started = False while True: # Your Event Loop if debug_started: debug_started = imwatchingyou.refresh( locals(), globals()) # STEP 3 - refresh debugger event, values = window.Read(timeout=timeout) if event in (None, 'Exit'): break
def main(): args = arg_parse() VIDEO_PATH = args['video'] if not args['webcam'] else 0 resolution_list = [320, 416, 512] index = [args['small_resol'], args['best_resol'], args['large_resol']].index(True) inp_dim = resolution_list[index] device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("Loading network.....") model = Darknet(args['cfg_path'], img_size=inp_dim).to(device) model.load_darknet_weights(args['weight_path']) print("Network successfully loaded") model.eval() # load detection class, default confidence threshold is 0.5 detect = DetectBoxes(args['label_path'], args['class_list'], conf_threshold=args['confidence'], nms_threshold=args['nms_threshold']) try: # Read Video file cap = cv2.VideoCapture(VIDEO_PATH) except IOError: print("Input video file", VIDEO_PATH, "doesn't exist") sys.exit(1) win_started = False while cap.isOpened(): hasFrame, frame = cap.read() if not hasFrame: break start = time.time() detect.bounding_box_yolo(frame, inp_dim, model) imgbytes = cv2.imencode('.png', frame)[1].tobytes() # ditto if not win_started: win_started = True layout = [[sg.Text('Pytorch YOLO Video', size=(30, 1))], [sg.Image(data=imgbytes, key='_IMAGE_')], [ sg.Text('Confidence'), sg.Slider(range=(0, 1), orientation='h', resolution=.1, default_value=.5, size=(15, 15), key='confidence'), sg.Text('NMSThreshold'), sg.Slider(range=(0, 1), orientation='h', resolution=.1, default_value=.4, size=(15, 15), key='nms') ], [sg.Exit()]] win = sg.Window('YOLO Output', default_element_size=(14, 1), text_justification='right', auto_size_text=False).Layout(layout).Finalize() image_elem = win.FindElement('_IMAGE_') else: image_elem.Update(data=imgbytes) event, values = win.Read(timeout=0) if event is None or event == 'Exit': break end = time.time() print("FPS {:5.2f}".format(1 / (end - start))) detect.update_threshold(values['confidence'], values['nms']) if cv2.waitKey(1) & 0xFF == ord('q'): break win.Close() print("Video ended") # releases video and removes all windows generated by the program cap.release()
default_value='', size=(20, 6)), sg.Text('业务子:', size=(15, 1)), sg.InputCombo(['Y', 'N'], key='business_subinv_active_flag', default_value='', size=(20, 6)), sg.Text('核算子: ', size=(18, 1)), sg.InputCombo(['Y', 'N'], key='active_flag', default_value='', size=(20, 6)), ], [ sg.Button('修改', key='update_flag', size=(15, 1)), sg.Exit(button_text='退出', key='Exit', size=(15, 1)) ] ] #窗口实例化 并设置窗口名,把内容放进去 window = sg.Window('子库属性更改', layout, auto_size_text=True) #主题循环 while True: #读取按键和各个插件的值 window.read()窗口显示 #event获取按键值 #values[‘控件的KEY’] event, values = window.read() print(event, values) if event in (None, 'Exit'):
import PySimpleGUI as sg import random, pyperclip from datetime import datetime global time layout = [[sg.Text('Dice Roller')], [sg.Spin([i for i in range(1,11)], key='many'), sg.T('Dices will be rolled')], [sg.T('This will choose from 1-6\nClick here to roll\n\\/')], [sg.Button('ROLL'), sg.Exit('EXIT')], [sg.T('', size=(25,1),key='random')], [sg.Button('COPY SEED')]] window = sg.Window('Dice Roll', layout, margins=(30,30)) while True: now = datetime.now() time = now.strftime('%m%D%h%Y%H%M%S%M').replace('/', '') event, values = window.read(timeout=500) if event in ('EXIT', sg.WIN_CLOSED): break if event == 'ROLL': random.seed(time) images = [] total = 0 try: if int(values['many']) <= 10: for i in range(int(values['many'])): num = str(random.randint(1, 6)) images.append(sg.Image(f'diceassets/{num}.png')) total = total+int(num) layout2 = [images, [sg.T(f'Total value : {total}')], [sg.Button('OK')], [sg.T(f'Seed used : {time}'), sg.Button('COPY')]] window2 = sg.Window('DICE', layout2, margins=(10,10)) while True: event2, values2 = window2.read()
n.createTable() n.createUsers() lis, completed = [], [] llayout = [ #login layout [s.Text("LOGIN", pad=((200, 100), (0, 0)))], [s.Text('Username : '******'', key='lusername')], [ s.Text('Password : '******'', key='lpassword', password_char='*') ], [ s.Button('Login', pad=((100, 10), (0, 0))), s.Text('Not a member?'), s.Button('Sign up') ], [s.Exit()], [s.Text("", auto_size_text=False, key="tell")] ] slayout = [ #sign up layout s- sign up [s.Text("SIGN UP", pad=((200, 100), (0, 0)))], [s.Text("NAME : "), s.InputText('', key='sname', do_not_clear=False)], [s.Text('E-mail : '), s.InputText('', key='semail', do_not_clear=False)], [ s.Text('Username : '******'', key='susername', do_not_clear=False) ], [ s.Text('Password : '******'', key='spassword', password_char='*', do_not_clear=False) ], [s.Button('Sign up'), s.Button('Back'),
def main(): #Layout of lower frame of main window details_frame = [[ FieldColumn("Sport: ", '-SPORT-'), FieldColumn("Date: ", '-DATE-'), FieldColumn("Time: ", '-STARTTIME-'), FieldColumn("Duration: ", '-DURATION-'), FieldColumn("Distance: ", '-DISTANCE-') ], [ FieldColumn("Pace: ", '-PACE-'), FieldColumn("Ascent: ", '-ASC-'), FieldColumn("Descent: ", '-DESC-') ], [ sg.Frame('Note', [[sg.Text(key='-NOTE-', size=(180, 6))]]) ]] #List of labels for main table tabl_head = [ 'Date', 'Time', 'Type', 'Distance', 'Duration', 'Pace', 'Photos', 'Note', 'Comments' ] #Fill data for main table (needed as placeholder to define size for initial layout) data = [[ ' ' * 15, ' ' * 15, ' ' * 15, ' ' * 10, ' ' * 10, ' ' * 10, ' ' * 10, ' ' * 45, ' ' * 10 ] for row in range(16)] #Main window layout layout = [[ sg.FolderBrowse(target='-FOLDER-'), sg.Input(key='-FOLDER-', enable_events=True), sg.Submit(), sg.Button('Fetch Comments', key='-FETCH-'), sg.Exit() ], [ sg.Table(data, headings=tabl_head, justification='center', select_mode='browse', key='-DATA-', num_rows=30, enable_events=True, bind_return_key=True, max_col_width=100) ], [sg.Column(details_frame, expand_y=True, expand_x=True)]] window = sg.Window('EndoView', layout, size=(1320, 670), finalize=True) window['-DATA-'].bind('<Double-Button-1>', '+DBL+') window['-DATA-'].bind('<Return>', '+ENTER+') config = configparser.ConfigParser() config.read('endoview.ini') dd = {} max_workouts = 0 try: if 'cache' in config['endoview']: folder_path = config['endoview']['BackupFolder'] window['-FOLDER-'].update(folder_path) with open('cache.pkl', 'rb') as f: dd = pickle.load(f) max_workouts = len(dd) with open('index.pkl', 'rb') as f: indx = pickle.load(f) updatetable(data, dd, window) except: pass while True: # Event Loop of main window event, values = window.read(timeout=100) #trap for strange exception if event == sg.TIMEOUT_KEY: continue #print(event, values) if event == sg.WIN_CLOSED or event == 'Exit': break elif event == '-FETCH-': #test if endoworkouts.json file is present if os.path.isfile(folder_path + '/endoworkouts.json'): with open(folder_path + '/endoworkouts.json') as p: comm = json.load(p) if comm is not None: updatecomments(dd, comm, indx) with open("cache.pkl", "wb") as write_file: pickle.dump(dd, write_file, pickle.HIGHEST_PROTOCOL) updatetable(data, dd, window) elif event == '-FOLDER-' or (event == 'Submit' and len(values['-FOLDER-']) > 0): folder_path = values['-FOLDER-'] #test if endoworkouts.json file is present # if os.path.isfile(folder_path+'/endoworkouts.json'): # with open(folder_path+'/endoworkouts.json') as p: # dd = json.load(p) # print('Loading endoworkouts.json') # distance_key='distance_km' # duration_key='duration' # speed_avg_key='speed_avg' # else: dd, indx = loadfull(folder_path) max_workouts = len(dd) #print('Loading backup! ') # we have processed database in memory - let's write cache and create config file config = configparser.ConfigParser() config['endoview'] = {} config['endoview'][ 'Cache'] = 'Y' #indicate that we have cached data config['endoview'][ 'BackupFolder'] = folder_path #save location of Endomondo backup with open('endoview.ini', 'w') as configfile: config.write(configfile) #now store cache to file system with open("cache.pkl", "wb") as write_file: pickle.dump(dd, write_file, pickle.HIGHEST_PROTOCOL) with open("index.pkl", "wb") as write_file: pickle.dump(indx, write_file, pickle.HIGHEST_PROTOCOL) updatetable(data, dd, window) elif event == '-DATA-': try: workout = dd[values['-DATA-'][0]] window['-SPORT-'].update(workout.get('sport')) window['-DATE-'].update(workout.get('date')) window['-STARTTIME-'].update(workout.get('time')) window['-DURATION-'].update(workout.get('duration')) window['-DISTANCE-'].update(workout.get('distance')) window['-PACE-'].update(workout.get('pace')) window['-ASC-'].update(workout.get('ascend_m')) window['-DESC-'].update(workout.get('descend_m')) window['-NOTE-'].update(workout.get('message')) except (IndexError, KeyError) as err: print(err) elif event == '-DATA-+DBL+' or event == '-DATA-+ENTER+': try: #in case of double click or ENTER press on specific line - pop up detailed window workout = dd[values['-DATA-'][0]] # selected workout #prepare layout for detailed window #define sizes of the details window TODO: bind to desktop size win2_width = 1100 win2_height = 100 WIN2_HEIGHT_MAX = 700 windetails = [ [ FieldColumn("Sport: ", '-SPORT-', workout.get('sport')), FieldColumn("Date: ", '-DATE-', workout.get('date')), FieldColumn("Time: ", '-STARTTIME-', workout.get('time')), FieldColumn("Duration: ", '-DURATION-', workout.get('duration')), FieldColumn("Distance: ", '-DISTANCE-', workout.get('distance')) ], [ FieldColumn("Pace: ", '-PACE-', workout.get('pace')), FieldColumn("Ascent: ", '-ASC-', workout.get('ascend_m')), FieldColumn("Descent: ", '-DESC-', workout.get('descend_m')), FieldColumn("Alt min: ", '-ALTMIN-', workout.get('altitude_min_m')), FieldColumn("Alt max: ", '-ALTMAX-', workout.get('altitude_max_m')) ], [ FieldColumn("HR AVG: ", '-HAVG-', workout.get('heart_rate_avg_bpm')), FieldColumn("HR MAX: ", '-HMAX-', workout.get('heart_rate_max_bpm')), FieldColumn("Calories: ", '-CAL-', workout.get('calories_kcal')), FieldColumn("Cad AVG: ", '-CADAVG-', workout.get('cadence_avg_rpm')), FieldColumn("Cad MAX: ", '-CADMAX-', workout.get('cadence_max_rpm')) ], [ FieldColumn("Speed AVG: ", '-SPAVG-', workout.get('speed')), FieldColumn("Speed MAX: ", '-SPMAX-', workout.get('speed_max')), ] ] msg = workout.get('message') lennote = 0 if msg is None else len( msg) #find out length of text note if lennote > 0: # if there is note in workout - add text field and fill it with note #nlines = msg.count('\n')+1 lines = msg.split("\n") nlines = 0 for oneline in lines: nlines += int( len(oneline) / 165 ) + 1 # text breaks at about 165 chars in average nheight = int(lennote / 150) + 1 if nlines < nheight: nlines = nheight windetails += [[ sg.Frame('Note', [[ sg.Text(msg, key='-NOTE-', size=(int(win2_width / 8), nlines)) ]]) ]] win2_height += nlines * 8 + 50 #extend height of the window #check if there are pictures posted to the workout and add layout to the window pict = workout.get('pictures') if pict is not None: linewidth = 0 imgline = [] for i in range(0, len(pict)): # try: try: url = pict[i][1].get('picture')[0][0].get('url') data, (imgwidth, imgheight) = get_img_data( folder_path + '/' + url, first=True) except KeyError: url = pict[i].get('picture_file') data, (imgwidth, imgheight) = get_img_data( os.path.join(folder_path, 'Images', os.path.split(url)[1]), first=True) if linewidth + imgwidth > win2_width: windetails += [imgline] win2_height += imgheight + 50 imgline = [] linewidth = 0 imgline.append( sg.Image(key='-IMAGE' + str(i) + '-', data=data)) linewidth += imgwidth if imgline != []: windetails += [imgline] win2_height += imgheight + 50 # except Exception as err: # print("Images exception: ", err) # break #create comments section comm_num = workout.get('num_comments') if comm_num != '': try: comment = workout.get('ecomments').get('data') except AttributeError: comment = workout.get('comments').get('data') for i in range(len(comment)): comtext = comment[i]['text'] lines = comtext.split("\n") nlines = 0 for oneline in lines: nlines += int( len(oneline) / 100 ) + 1 # text breaks at about 165 chars in average #comh = int(len(comtext)/100)+1 #height of the comment cell to fit the comment comh = nlines frame_layout = [[ sg.Text(emoji.get_emoji_regexp().sub( r'', comment[i]['from']['name']) + ':', size=(20, comh)), sg.Text(emoji.get_emoji_regexp().sub(r'', comtext), size=(100, comh), pad=(0, 0)) ]] windetails += frame_layout win2_height += 28 #TODO: add height depending on comment height win2_height = WIN2_HEIGHT_MAX if win2_height > WIN2_HEIGHT_MAX else win2_height win2layout = [[ sg.Column(windetails, scrollable=True, vertical_scroll_only=True, size=(win2_width, win2_height)) ]] win2 = sg.Window('Workout detail', win2layout, finalize=True, modal=True) win2.bind('<Escape>', '+ESC+') win2.bind('<Return>', '+ENTER+') while True: # Event Loop ev2, val2 = win2.read(timeout=100) #timeout for debugger if ev2 == sg.TIMEOUT_KEY: continue if ev2 == sg.WIN_CLOSED or ev2 == '+ESC+' or ev2 == '+ENTER+': break win2.close() del win2layout del win2 del windetails except (IndexError, KeyError) as err: print(err) pass window.close()
import PySimpleGUI as sg def todoitem(num): return [sg.T(f'{num}. '), sg.CBox(''), sg.In()] layout = [todoitem(i) for i in range(1, 10)] + [[sg.Save(), sg.Exit()]] window = sg.Window('To Do List', layout) event, values = window.read()
def initload(): layout = [[ sg.Text('Stay', font=(None, 20)), sg.Text('Hydrated', font=(None, 20)) ], [sg.Button("Login"), sg.Button("Log-In")], [sg.Button("Sign Up"), sg.Button("Register")], [sg.Exit(), sg.Button("About")]] terms_agreements = 'You, the User, agree to the following terms and agreements:\n\n' \ ' 1. Users on other parts of the network are allowed to terrorize you. ' \ 'This includes but not limited to:\n\n' \ ' - Acts of destruction upon your computer (e.g. forced shutdowns, copying of files, ' \ 'deletion of files, opening of malware/McAfee/Norton, opening ransomware, etc.)\n' \ ' - Acts of terrorism (e.g. 100s of notifications offloading on your computer, using up ' \ 'all available RAM/memory, and killing your GPU because... why not?)\n' \ ' 2. The Stay Hydrated Team is not responsible for damage to your computer. All code is open' \ 'source and you should make sure to review the code for safety. Ths Stay Hydrated Team is NOT ' \ 'legally bound to any destruction and is not legally responsible for any action that happens\n' \ ' 3. You agree not to use our application for malicious purposes against users on a different' \ ' network. You agree to only use this application to target users within your dedicated server' \ ' or the dedicated server that someone else in your network has set up.\n' \ ' 4. You agree to only write Python code to damage others within your own network. You also' \ ' agree that you allow others to target your computer, as well.' \ '\n\nYou have been warned.\n\n~Stay Hydrated Team\n\nApache 2.0 License can be found on ' \ 'apache.org' privacy_policy = r'We do not actually collect any of your data. Your data stays within your home or workplace ' \ r"or server or WiFi network. It's practically useless for this application. However, it brings" \ r" me GREAT joy that you are actually reading legal parts! It really does cut down on time when " \ r"it comes to these registration forms; am I right? If you've gotten all the way down here, then" \ r" congrats! You don't actually have to fill in anything except for the username and password " \ "and password confirmation fields! I hope you have a wonderful day and a terrific experience " \ "with the Stay Hydrated Client\n\n~ Stay Hydrated Team" about_text = 'About Stay Hydrated\n\n' \ 'Developed by blitzcraft, kyouma, Stoffel, and Yoom/YoomamaFTW, Stay Hydrated is a project developed' \ ' for the r/ProgrammerHumor hackathon with the theme of over-engineering.\n' \ "We want you to be able to stay healthy while using your computer! So there are great default check" \ "-ups that your employer or parent can deploy. For example, are your eyes far away from the screen?" \ "Have you taken a break from the screen? How much water have you drunk? Did you do your daily " \ "calisthenics? Most of these are already installed, but what's the point of checku-ups if there're " \ "no punishments?\n\n" \ "We got you covered! We will make sure there are effective punishments in place, " \ "such as forcefully shutting down a computer, opening 100 tabs full of cat videos, turn up your " \ "volume to 100%, and even call your mother telling her how fun you're having with this program. " \ "Additionally, other users within this network can join in on the punishing fun! They can program, in" \ " Python, some great punishments using the os module.\n\n" \ "The setup of this project is simple -- sorta simple: a server is setup on someone's computer, or" \ " a Raspberry Pi (hint hint), and the users download the client. The client will check on you with" \ "default health check-ups and custom inspections designed by fellow users. If a user fails his/her " \ "check-up, then other users are able to terrorize the failing user through tons of notifications, " \ 'custom trolls, and custom "terrorist" attacks, which other users can create using Python. The ' \ 'notifications can also be custom made by other users. All users must be connected to the same WiFi.' landing = sg.Window('Stay Hydrated', layout=layout, resizable=True) landing_active = True register_active = False login_active = False while True: ev1, val1 = landing.Read() if ev1 is None or ev1 == 'Exit': break elif ev1 == 'About': sg.PopupScrolled(about_text, title="Stay Hydrated | About") elif ev1 == 'Login' or ev1 == "Log-In": if not login_active and landing_active and not register_active: landing.Hide() login_active = True layout_login = [ [sg.Text("Login", font=(None, 20))], [sg.Text("Username"), sg.InputText(key='Username')], [ sg.Text("Password"), sg.InputText("", password_char="*", key='Password') ], [ sg.Submit(), sg.Exit( tooltip= 'Click to exit the login window. No data will be saved' ) ] ] win_login = sg.Window(title="Stay Hydrated | Login", layout=layout_login) while True: ev2, val2 = win_login.Read() if ev2 is None or ev2 == 'Exit': win_login.Close() login_active = False register_active = False landing_active = True landing.UnHide() break elif ev1 == 'Sign Up' or ev1 == 'Register': if not register_active and not login_active and landing_active: landing.Hide() register_active = True win_register = sg.Window("Stay Hydrated | Register", resizable=True) \ .Layout([[sg.Column(layout=signup(), scrollable=True)]]) while True: ev3, val3 = win_register.Read() if ev3 is None or ev3 == 'Exit' or ev3 == 'Cancel': win_register.Close() register_active = False login_active = False landing_active = True landing.UnHide() break elif ev3 == 'Submit': if val3['Agreements']: if val3['Username'] is not None: if val3["Address"] is not None: # send dummy request that returns "Valid" if val3['Password'] is not None: if val3['Confirm'] is not None: if val3['Password'] == val3[ 'Confirm']: # send request using the requests package pass else: sg.Popup( "Your passwords did not match. Reconfirm it." ) else: sg.Popup( "Please confirm your password." ) else: sg.Popup( "You need to fill out the password field." ) else: sg.Popup( "You need to fill out the address to the server. It probably looks " "like this: 192.168.0.11") else: sg.Popup( "Please provide a username. Make it count." ) else: sg.Popup( "You must agree to the Terms and Agreements and Privacy Policy by marking the box" " with a check-mark first.") elif ev3 == 'Terms and Agreements': sg.PopupScrolled(terms_agreements, title="Terms and Agreements") elif ev3 == 'Privacy Policy': sg.PopupScrolled(privacy_policy, title="Privacy Policy") landing.Close()
def uncompress_files(opmoptn): """Uncompress All Jobs that Have Been Compressed in a Zip File Using the Base Name The function allows the use to select a group of ZIP files for unzipping of all files associated with the case name (*.DATA), using the standard unzip utility on Linux systems Parameters ---------- opmoptn; dict A dictionary containing the OPMRUN default parameters Returns ------ None """ if sg.running_windows(): wsl = 'wsl ' else: wsl = '' joblist1 = [] outlog = '_outlog1_' + sg.WRITE_ONLY_KEY layout1 = [ [sg.Text('Select Multiple Archive Files to Uncompress')], [ sg.Listbox(values='', size=(100, 10), key='_joblist1_', font=(opmoptn['output-font'], opmoptn['output-font-size'])) ], [sg.Text('Output')], [ sg.Multiline(key=outlog, size=(100, 15), text_color='blue', autoscroll=True, font=(opmoptn['output-font'], opmoptn['output-font-size'])) ], [sg.Text('Uncompress Options')], [ sg.Radio('Uncompress and Keep Existing Files', "bRadio1", default=True, key='_bRadio1_') ], [sg.Radio('Uncompress and Overwrite Existing Files', "bRadio1")], [sg.Text('Compressed File Options')], [ sg.Radio('Keep Compressed File After Uncompressing', "bRadio2", default=True, key='_bRadio2_') ], [sg.Radio('Delete Compressed File After Uncompressing', "bRadio2")], [ sg.Button('Add'), sg.Button('Clear', tooltip='Clear Output'), sg.Button('List'), sg.Button('Remove', tooltip='Remove Zip Files'), sg.Submit(), sg.Exit() ] ] window1 = sg.Window('Uncompress Job Files', layout=layout1, finalize=True) # # Set Output Multiline Window for CPRINT and Check If ZIP Package is Available # sg.cprint_set_output_destination(window1, outlog) compress_chk('unzip', window1) # # Define GUI Event Loop, Read Buttons, and Make Callbacks etc. Section # while True: (event, values) = window1.read() if event == sg.WIN_CLOSED: break if event == 'Add': jobs = sg.popup_get_file('Select ZIP Files to Uncompress', no_window=False, default_path=str(Path().absolute()), initial_folder=str(Path().absolute()), multiple_files=True, file_types=[('zip', ['*.zip', '*.ZIP'])]) if jobs is not None: jobs = jobs.split(';') for job in jobs: joblist1.append(job) window1['_joblist1_'].update(joblist1) continue # # Clear Output # if event == 'Clear': window1[outlog].update('') continue # # Exit # elif event == 'Exit': text = sg.popup_yes_no('Exit Uncompress Utility?', no_titlebar=False, grab_anywhere=False, keep_on_top=False) if text == 'Yes': break else: continue # # Get Directory and List Files # if event == 'List': jobpath = sg.popup_get_folder('Select Directory', no_window=False, default_path=str(Path().absolute()), initial_folder=str( Path().absolute())) if jobpath is not None: error = change_directory(jobpath, popup=True, outprt=True) if not error: jobpath = Path().absolute() for file in Path(jobpath).glob("*.zip"): sg.cprint(str(Path(file).name)) for file in Path(jobpath).glob('*.ZIP'): sg.cprint(str(Path(file).name)) sg.cprint('Listing Complete ' + str(jobpath)) continue # # Remove Files # if event == 'Remove': joblist1 = [] window1['_joblist1_'].update(joblist1) continue # # Uncompress Files # if event == 'Submit': if values['_bRadio1_']: zipcmd = 'unzip -u -n ' else: zipcmd = 'unzip -u -o ' jobnum = -1 for cmd in joblist1: jobnum = jobnum + 1 window1['_joblist1_'].update(set_to_index=jobnum, scroll_to_index=jobnum) sg.cprint('Start Uncompression') (job, jobcmd, jobpath, jobbase, jobroot, jobfile, jobzip) = compress_cmd(cmd) error = change_directory(jobpath, popup=True, outprt=True) if not error: jobcmd = wsl + zipcmd + str(jobzip) sg.cprint(' ' + jobcmd) sg.cprint(str(jobpath)) run_command(jobcmd, timeout=None, window=window1) if not values['_bRadio2_']: jobcmd = wsl + 'rm -v ' + str(jobzip) sg.cprint(' ' + jobcmd) run_command(jobcmd, timeout=None, window=window1) sg.cprint('End Uncompressing') window1.refresh() window1['_joblist1_'].update(joblist1) continue window1.Close() return () # ====================================================================================================================== # End of OPM_COMMON.PY # ======================================================================================================================
usecols=['id'])['id'].values.tolist() sg.ChangeLookAndFeel('Black') homeLayout = [[ sg.Listbox(values=(groups), size=(15, 15), font=("Helvetica", 20), key='__groupname__'), sg.Listbox(values=(problems), size=(15, 15), font=("Helvetica", 20), key='__problemNumber__') ], [ sg.Exit(button_color=('white', 'purple')), sg.RButton('Accept!', button_color=('white', 'green'), size=(25, 1)), sg.RButton('Reject!', button_color=('white', 'red'), size=(25, 1)) ]] def solved(groupName, tag): if groupName not in groups: return 'Wrong group name!' if tag not in problems: return 'This problem dosen\'t exist'
import PySimpleGUI as sg # sg.preview_all_look_and_feel_themes() layout = [[sg.Text("Enter text here"), sg.InputText(key='-IN-')], [sg.Text("Your ouput goes here", key='-OUT-', size=(30, 1))], [sg.OK(), sg.Exit()]] # ,[sg.Button("NAMASET !!!")]])#, no_titlebar=True) window = sg.Window(title="HELLO APP", layout=layout, no_titlebar=True) while True: event, values = window.read() print(values) if event == sg.WIN_CLOSED or event == 'Exit': break window['-OUT-'].update(values['-IN-']) window['-IN-'].update("") window.close()
size=(1, 1)) ], [ sg.InputCombo(('heaviside', 'sigmoid', 'sin', 'cos', 'tanh', 'sign', 'ReLu', 'leaky ReLu'), default_value='heaviside', size=(10, 1), key='activation') ], [ sg.Spin([i for i in range(10, 100000, 10)], initial_value=1000, key='epochs', size=(5, 1)) ], [sg.In(default_text='0.01', key='learningRate', size=(4, 1))], [sg.Exit(size=(8, 1))]] layout = [[sg.Canvas(size=(1, 1), key='canvas')], [sg.Column(column1), sg.Column(column2)]] # Create the Window window = sg.Window('Single neuron', layout).Finalize() # Event Loop to process "events" and get the "values" of the inputs while True: event, values = window.read() if event in (None, 'Exit'): # if user closes window or clicks cancel print('Close') plt.close('all') break
break elif event == 'Reverse!': modificoJugador(jugador, event) reversegam.main() window.Close() break #-------------------------------------------------------- #P.P #Definimos la ventana layout = [[sg.Text("Nickname: "), sg.Input(key='_nombre_')], [sg.Button('Elegir juego: '), sg.Exit()]] window = sg.Window('ENTRADA DE DATOS').Layout(layout).Finalize() #Defino main def jugar(): while True: event, values = window.Read() if event is None or event == 'Exit': break elif (event == 'Elegir juego: '): if faltaCompletar(values): sg.Popup('Falta completar algun campo')
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), size=(9, 1)), sg.Spin([x + 1 for x in range(10)], 1, key='spin') ], ] window = sg.Window('CPU Utilization', no_titlebar=True, 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 -------- event, values = window.ReadNonBlocking() # --------- Do Button Operations -------- if values is None or event == '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()
sg.InputText(key='_torrentFolder_'), sg.FolderBrowse() ], [sg.Text('2) 指定音乐文件夹', font=("Microsoft YaHei", 16))], [ sg.InputCombo(('单种模式', '批量模式'), size=(20, 1), key='_singleOrBash_', font=("Microsoft YaHei", 10)), sg.InputText(key='_musicFolder_'), sg.FolderBrowse() ], [sg.Text('单种模式:请指定直接包含音乐文件的目录。', font=("Microsoft YaHei", 10))], [sg.Text('批量模式:请指定直接包含音乐文件目录的上层目录。', font=("Microsoft YaHei", 10))], [sg.Text('_' * 80)], [ sg.Submit(button_text='运行', key='_goGo_'), sg.Exit(button_text='退出', key='_exit_') ] ] window = sg.Window('Gazelle -> Gazelle (5.0)', layout, default_element_size=(40, 1), grab_anywhere=False, icon="favicon2.ico") event, values = window.Read() while True: event, values = window.Read() callMovePy = '' if event == '_goGo_':
[sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1))], [sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1))], [sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1))], [sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1))], [sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1))], [sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1))] ] layout = [[sg.Column(col1), sg.Column(col2), sg.Column(col3)], [sg.Submit(), sg.Exit()]] window = sg.Window('Update Selected Absorbers', layout, font=("Helvetica", 12)) while True: event, values = window.read() #update database for i in range(0, 10): df.at[i, 'zabs'] = values[i] df.at[i, 'List'] = values[i + 10] df.at[i, 'color'] = values[i + 20] print(values) # the input data looks like a simple list when auto numbered print(df) if event == sg.WIN_CLOSED or event == 'Exit': break window.close()
# '--''--''--''--''--''--''--''--''--' BAR_WIDTH = 50 BAR_SPACING = 75 EDGE_OFFSET = 3 GRAPH_SIZE = (500,500) DATA_SIZE = (500,500) sg.theme('Light Brown 1') graph = sg.Graph(GRAPH_SIZE, (0,0), DATA_SIZE) layout = [[sg.Text('Labelled Bar graphs using PySimpleGUI')], [graph], [sg.Button('OK'), sg.T('Click to display more data'), sg.Exit()]] window = sg.Window('Window Title', layout) while True: event, values = window.read() if event in (None, 'Exit'): break graph.erase() for i in range(7): graph_value = random.randint(0, 400) graph.draw_rectangle(top_left=(i * BAR_SPACING + EDGE_OFFSET, graph_value), bottom_right=(i * BAR_SPACING + EDGE_OFFSET + BAR_WIDTH, 0), fill_color='blue') graph.draw_text(text=graph_value, location=(i*BAR_SPACING+EDGE_OFFSET+25, graph_value+10)) window.close()
sg.FileBrowse('Select monthlyNDforecast', size=(50, 1)) ], [ sg.Text('Month: '.ljust(50)), sg.Slider(range=(1, 12), orientation='h', size=(45, 10), default_value=6, key="_months_") ], [ sg.Text('activityToday'.ljust(50)), sg.DropDown(states, size=(40, 1), key="_activityToday_") ], [sg.RButton('Run', size=(100, 1))], [sg.Exit(size=(100, 1))], ] window = sg.Window('Forecast Tool', grab_anywhere=False).Layout(layout).Finalize() window.Resizable = True window.TextJustification = True while True: e, v = window.Read() if e in [None, 'Exit']: break if e in ['Run']: try: print(v)
def blink(): while stopflag == False and runningflag: print('コマンド送信: d2 1') time.sleep(1) print('コマンド送信: d2 0') time.sleep(1) layout = [[sg.Text('IPアドレス'), sg.InputText(size=(15, 1), key='-IPADDRESS-')], [sg.Button('OPEN'), sg.Text('未接続', size=(10, 1), key='-STATUS-')], [sg.Button('LED ON'), sg.Button('LED OFF')], [sg.Button('点滅開始'), sg.Button('点滅終了')], [sg.Exit()]] window = sg.Window('GUI LED DUMMY', layout, auto_size_buttons=False, default_button_element_size=(12, 1)) runningflag = True stopflag = True while True: event, values = window.read() print(event, values) if event in (sg.WIN_CLOSED, 'Exit'): break
global strike_num strike_num = random.randint (1, 10) # ------ Column Definition ------ # col1 = sg.Col([[sg.Text('0', size=(5, 0), auto_size_text=True,justification='center', font=("Helvetica", 60), relief=sg.RELIEF_RAISED, key='Strike_Count',pad=(60,20))]], size=(350,150), pad=(0,0)) col2 = sg.Col([[sg.Text('0', size=(5, 0), justification='center', font=("Helvetica", 60), relief=sg.RELIEF_RIDGE, key='Strike_Num', pad=(60,20))]], size=(350,150), pad=(0,0)) col3 = sg.Col ([ [sg.Text('', pad=(5,5))], [sg.Text('', size=(20, 2), font=('Helvetica', 20),justification='center', key='timer')], ]) layout = [ [sg.Text('Southrac Boxing Machine', size=(150, 1), justification='center', font=("Helvetica", 35), relief=sg.RELIEF_FLAT, key='BoxMachine', pad=(10,20))], [sg.Frame('Total Strikes',[[col1]],title_color='red',title_location='n', font=("Helvetica", 25), pad=(50,30)), sg.Frame('Count Down Meter',[[col2]], title_color='blue',title_location='n', font=("Helvetica", 25), pad=(50,30))], [sg.Button('squats'), sg.Button('Stop'),sg.Exit()], [sg.Frame('Session Timer',[[col3]],title_color='Green',title_location='n', font=("Helvetica", 25), pad=(300,30))], ] window = sg.Window('Southrac Boxing Machine', layout, size = (1024, 800), default_element_size=(40, 1), grab_anywhere=False) random.seed () current_time, paused_time, timer_stopped = 0, 0, True start_time = time_as_int() #Set up the sensor/buttons GPIO.setmode(GPIO.BCM) GPIO.setup(SENSOR_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(SENSOR_GPIO, GPIO.RISING,callback=sensor_pressed_callback, bouncetime=100) GPIO.setmode(GPIO.BCM) GPIO.setup(RESET_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
event, values = window.read(timeout=100) if event != '__TIMEOUT__': print(event, values) if event == sg.WIN_CLOSED or event == 'Exit': break await asyncio.sleep(.1) async def main(): loop = asyncio.get_event_loop() job1 = loop.create_task(task1()) job2 = loop.create_task(task2()) job3 = loop.run_in_executor(None, blocking_task) job4 = loop.create_task(test_gui()) await job1 await job2 await job3 await job4 if __name__ == "__main__": ct = time.time() layout = [[sg.Text('Persistent window')], [sg.Input(key='-IN-')], [sg.Button('Read'), sg.Exit()]] window = sg.Window('Window that stays open', layout) asyncio.run(main()) print(f'Total runtime {time.time() - ct}')
[ sg.Listbox(values=[], size=(30, H_ // 20), enable_events=True, key="__FILELIST__", tooltip="Select a file to analyze"), canvasTabs ]] layout_ = [[ sg.TabGroup([[ sg.Tab('Analyze Data', tab2, tooltip="Analyze TIFF files"), sg.Tab('Behaviour Session', tab1, tooltip="Run experiment") ]], key="__TABS__", enable_events=True) ], [sg.Exit(), status_] # , [sg.Output( size=(3*W_//20,2))] ] win_ = sg.Window('MouseBehaviour', layout_).Finalize() class TiffFile: def __init__(self, path): self.path = Path(path) self.name = self.path.name def __str__(self): return self.name def readFrames(self):
from lxml import etree from bs4 import BeautifulSoup from datetime import datetime, timedelta import csv import random import time import logging import PySimpleGUI as sg from fake_useragent import UserAgent values = ["a", "b", "c"] layout = [[sg.Text('Start quarter(\'mm_dd_yyyy\',eg:01_31_2018):')], [sg.Input()], [sg.Text('End quarter(eg,\'mm_dd_yyyy\'):')], [sg.Input()], [sg.Text('One keyword(eg:bond,China...):')], [sg.Input()], [sg.RButton('Read'), sg.Exit()]] window = sg.Window('Persistent GUI Window').Layout(layout) while True: event, start_end = window.Read() if event is None or event == 'Exit': break else: print(start_end) values[0] = start_end[0] values[1] = start_end[1] values[2] = start_end[2] window.Close() start_dt = datetime.strptime(values[0], '%m_%d_%Y') + timedelta(days=7)
import PySimpleGUI as sg from datetime import datetime timer_paused = False layout = [[sg.Text('')], [sg.Text(size=(16,2),key='text')], [sg.Button('Pause',key='Pause'),sg.Button('Resume',key='Resume'), sg.Exit(key='Exit')]] window = sg.Window('Timer', layout, size=(300, 120), modal=True) while True: # For more details on non-blobking window events and the usage of 'timeout' parameter # read @ https://github.com/PySimpleGUI/PySimpleGUI/issues/520 # Read with a timeout is a very good thing for your GUIs to use in a read non-blocking situation, # if you can use them. If your device can wait for a little while, then use this kind of read. # The longer you're able to add to the timeout value, the less CPU time you'll be taking). # window.read(timeout=10) : This program will quickly test for user input, then deal with the hardware. # Then it'll sleep for 10ms, while your gui is non-responsive, then it'll check in with your GUI again. event, values = window.read(timeout=10) # Close window if exit.\/close is clicked. if event == sg.WINDOW_CLOSED or event == 'Exit': break current_time = datetime.now() current_time = current_time.strftime("%H:%M:%S") window['text'].update(current_time) # Pause the timer. if event == 'Pause':
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:
from pytube import Playlist from pytube import YouTube import re import PySimpleGUI as sg # sg.theme('DarkAmber') #theme layout = [[sg.Text('Enter video / playlist link: ')], [sg.Input(key='link')], [ sg.Text('Download Folder: '), sg.In(size=(25, 1), enable_events=True, key='-FOLDER-'), sg.FolderBrowse() ], [sg.Button('Download'), sg.Exit()], [sg.Text('Downloading:'), sg.Text(size=(15, 1), key='-OUTPUT-')]] window = sg.Window('YouTube Downloader by JLearn PH', layout) while True: event, values = window.read() link = values['link'] show = '' download_folder = values['-FOLDER-'] #for a playlist if event == 'Download': if (link == '' and download_folder == ''): sg.popup_error('Enter a YouTube Link and Download Folder') elif link == '': sg.popup_error('Enter a YouTube Link') elif download_folder == '':