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....')], [sg.Output(size=(900, 500), font=('Courier', 10))], [ sg.Spin(values=(1, 4), initial_value=1, size=(50, 25), key='Num Answers', font=('Helvetica', 15)), sg.Text('Num Answers',font=('Helvetica', 15), size=(170,22)), sg.Checkbox('Display Full Text', key='full text', font=('Helvetica', 15), size=(200,22)), sg.T('Command History', font=('Helvetica', 15)), sg.T('', size=(100,25), text_color=sg.BLUES[0], key='history'), sg.Stretch()], [sg.Multiline(size=(600, 100), enter_submits=True, focus=True, key='query', do_not_clear=False), sg.Stretch(), 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])), sg.Stretch()] ] window = sg.Window('How Do I ??', default_element_size=(100, 25), # element_padding=(10,10), icon=DEFAULT_ICON, font=('Helvetica',14), default_button_element_size=(70,50), return_keyboard_events=True, no_titlebar=False, grab_anywhere=True,) window.Layout(layout) # ---===--- Loop taking in user input and using it to query HowDoI --- # command_history = [] history_offset = 0 while True: event, values = window.Read() if event in ['SEND', 'query']: # window.FindElement('+OUTPUT+').Update('test of output') # manually clear input because keyboard events blocks clear query = values['query'].rstrip() # print(query) QueryHowDoI(query, values['Num Answers'], values['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 event is None or event == 'EXIT': # if exit button or closed using X break elif 'Up' in event 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 event 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 event: # clear currently line window.FindElement('query').Update('')
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('', font='Helvetica 25', 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, location=(0, 0)).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 event, values = window.Read(timeout=500) if event == 'Quit' or event 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 g_exit = True window.Close()
def main(): sg.ChangeLookAndFeel('LightGreen') # define the window layout layout = [[ sg.Text('OpenCV Demo', size=(40, 1), justification='center', font='Helvetica 20') ], [sg.Image(filename='', key='image')], [ sg.Button('Record', size=(10, 1), font='Helvetica 14'), sg.Button('Stop', size=(10, 1), font='Any 14'), sg.Button('Exit', size=(10, 1), font='Helvetica 14'), sg.Button('About', size=(10, 1), font='Any 14') ]] # create the window and show it without the plot window = sg.Window('Demo Application - OpenCV Integration', location=(800, 400)) window.Layout(layout) # ---===--- Event LOOP Read and display frames, operate the GUI --- # cap = cv2.VideoCapture(0) recording = False while True: event, values = window.Read(timeout=0, timeout_key='timeout') if event == 'Exit' or event is None: sys.exit(0) pass elif event == 'Record': recording = True elif event == 'Stop': recording = False img = np.full((480, 640), 255) imgbytes = cv2.imencode('.png', img)[1].tobytes( ) #this is faster, shorter and needs less includes window.FindElement('image').Update(data=imgbytes) elif event == 'About': sg.PopupNoWait( 'Made with PySimpleGUI', 'www.PySimpleGUI.org', 'Check out how the video keeps playing behind this window.', 'I finally figured out how to display frames from a webcam.', 'ENJOY! Go make something really cool with this... please!', keep_on_top=True) if recording: ret, frame = cap.read() imgbytes = cv2.imencode('.png', frame)[1].tobytes() #ditto window.FindElement('image').Update(data=imgbytes)
def gui(): sg.ChangeLookAndFeel('Topanga') sg.SetOptions(border_width=0, margins=(0, 0), element_padding=(0, 0)) layout = [ [sg.T('GitHub Issues Watcher' + 48 * ' '), sg.Button('', size=(25,25), image_data=red_x, key='_quit_',button_color=(sg.LOOK_AND_FEEL_TABLE['Topanga']['TEXT'],sg.LOOK_AND_FEEL_TABLE['Topanga']['BACKGROUND']), tooltip='Closes window')], [sg.T('', key='_status_', size=(12, 1))], [sg.T('', key='_numissues_', size=(20, 1))], ] window = sg.Window('Issue watcher', no_titlebar=True, grab_anywhere=True, keep_on_top=True, alpha_channel=.8, # dim the lights a little location=(2121,310), # locate in upper right corner of screen ).Layout(layout).Finalize() window.Refresh() status_elem = window.FindElement('_status_') issues_elem = window.FindElement('_numissues_') initial_issue_count, initial_first_issue = get_num_issues() # The Event Loop runs every 1000ms i = 0 while True: if i % 60 == 0: # Every 60 seconds read GitHub status_elem.Update('Reading...') window.Refresh() issues, first_issue = get_num_issues() issues_elem.Update('{} Issues. {} is first issue'.format(issues, initial_first_issue)) window.Refresh() # if something changed, then make a popup if issues != initial_issue_count or first_issue != initial_first_issue: sg.PopupNoWait('Issues changed on GitHub', background_color='red') initial_issue_count = issues initial_first_issue = first_issue status_elem.Update('') else: status_elem.Update('.' if i%2 else '') # blink a '.' every 2 seconds so know still running # read with a 1 second timeout event, values = window.Read(timeout=1000) if event in ('_quit_', None): break i += 1
#!/usr/bin/env python import os, sys import pycurl import queue import time import certifi from io import BytesIO import json # import PySimpleGUIWx as sg import PySimpleGUIQt as sg import webbrowser sg.ChangeLookAndFeel('Reds') sg.SetOptions(font='any 12') version = 1.0 path = os.path.abspath(sys.argv[0]) path = os.path.dirname(path) os.chdir(path) icon1 = os.path.join(path, 'icons', "cat1.png") icon2 = os.path.join(path, 'icons', "cat2.png") user = '******' # load your authorization token from a file with open('token.txt') as f: password = f.read().strip() base_url = 'https://api.github.com'
else: raise def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) return os.path.join(base_path, relative_path) prototext = resource_path("colorization_deploy_v2.prototxt") caffemodel = resource_path("colorization_release_v2.caffemodel") npyfile = resource_path("pts_in_hull.npy") sg.ChangeLookAndFeel('Reddit') sg.set_options(button_color=("0079d3", "0079d3"), button_element_size=(10, 1), text_justification="center") col1 = [[sg.T("IMAGEM:", size=(44, 1)), sg.I(size=(0, 0), visible=False, key="img", enable_events=True), sg.FileBrowse("SELECIONAR", file_types=(("Imagem", "*.png; *.jpg; *.jpeg"),), target="img")], [sg.Image(filename=resource_path("placeholder.png"), key="img_display")]] col2 = [[sg.T('RESULTADO:', size=(44, 1)), sg.I(size=(0, 0), visible=False, key="savefile", enable_events=True), sg.B("COLORIR", key="processar")], [sg.Image(filename=resource_path("placeholder.png"), key="img_display2", )]] tab1_layout = [[sg.Column(col1), sg.Column(col2)], [sg.Exit(key="EXIT"), sg.FileSaveAs("SALVAR", file_types=(("Imagem", "*.jpg"),), target='savefile', key="savefilebrowse", disabled=True, button_color=("black","grey"))]] tab2_layout = [[sg.T('PASTA:'), sg.I(key="pasta", size=(98,1)), sg.FolderBrowse()], [sg.B("COLORIR")], [sg.Exit(key="Exit")]] layout = [[sg.T("\t\t\t\t\tCOLORIZADOR DE FOTOS EM PRETO E BRANCO", font=("Arial 12 bold"))],
# YOLO object detection using a webcam # Exact same demo as the read from disk, but instead of disk a webcam is used. # import the necessary packages import numpy as np # import argparse import imutils import time import cv2 import os import PySimpleGUIQt as sg i_vid = r'videos\car_chase_01.mp4' o_vid = r'output\car_chase_01_out.mp4' y_path = r'yolo-coco' sg.ChangeLookAndFeel('LightGreen') layout = [ [ sg.Text('YOLO Video Player', size=(22, 1), font=('Any', 18), text_color='#1c86ee', justification='left') ], [ sg.Text('Path to input video'), sg.In(i_vid, size=(40, 1), key='input'), sg.FileBrowse() ], [ sg.Text('Optional Path to output video'), sg.In(o_vid, size=(40, 1), key='output'),
def main(): sg.ChangeLookAndFeel('GreenTan') # sg.SetOptions(element_padding=(0,0)) # ------ Menu Definition ------ # menu_def = [ ['&File', ['&Open', '&Save', '&Properties', 'E&xit']], [ '&Edit', ['&Paste', [ 'Special', 'Normal', ], 'Undo'], ], ['&Toolbar', ['Command &1', 'Command &2', 'Command &3', 'Command &4']], ['&Help', '&About...'], ] treedata = sg.TreeData() treedata.Insert( "", '_A_', 'Tree Item 1', [1, 2, 3], ) treedata.Insert( "", '_B_', 'B', [4, 5, 6], ) treedata.Insert( "_A_", '_A1_', 'Sub Item 1', ['can', 'be', 'anything'], ) treedata.Insert( "", '_C_', 'C', [], ) treedata.Insert( "_C_", '_C1_', 'C1', ['or'], ) treedata.Insert("_A_", '_A2_', 'Sub Item 2', [None, None]) treedata.Insert("_A1_", '_A3_', 'A30', ['getting deep']) treedata.Insert("_C_", '_C2_', 'C2', ['nothing', 'at', 'all']) for i in range(100): treedata.Insert('_C_', i, i, []) frame1 = [ [sg.Input('Input Text', size=(250, 35)), sg.Stretch()], [ sg.Multiline(size=(250, 75), default_text='Multiline Input'), sg.MultilineOutput(size=(250, 75), default_text='Multiline Output') ], ] frame2 = [ [sg.Listbox(['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(200, 85))], [ sg.Combo(['Combo item 1', 'Combo item 2', 'Combo item 3'], size=(200, 35)) ], [sg.Spin([1, 2, 3], size=(40, 30))], ] frame3 = [ [sg.Checkbox('Checkbox1', True), sg.Checkbox('Checkbox1')], [ sg.Radio('Radio Button1', 1), sg.Radio('Radio Button2', 1, default=True), sg.Stretch() ], ] frame4 = [ [ sg.Slider(range=(0, 100), orientation='v', size=(3, 30), default_value=40), sg.Dial(range=(0, 100), tick_interval=50, size=(150, 150), default_value=40), sg.Stretch() ], ] matrix = [[str(x * y) for x in range(4)] for y in range(3)] frame5 = [ [ sg.Table(values=matrix, max_col_width=25, auto_size_columns=True, display_row_numbers=True, change_submits=False, bind_return_key=True, justification='right', num_rows=8, alternating_row_color='lightblue', key='_table_', text_color='black'), sg.Tree(data=treedata, headings=['col1', 'col2', 'col3'], change_submits=True, auto_size_columns=True, num_rows=10, col0_width=10, key='_TREE_', show_expanded=True, size=(200, 150)), sg.Stretch() ], ] graph_elem = sg.Graph((880, 150), (0, 0), (600, 300), key='+GRAPH+') frame6 = [ [graph_elem, sg.Stretch()], ] tab1 = sg.Tab('Graph Number 1', frame6) tab2 = sg.Tab('Graph Number 2', [[]]) layout = [ [sg.Menu(menu_def)], [ sg.Image(data_base64=logo), sg.Frame('Input Text Group', frame1, title_color='red'), sg.Stretch() ], [ sg.Frame('Multiple Choice Group', frame2, title_color='green'), sg.Frame('Binary Choice Group', frame3, title_color='purple'), sg.Frame('Variable Choice Group', frame4, title_color='blue'), sg.Stretch() ], [ sg.Frame('Structured Data Group', frame5, title_color='red'), ], # [sg.Frame('Graphing Group', frame6)], [sg.TabGroup([[tab1, tab2]])], [ sg.ProgressBar(max_value=600, start_value=400, size=(600, 25), key='+PROGRESS+'), sg.Stretch(), sg.ButtonMenu('&Menu', ['Menu', ['&Pause Graph', 'Menu item']], key='_MENU_'), sg.Button('Button'), sg.Button('Exit') ], ] window = sg.Window('Window Title', font=('Helvetica', 13), default_button_element_size=(100, 30), auto_size_buttons=False, default_element_size=(200, 22)).Layout(layout).Finalize() graph_elem.DrawCircle((200, 200), 50, 'blue') i = 0 graph_paused = False while True: # Event Loop # sg.TimerStart() event, values = window.Read(timeout=0) if event is None or event == 'Exit': break if event == 'Button': print(event, values) if values['_MENU_'] == 'Pause Graph': graph_paused = not graph_paused if not graph_paused: i += 1 if i >= 600: graph_elem.Move(-1, 0) graph_elem.DrawLine((i, 0), (i, randint(0, 300)), width=1, color='#{:06x}'.format(randint(0, 0xffffff))) window.FindElement('+PROGRESS+').UpdateBar(i % 600) # sg.TimerStop() window.Close()
#!/usr/bin/env python import PySimpleGUIQt as sg sg.ChangeLookAndFeel('Topanga') # ------ Column Definition ------ # column1 = [ [ sg.Text('Column 1', background_color='lightblue', text_color='black', justification='center', size=(100, 22)) ], [sg.Spin((1, 10), size=(100, 22))], [sg.Spin((1, 10), size=(100, 22))], [sg.Spin((1, 10), size=(100, 22))], ] layout = [ [ sg.Text('(Almost) All widgets in one Window!', justification='c', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE) ], [sg.Text('Here is some text.... and a place to enter text')], [sg.InputText('This is my text', size=(400, 22))], [ sg.Frame( layout=[[ sg.Checkbox('Checkbox', size=(185, 22)), sg.Checkbox('My second checkbox!', default=True)
config = Config() config = config.data() print(config) # Load bytecode for icon from monopolpy_companion.lib.gui.models.images.icons.main_default import icon as app_icon # Load bytecode for button images from monopolpy_companion.lib.gui.models.images.buttons.app_win import start_new_button_img from monopolpy_companion.lib.gui.models.images.buttons.app_win import load_saved_button_img import PySimpleGUIQt as gui conf = config gui.ChangeLookAndFeel('DarkGreen1') button_frame = [ [gui.Button('', key='start_new_main_button', image_data=start_new_button_img)], [gui.Button('', key='load_saved_main_button', image_data=load_saved_button_img)], [gui.Button('Options', key='options_main_button', font=('Monopoly, Bold', 16))], [gui.Button('Manage Players', key='play_man_main_button', font=('Monopoly, Bold', 16))] ] frame = [ [gui.Text('Welcome to Monopolpy Companion!', justification='center', background_color='#C70000', font=('Monopoly, Bold', 18))], [gui.Frame('What would you like to do', button_frame, title_location='center-top', background_color='#99FFFFFF', title_color='#000000')],
def resource_path(relative_path): try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) pytesseract.pytesseract.tesseract_cmd = resource_path( r"Tesseract-OCR\tesseract.exe") aod = 0 monitor_number = 0 sg.ChangeLookAndFeel("LightGreen") layout = [ [ sg.Text("Amount of Deocs"), sg.Input(key="amountInput", tooltip="Tip: 50 per page") ], [ sg.Text("Select Monitor MHW is on (default 1)"), sg.Drop(values=(1, 2, 3, 4), key="dropdown") ], [ sg.Button(" Default 16:9 Region ", tooltip="Use this if you have a 16:9 monitor", key="defaultButton"), sg.Button( " Select Custom Region ",
import PySimpleGUIQt as sg # sg.Popup('test 1') # sg.Popup('test 2') sg.ChangeLookAndFeel('GreenTan') layout = [ [ sg.Text('Hello From PySimpleGUIQt!', text_color='red', tooltip='This is my tooltip', justification='c', font=('Courier', 22), key='_TEXT_') ], [ sg.Text('Input something here'), sg.Stretch(), sg.Input('This is an InputText Element', key='_INPUT_', font=('Any', 14)) ], [ sg.Text('This is the new Dial Element'), sg.Dial(background_color='red'), sg.Stretch() ], [ sg.Combo(['Combo 1', 'Combo 2', 'Combo 3'], key='+COMBO+', size=(150, 30), text_color='green') ],
from glob import glob from shutil import copy from os.path import basename, isdir import threading import PySimpleGUIQt as sg sg.ChangeLookAndFeel('SystemDefaultForReal') layout = [ [sg.Stretch(), sg.T("COPIADOR DE ARQUIVOS"), sg.Stretch()], [ sg.T("ARQUIVOS:", tooltip='Local onde as pastas contendo os documentos estão.', size=(10, 1)), sg.I("", do_not_clear=True, size=(92, 1), key='Files', tooltip='Local onde as pastas contendo os documentos estão.'), sg.FolderBrowse("PASTA", size=(8, 1), tooltip='Procurar pasta.'), sg.Stretch() ], [ sg.T("EXTENSÃO:", tooltip='Local onde as pastas contendo os documentos estão.', size=(10, 1)), sg.I("", do_not_clear=True, size=(5, 1), key='Ext',
import os from tabulate import tabulate import PySimpleGUIQt as sg # The following are the available custom processors. from processors import convert_to_plaintext from processors import encode_to_utf8 from processors import standardize_characters from processors import remove_pdf_metadata # Set the 'print' command to use the GUI. print = sg.Print # Define the GUI. sg.ChangeLookAndFeel('TealMono') layout = [ [sg.Text('Select folder to process:', size=(22, 1)), sg.InputText("", key='source'), sg.FolderBrowse(size=(9, 1))], [sg.Text('Save files to:', size=(25, 1)), sg.InputText("", key='destination'), sg.FolderBrowse(size=(9, 1))], [sg.Text('Choose processor:', size=(20, 1))], [sg.Radio("Convert to plaintext (supports .docx, .html, .pdf, .pptx, .rtf)", "Processors", key='convertToPlaintext', default=True)], [sg.Radio("Encode in UTF-8 (expects .txt files)", "Processors", key='encodeUtf8', default=False)], [sg.Radio("Standardize non-ASCII characters and remove non-English characters (expects UTF-8 encoded input)", "Processors", key='standardizeCharacters', default=False)], [sg.Radio("Remove PDF metadata (i.e., authoring information). Expects .pdf files.", "Processors", key='removeMetadata', default=False)], [sg.Button("Process files", size=(20, 1)), sg.Exit(size=(6, 1))],
import time """ Timer Desktop Widget Creates a floating timer that is always on top of other windows You move it by grabbing anywhere on the window Good example of how to do a non-blocking, polling program using SimpleGUI Can be used to poll hardware when running on a Pi While the timer ticks are being generated by PySimpleGUI's "timeout" mechanism, the actual value of the timer that is displayed comes from the system timer, time.time(). This guarantees an accurate time value is displayed regardless of the accuracy of the PySimpleGUI timer tick. If this design were not used, then the time value displayed would slowly drift by the amount of time it takes to execute the PySimpleGUI read and update calls (not good!) NOTE - you will get a warning message printed when you exit using exit button. It will look something like: invalid command name \"1616802625480StopMove\" """ # ---------------- Create Form ---------------- sg.ChangeLookAndFeel('Black') sg.SetOptions(element_padding=(0, 0)) layout = [[ sg.Text('test', size=(222, 90), font=('Any', 24), text_color='white', justification='center', key='text') ], [ sg.Button('Pause', key='button', button_color=('white', '#001480')), sg.Button('Reset',
def displayImages(): sg.ChangeLookAndFeel('LightGrey') folder = sg.popup_get_folder('Image folder to open', title='Choose Folder', default_path='') img_types = (".png", ".jpg", "jpeg", ".tiff", ".bmp") flist0 = os.listdir(folder) fnames = [f for f in flist0 if os.path.isfile( os.path.join(folder, f)) and f.lower().endswith(img_types)] num_files = len(fnames) del flist0 def get_img_data(f, maxsize=(1200, 850), first=False): img = Image.open(f) img.thumbnail(maxsize) if first: bio = io.BytesIO() img.save(bio, format="PNG") del img return bio.getvalue() return ImageTk.PhotoImage(img) filename = os.path.join(folder, fnames[0]) image_elem = sg.Image(data=get_img_data(filename, first=True)) filename_display_elem = sg.Text(filename, size=(80, 3)) file_num_display_elem = sg.Text('File 1 of {}'.format(num_files), size=(15, 1)) col = [[filename_display_elem], [image_elem]] col_files = [[sg.Text('List of images')], [sg.Listbox(values=fnames, change_submits=True, size=(60, 10), key='listbox')], [sg.Button('Next', size=(8, 1)), sg.Button('Prev', size=(8, 1)), file_num_display_elem], [sg.Button('Enhance Resolution', size=(16, 1))], [sg.Button('Exit', size=(8, 1))]] layoutSavedImages = [[sg.Column(col_files), sg.Column(col)]] window = sg.Window('Image Browser', layoutSavedImages, return_keyboard_events=True, location=(0, 0), use_default_focus=False) i = 0 im = 0 while True: event, values = window.read() print(event, values) if event == sg.WIN_CLOSED or event == 'Exit': raise SystemExit() elif event in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34'): i += 1 if i >= num_files: i -= num_files filename = os.path.join(folder, fnames[i]) elif event in ('Prev', 'MouseWheel:Up', 'Up:38', 'Prior:33'): i -= 1 if i < 0: i = num_files + i filename = os.path.join(folder, fnames[i]) elif event == 'listbox': f = values["listbox"][0] filename = os.path.join(folder, f) i = fnames.index(f) elif event == 'Enhance Resolution': filename = os.path.join(folder, fnames[i]) super_res(filename, im) im += 1 print(filename) else: filename = os.path.join(folder, fnames[i]) image_elem.update(data=get_img_data(filename, first=True)) filename_display_elem.update(filename) file_num_display_elem.update('File {} of {}'.format(i+1, num_files)) window.close()
# !/usr/bin/env python import cx_Oracle import PySimpleGUIQt as sg con = cx_Oracle.connect('EOM/[email protected]/xe') cur = con.cursor(scrollable=True) sg.ChangeLookAndFeel('DarkBlue') layout = [[sg.Stretch(), sg.Text('Add New Classes', font=("Helvetica", 25)), sg.Stretch()], [sg.Stretch(), sg.Text('Course Code', font=("Helvetica", 15)), sg.Stretch()], [sg.Stretch(), sg.Input(size=(20, 2), ), sg.Stretch()], [sg.Stretch(), sg.Text('Period Number', font=("Helvetica", 15)), sg.Stretch()], [sg.Stretch(), sg.Input(size=(20, 2)), sg.Stretch()], [sg.Stretch(), sg.Text('Year', font=("Helvetica", 15)), sg.Stretch(), ], [sg.Stretch(), sg.DropDown(('2016', '2017', '2018', '2019'), size=(12, 2), font=("Helvetica", 15)), sg.Stretch(), ], [sg.Stretch(), sg.ReadButton('Add Course', key='add_new_courses_button', size=(20, 2), bind_return_key=True), sg.Stretch(), ] ] window = sg.Window('Add New Courses', default_element_size=(40, 2)).Layout(layout) while 'add_new_courses_button': event, values = window.Read() if event is None or event == 'Exit': break v_course_code = values[0] v_period_num = values[1] v_year = values[2] print(v_course_code, v_period_num, v_year)
def main(): # A couple of "Uber Elements" that combine several elements and enable bulk edits def Txt(text, **kwargs): return (sg.Text(text, font=('Helvetica 8'), **kwargs)) def GraphColumn(name, key): col = sg.Column([[ Txt(name, key=key + '_TXT_'), ], [ sg.Graph((GRAPH_WIDTH, GRAPH_HEIGHT), (0, 0), (GRAPH_WIDTH, 100), background_color='black', key=key + '_GRAPH_') ]], pad=(2, 2)) return col num_cores = len( psutil.cpu_percent(percpu=True)) # get the number of cores in the CPU sg.ChangeLookAndFeel('Black') sg.SetOptions(element_padding=(0, 0), margins=(0, 0), border_width=0) # ---------------- Create Layout ---------------- layout = [[ sg.Button('', image_data=red_x, button_color=('red', 'black'), key='Exit', tooltip='Closes window'), sg.Stretch(), sg.Text(' CPU Core Usage'), sg.Stretch() ]] # add on the graphs for rows in range(num_cores // NUM_COLS + 1): row = [] for cols in range(min(num_cores - rows * NUM_COLS, NUM_COLS)): row.append( GraphColumn('CPU ' + str(rows * NUM_COLS + cols), '_CPU_' + str(rows * NUM_COLS + cols))) layout.append(row) # ---------------- Create Window ---------------- window = sg.Window( 'PSG System Dashboard', keep_on_top=True, auto_size_buttons=False, grab_anywhere=True, no_titlebar=True, default_button_element_size=(20, 15), return_keyboard_events=True, alpha_channel=TRANSPARENCY, use_default_focus=False, ).Layout(layout) # setup graphs & initial values graphs = [] for i in range(num_cores): graphs.append( DashGraph(window.FindElement('_CPU_' + str(i) + '_GRAPH_'), window.FindElement('_CPU_' + str(i) + '_TXT_'), 0, colors[i % 6])) # ---------------- main loop ---------------- while (True): # --------- Read and update window once every Polling Frequency -------- event, values = window.Read(timeout=POLL_FREQUENCY) if event in (None, 'Exit'): # Be nice and give an exit break # read CPU for each core stats = psutil.cpu_percent(interval=.2, percpu=True) # Update each graph for i in range(num_cores): graphs[i].graph_percentage_abs(stats[i]) graphs[i].text_display('{} CPU {:2.0f}'.format(i, stats[i])) window.Close()