#---- press YES (or finshe the first part)
Back = True
Targ = False
while Back:
    Back = False
    #choose the target picture
    event, TargetDir = sg.Window('My Script', [[
        sg.Text('choose your target picture')
    ], [sg.In(), sg.FileBrowse()], [sg.Open(), sg.Cancel()]]).read(close=True)
    if event == sg.WIN_CLOSED or event == 'Cancel':
        break
    imgTarget = Image.open(TargetDir[0])

    #make the window (image, slider and buttons)
    imageT = sg.Image(data=get_img_data(TargetDir[0], first=True))
    pixelsT = sg.Text('size: {} x {}'.format(imgTarget.size[0],
                                             imgTarget.size[1]))
    layout = [[imageT],
              [sg.Text('Slider Demonstration'),
               sg.Text('', key='_OUTPUT_')],
              [
                  sg.T('0', key='_LEFT_'),
                  sg.Slider((1, 100),
                            key='_SLIDER_',
                            orientation='h',
                            enable_events=True,
                            disable_number_display=True),
                  sg.T('0', key='_RIGHT_')
              ], [sg.Button('OK'), sg.Button('Back'), pixelsT]]
예제 #2
0
v_max = 255

layout = [
  [sg.Frame('Hue',[[      
        sg.Slider(range=(0, 255), size=(15, 10), orientation='h', default_value=1, key="h_min")],           
        [sg.Slider(range=(0, 255), orientation='h', size=(15, 10), default_value=1, key="h_max")]]),
        sg.Frame('Saturation',[[     
        sg.Slider(range=(0, 255), size=(15, 10), orientation='h', default_value=1, key="s_min")],           
        [sg.Slider(range=(0, 255), orientation='h', size=(15, 10), default_value=1, key="s_max" 
        )]]),
        sg.Frame('Value',[[      
        sg.Slider(range=(0, 255), size=(15, 10), orientation='h', default_value=1, key="v_min")],           
        [sg.Slider(range=(0, 255), orientation='h', size=(15, 10), default_value=1, key="v_max")]]),
        ],
  
  [sg.Image(data=gs(imgf, imgb, (h_min, s_min, v_min), (h_max, s_max, v_max)))]
]

window = sg.Window('Green Screen', layout)

while True:
  event, values = window.read()
  if event == sg.WINDOW_CLOSED or event == 'Quit':
    break
  elif event in ('h_min', 'h_max', 's_min', 's_max', 'v_min', 'v_max'):
    h_min = int(values['h_min'])
    h_max = int(values['h_max'])
    s_min = int(values['s_min'])
    s_max = int(values['s_max'])
    v_min = int(values['v_min'])
    v_max = int(values['v_max'])
예제 #3
0
              key="-FOLDER-",
              default_text=os.getcwd()),
        sg.FolderBrowse(),
    ],
    [
        sg.Listbox(values=fnames,
                   enable_events=True,
                   size=(40, 20),
                   key="-FILE LIST-")
    ],
]

# For now will only show the name of the file that was chosen
image_viewer_column = [[
    sg.Text("Choisir une image à flouter dans la liste à gauche:")
], [sg.Text(size=(40, 1), key="-TOUT-")], [sg.Image(key="-IMAGE-")],
                       [
                           sg.Text("Valeur de sigma:"),
                           sg.Slider(
                               (0.1, 10),
                               5,
                               0.001,
                               orientation="h",
                               size=(40, 15),
                               key="-SIGMA SLIDER-",
                           ),
                       ], [sg.Button("Envoyer", key="send")]]

# ----- Full layout -----
layout = [[
    sg.Column(file_list_column),
예제 #4
0
del root
# ------------------------------------------------------------------------------

form = sg.FlexForm(title,
                   return_keyboard_events=True,
                   location=(0, 0),
                   use_default_focus=False)

cur_page = 0
data, clip_pos = get_page(
    cur_page,  # read first page
    zoom=False,  # not zooming yet
    max_size=max_size,  # image max dim
)

image_elem = sg.Image(data=data)  # make image element

goto = sg.InputText(str(cur_page + 1),
                    size=(5, 1),
                    do_not_clear=True,
                    key="PageNumber")  # for display & input

layout = [  # the form layout
    [
        sg.ReadFormButton("Next"),
        sg.ReadFormButton("Prior"),
        sg.Text("Page:"),
        goto,
        sg.Text("(%i)" % page_count),
        sg.ReadFormButton("Zoom"),
        sg.Text("(toggle on/off, use arrows to navigate while zooming)"),
예제 #5
0
def gui(ctx):
    import PySimpleGUI as sg

    coconnect_theme = {'BACKGROUND': 'white',
                       'TEXT': '#000000',
                       'INPUT': '#c4c6e2',
                       'TEXT_INPUT': '#000000',
                       'SCROLL': '#c4c6e2',
                       'BUTTON': ('white', '#475da7','#3DB28C'),
                       'PROGRESS': ('#01826B', '#D0D0D0'),
                       'BORDER': 1,
                       'SLIDER_DEPTH': 1,
                       'PROGRESS_DEPTH': 0}
    
    # Add your dictionary to the PySimpleGUI themes
    sg.theme_add_new('coconnect', coconnect_theme)
    sg.theme('coconnect')

    _dir = os.path.dirname(os.path.abspath(coconnect.__file__))
    data_dir = f"{_dir}{os.path.sep}data{os.path.sep}"
    
    layout = [
        [sg.Image(f'{data_dir}logo.png'),sg.T("CO-CONNECT: Dataset2CDM",font = ("Roboto", 25))],
        [sg.T('Select the rules json:')],
        [sg.Input(key='_RULES_'), sg.FilesBrowse(initial_folder=os.getcwd())],
        [sg.T('Select the input CSVs:')],
        [sg.Input(key='_INPUTS_'), sg.FilesBrowse(initial_folder=os.getcwd())],
        [sg.T('Select an output folder:')],
        [sg.Input(key='_OUTPUT_',default_text='.'), sg.FolderBrowse(initial_folder=os.getcwd())],
        #[sg.Checkbox("Mask the person_id",key="_MASK_PERSON_ID_",default=False)],
        #[[sg.T('Change the default data chunksize:'),
        #  sg.Slider(range=(0,1000000),
        #            default_value=100000,
        #            resolution=10000,
        #            orientation='horizontal')]],
        [sg.OK('Run'), sg.Cancel(button_color=('white','#3DB28C'))]
    ]

    font = ("Roboto", 15)
    
    window = sg.Window('COCONNECT', layout, font=font)
    while True:
        event, values = window.Read()
        
        if event == 'Cancel' or event == None:
            break

        output_folder = values['_OUTPUT_']
        if output_folder == '':
            output_folder = None
            
        rules = values['_RULES_']
        if rules == '':
            sg.Popup(f'Error: please select a rules file')
            continue
        elif len(rules.split(';'))>1:
            sg.Popup(f'Error: only select one file for the rules!')
            continue

        inputs = values['_INPUTS_']
        if inputs == '':
            sg.Popup(f'Error: please select at least one file or directory for the inputs')
            continue
        inputs = inputs.split(';')

        #mask_person_id = values['_MASK_PERSON_ID_']

        try:
            #ctx.invoke(run,rules=rules,inputs=inputs,output_folder=output_folder,mask_person_id=mask_person_id)
            ctx.invoke(run,rules=rules,inputs=inputs,output_folder=output_folder)
            sg.Popup("Done!")
        except Exception as err:
            sg.popup_error("An exception occurred!",err)
            
        break
        
    window.close()
예제 #6
0
#Check for updates to the script
try:
    with urllib.request.urlopen(vercheck) as response:
        current_ver = response.read()
    cur_ver = current_ver.decode('ascii').replace('\n', '')
    if cur_ver != ver:
        msg_text = "{subtitle}\n\n{repo}\n\n{lic}\n\nver. {ver}\nThis version is outdated. Current version is {cur_ver}.\nPlease download the updated version at: {repo}"
    else:
        msg_text = "{subtitle}\n\n{repo}\n\n{lic}\n\nver. {ver}"
except:
    msg_text = "{subtitle}\n\n{repo}\n\n{lic}\n\nver. {ver}"
    cur_ver = ver

#GUI info window
github_text = "Go to Github"
layout = [[sg.Image(data=dpologo)], [sg.Txt('_' * 48)],
          [sg.Text(script_title, font=(20))],
          [
              sg.Text(
                  msg_text.format(subtitle=subtitle,
                                  ver=ver,
                                  repo=repo,
                                  lic=lic,
                                  cur_ver=cur_ver))
          ], [sg.Submit("OK"), sg.Cancel(github_text)]]
window = sg.Window("Info", layout)
event, values = window.Read()
window.Close()

# Open browser to Github repo if user clicked the "Go to Github" button
if event == github_text:
예제 #7
0
import PySimpleGUI as sg

f = open("number.txt", "r")
counter = f.read()

sg.change_look_and_feel('DarkGrey3') 
layout = [[sg.Image("<imagenamehere68pxby99px>.png",size=(68,88)),sg.Text(counter, font=("Arial",40), key="upb"), sg.Button(" ",image_filename="Up.png", enable_events=True)]]

# Create the window
window = sg.Window("Counter", layout)

# Create an event loop
while True:
    event, values = window.read()
    # End program if user closes window or
    if event == " ":
        f = open("number.txt", "r")
        test = f.read()
        counter = int(test)
        
        counter += 1
        w = open("number.txt", "w")
        w.write(str(counter))
        w.close()
        window["upb"].update(counter)
        
    
    # presses the OK button
    if event == sg.WIN_CLOSED:
        break
예제 #8
0
         "Pension",
         size=(30, 3),
         key="pen",
     )
 ],
 [
     sg.Text("", size=(27, 5)),
     sg.Button("Gratuity", size=(30, 3), key="gra")
 ],
 [
     sg.Text("", size=(27, 5)),
     sg.Button("Leave Salary", size=(30, 3), key="leave")
 ], [sg.HSeparator()],
 [
     sg.Image(r'python.gif',
              enable_events=True,
              key='python',
              tooltip="Click here to know more!"),
     sg.Text("", size=(60, 1)),
     sg.Image(r'gnu-linux.png',
              enable_events=True,
              key='gnu',
              tooltip="Click here to know more!")
 ], [
     sg.Text("How to use :", font=(0.5), size=(65, 1)),
 ],
 [
     sg.Text(
         "1. This is an OFFLINE app, so no need of an Internet Connection. Just select any type of calculator from "
         "the main menu.\n2. Enter valid data in the given input fields and click CALCULATE button."
         "\n3. Check your results in the output "
         "fields, As simple as that. More features will be added in future releases."
예제 #9
0
     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'),
        s.Exit()], [s.Text("", auto_size_text=False, key="tell")]
]

selayout = [  #select layout se - select
    [s.Image(r'logo1.png', pad=((90, 0), (0, 0)))],
    #[s.Text("OPTION WINDOW",pad = ((250,0),(0,0)))],
    [
        s.Button("ADD TASK", pad=((140, 0), (0, 10))),
        s.Button("EDIT STATUS", pad=((140, 140), (0, 10)))
    ],
    [
        s.Button("VIEW MODE", pad=((140, 0), (0, 10))),
        s.Button("EDIT TASK", pad=((128, 140), (0, 10)))
    ],
    [
        s.Button("DELETE TASK", pad=((140, 0), (0, 10))),
        s.Button("DELETE COMPLETED", pad=((116, 140), (0, 10)))
    ],
    [s.Button("LOG OUT"), s.Exit()]
]
예제 #10
0
    elif zoom == 2:  # top-right
        clip = fitz.Rect(mt, mr)
    elif zoom == 3:  # bot-left
        clip = fitz.Rect(ml, mb)
    if zoom == 0:  # total page
        pix = dlist.getPixmap(alpha=False)
    else:
        pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip)
    return pix.getPNGData()  # return the PNG image


window = sg.Window(title, return_keyboard_events=True, use_default_focus=False)

cur_page = 0
data = get_page(cur_page)  # show page 1 for start
image_elem = sg.Image(data=data)
goto = sg.InputText(str(cur_page + 1), size=(5, 1), do_not_clear=True)

layout = [
    [
        sg.Button('Prev'),
        sg.Button('Next'),
        sg.Text('Page:'),
        goto,
    ],
    [
        sg.Text("Zoom:"),
        sg.Button('Top-L'),
        sg.Button('Top-R'),
        sg.Button('Bot-L'),
        sg.Button('Bot-R'),
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))

matplotlib.use("TkAgg")

def draw_figure(canvas, figure):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=1)
    return figure_canvas_agg


######    Define the window layout    ###############
# Left Column
inputs_column = [
    [sg.Image(key="GREOLogo")], # PNG or GIF image
    [sg.Text("Inputs")], 
    [sg.Input('', enable_events=True,  key='-INPUT-')], # Text input field
]

# Right Column
image_viewer_column = [
    [sg.Text("Result")], # Simple Text
    [sg.Text(size=(40, 1), key="-TextResult-")], # Simple Text
    [sg.Canvas(key="-CANVAS-")], # Result Plot space 
    [sg.Button("Ok")], # Button
]

# Full Window layout
layout = [
        [   sg.Column(inputs_column),
예제 #12
0
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()
                    if event2 in ('OK', sg.WIN_CLOSED):
                        break
                    if event2 == 'COPY':
                        pyperclip.copy(time)
                        sg.PopupAutoClose('Copied to clipboard', auto_close_duration=1)
                window2.close()
            else:
                sg.Popup('Choose from 1 - 10')
        except ValueError:
            sg.Popup('Bruh!')
예제 #13
0
    ],
]

scrape_col = []
for site in all_sites:
    scrape_col.append([
        sg.pin(
            sg.Column([[
                sg.Text(all_sites[site], size=(12, 1)),
                sg.ProgressBar(3,
                               orientation='h',
                               key=f"p{site}",
                               bar_color=("#1c6fba", "#000000"),
                               border_width=1,
                               size=(20, 20)),
                sg.Image(data=check_mark, visible=False, key=f"img{site}")
            ]],
                      key=f"pcol{site}",
                      visible=False))
    ])

output_col = [[sg.Text('Output')],
              [
                  sg.Multiline(size=(69, 12),
                               key='out',
                               autoscroll=True,
                               disabled=True)
              ],
              [
                  sg.ProgressBar(3,
                                 orientation='h',
예제 #14
0
def lookAtThePicture(folder, fnames, num_files):
    # make these 2 elements outside the layout as we want to "update" them later
    # initialize to the first file in the list
    filename = os.path.join(folder, fnames[0])  # name of first file in list
    image_elem = sg.Image(data=get_img_data(filename, first=True))
    filename_display_elem = sg.Text(filename, size=(80, 3))
    file_num_display_elem = sg.Text('File 1 of {}'.format(num_files),
                                    size=(15, 1))

    # define layout, show and read the form
    col = [[filename_display_elem], [image_elem]]

    col_files = [[
        sg.Listbox(values=fnames,
                   change_submits=True,
                   size=(60, 30),
                   key='listbox')
    ],
                 [
                     sg.Button('OK', size=(8, 2)),
                     sg.Button('Cancel', size=(8, 2)), file_num_display_elem
                 ]]

    layout = [[sg.Column(col_files), sg.Column(col)]]

    window = sg.Window('Image Browser',
                       layout,
                       return_keyboard_events=True,
                       location=(0, 0),
                       use_default_focus=False)

    # loop reading the user input and displaying image, filename
    i = 0
    while True:
        # read the form
        event, values = window.read()
        #print(event, values)
        # perform button and keyboard operations
        if event == sg.WIN_CLOSED or event == 'Cancel':
            window.close()
            return False  #if not, we close the plane
        elif event == 'OK':
            window.close()
            return True  #if it is good, we continue
        elif event in ('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 ('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':  # something from the listbox
            f = values["listbox"][0]  # selected filename
            filename = os.path.join(folder, f)  # read this file
            i = fnames.index(f)  # update running index
        else:
            filename = os.path.join(folder, fnames[i])

        # update window with new image
        image_elem.update(data=get_img_data(filename, first=True))
        # update window with filename
        filename_display_elem.update(filename)
        # update page display
        file_num_display_elem.update('File {} of {}'.format(i + 1, num_files))

    window.close()
    return False
예제 #15
0
def GUI():
    image_path = resource_path("vault-tec.png")
    if not os.path.exists("Prep"):
        print(f"NOTE: {yellow}-Creating Prep folder{reset}")
        os.makedirs("Prep")

    def button2():
        r = requests.get(
            "https://raw.githubusercontent.com/texnevada/Fo76-loading-screen-preparing-tool/master/version.txt"
        )
        if r.text <= version:
            sg.PopupOK("No new updates.")
        else:
            sg.Popup("There is a new update out!")
            website = "https://github.com/texnevada/Fo76-loading-screen-preparing-tool/releases/latest"
            webbrowser.open_new_tab(website)

    # Lookup dictionary that maps button to function to call
    func_dict = {'Check for updates': button2}

    # Layout the design of the GUI
    layout = [
        [
            sg.Text(
                "===================================\n"
                f"F76LSPT - Version: {version}\n"
                "Fo76 Loading Screen Preparing Tool\n"
                "===================================",
                auto_size_text=True)
        ], [sg.Image(image_path)],
        [
            sg.Text(
                "Put the images you want as loading screens for 76 in the \"Prep\" folder before you continue.\n"
                "NOTE: This can be slow depending on the amount of files you have loaded in.\n\n"
                "Press RUN to continue",
                auto_size_text=True)
        ], [sg.Button('Run'),
            sg.Button('Check for updates'),
            sg.Quit()]
    ]

    # Show the Window to the user
    window = sg.Window('F76LSPT', layout)

    # Event loop. Read buttons, make callbacks
    while True:
        # Read the Window
        event, value = window.Read()
        if event in ('Quit', None):
            break
        elif event in ('Run', None):
            MaxNum = len(next(os.walk("Prep"))[2])
            if MaxNum == 0:
                sg.Popup(
                    "There is no images in the prep folder.\nYou will need to put some images in the prep "
                    "folder.\nThe folder will open automatically for you once you hit \"OK\"\n"
                    "Press \"Run\" once you have added some images into the Prep folder."
                )
                path = "Prep"
                path = os.path.realpath(path)
                os.startfile(path)
            elif MaxNum != 0:
                window.Close()
                file_conversion()
                break
        # Lookup event in function dictionary
        try:
            func_to_call = func_dict[
                event]  # look for a match in the function dictionary
            func_to_call(
            )  # if successfully found a match, call the function found
        except:
            pass

    window.Close()
left_col = [[
    sg.Text('Folder'),
    sg.In(size=(25, 1), enable_events=True, key='-FOLDER-'),
    sg.FolderBrowse()
], [
    sg.Listbox(values=[], enable_events=True, size=(40, 20), key='-FILE LIST-')
],
            [
                sg.Text('Resize to'),
                sg.In(key='-W-', size=(5, 1)),
                sg.In(key='-H-', size=(5, 1))
            ]]

# For now will only show the name of the file that was chosen
images_col = [[sg.Text('You choose from the list:')],
              [sg.Text(size=(40, 1), key='-TOUT-')], [sg.Image(key='-IMAGE-')]]

# ----- Full layout -----
layout = [[
    sg.Column(left_col, element_justification='c'),
    sg.VSeperator(),
    sg.Column(images_col, element_justification='c')
]]

# --------------------------------- Create Window ---------------------------------
window = sg.Window('Multiple Format Image Viewer', layout, resizable=True)

# ----- Run the Event Loop -----
# --------------------------------- Event Loop ---------------------------------
while True:
    event, values = window.read()
예제 #17
0
flag = False

while True:
    event, values = window.read()
    image_sl = values["image_sl"]
    if event in (sg.WIN_CLOSED, "Exit"):
        break
    if event == "OK":
        """window["img"].update( values["image_sl"])"""
        window.hide()
        flag = True

        if flag == True:
            layout_2 = [[sg.Text("Imagem"),
                         sg.Button("Sair", key=("sair"))],
                        [sg.Image(values["image_sl"])]]
            window_2 = sg.Window("Imagem", layout_2)

            while True:
                event_2, values_2 = window_2.read()
                if event_2 == sg.WIN_CLOSED:
                    break

                if event_2 == "sair":
                    flag = False
                    window.UnHide()
                    break
            window_2.close()

window.close()
def windowDefine():
    # Define frames & its individual internal components
    frame_cam_input = [[
        sg.Text("Click to run cameras", key="_textRunCam_"),
        sg.Button("Get", key="_get_"),
        sg.Button("Confirm", key="_confirm_", disabled=True)
    ]]
    frame_cam_img = [[
        sg.Column([[sg.Image(filename='', key='frame_0', size=(300, 300))],
                   [sg.Image(filename='', key='frame_1', size=(300, 300))]])
    ]]
    frame_cam = [[
        sg.Column([[sg.Frame('', frame_cam_input)],
                   [sg.Frame('', frame_cam_img)]])
    ]]

    frame_cube = [[
        sg.Graph((400, 400), (0, 180), (240, 0),
                 pad=(20, 20),
                 key="_net_",
                 change_submits=True,
                 drag_submits=False),
        sg.Listbox(key="_listMoves_", values=[], size=(4, 8), disabled=True)
    ],
                  [
                      sg.Text("Index: "),
                      sg.Text("?", key="_moveIndex_", size=(3, 1)),
                      sg.Slider(key="_movesProgress_",
                                orientation="horizontal",
                                disable_number_display=True,
                                disabled=True,
                                range=(0, 0),
                                enable_events=True),
                      sg.Text("Current Move: "),
                      sg.Text("?", key="_moveCurrent_", size=(4, 1))
                  ]]
    frame_button_bottom = [[
        sg.Button("Solve", disabled=True, key="_solve_"),
        sg.Button("Fill"),
        sg.Button("Reset"),
        sg.Button("Cancel")
    ]]
    # Given defined frames, define layout of window
    layout = [[
        sg.Frame("Howdy", frame_cam),
        sg.Column([[sg.Frame("Net Representation", frame_cube)],
                   [sg.Frame("button_bottom", frame_button_bottom)]])
    ]]

    def graphDefine(window):
        #g = window["_net_"]
        for face_row in range(3):
            for face_col in range(4):
                if (face_col == 1) or (face_row == 1):
                    window["_net_"].draw_rectangle(
                        ((face_col * FACE_SIZE), (face_row * FACE_SIZE)),
                        (((face_col * FACE_SIZE) + FACE_SIZE),
                         ((face_row * FACE_SIZE) + FACE_SIZE)),
                        line_color="black")
        #return g

    window = sg.Window("Window Title", layout, finalize=True)
    graphDefine(window)
    return window  # , g
예제 #19
0
def main(args):

    iniciarArch()
    sg.ChangeLookAndFeel('Dark Blue')  # Add some color for fun

    # 1- the layout

    t = True
    while t:

        dt_string = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
        layout = [[sg.Text(dt_string, size=(0, 0), font=("Helvetica", 25))],
                  [sg.Image(r'img.png')],
                  [
                      sg.Text('ingrese el nombre del jugador :'),
                      sg.Input(key='nombre')
                  ], [sg.Text('seleccione un juego')],
                  [
                      sg.Radio('ahorcado!     ', "RADIO1", default=False),
                      sg.Radio('tateti!', "RADIO1"),
                      sg.Radio('otello!', "RADIO1")
                  ],
                  [
                      sg.Button('Jugar'),
                      sg.Button('Salir'),
                      sg.Button('Ver Registro')
                  ]]  ##

        # 2 - the window
        window = sg.Window('Juegos', layout)
        window.Finalize()

        event, values = window.Read()

        if event is None:

            break
        if event is 'Jugar':
            print(values['nombre'])

            if values[1]:
                cargarArch(values['nombre'], 'ahorcado')

                hangman.main()

            if values[2]:
                cargarArch(values['nombre'], 'tateti')
                tictactoeModificado.main()

            if values[3]:
                cargarArch(values['nombre'], 'otello')
                reversegam.main()

        if event is 'Guardar':
            print('guardar')

        if event is 'Salir':
            print('salir')

            window.close()
            t = False
        if event is 'Ver Registro':
            mostrarRegistro()
예제 #20
0
def card(meaning, phrase, image, windowname, lan):
    needs_translit = False
    translit = ''
    glang = google_sp_dict[lan]
    if (lan == 'ru' or lan == 'ja' or lan == 'ko'):
        translit = transliter(phrase, lan)
        print(translit)
        needs_translit = True
    if needs_translit == True:
        layout = [[sg.Text(meaning)], [sg.Text(phrase)], [sg.Text(translit)],
                  [sg.Image(image)],
                  [sg.Text('Repeat sentence'),
                   sg.InputText()],
                  [
                      sg.Button('Ok'),
                      sg.Button('Repeat'),
                      sg.Button('Skip'),
                      sg.Button('Cancel')
                  ],
                  [
                      sg.Button('Speech to text'),
                      sg.Text('Say something right after clicking')
                  ]]
    else:
        layout = [[sg.Text(meaning)], [sg.Text(phrase)], [sg.Image(image)],
                  [sg.Text('Repeat sentence'),
                   sg.InputText()],
                  [
                      sg.Button('Ok'),
                      sg.Button('Repeat'),
                      sg.Button('Skip'),
                      sg.Button('Cancel')
                  ],
                  [
                      sg.Button('Speech to text'),
                      sg.Text('Say something right after clicking')
                  ]]
    global window
    window = sg.Window(windowname, layout)
    tts = gTTS(phrase, lang=lan)
    tts.save('audio.mp3')
    playsound('audio.mp3')
    while True:
        event, values = window.Read()
        if event in (None, 'Skip'):  # if user presses cancel
            break
        if event in (None, 'Cancel'):  # if user presses cancel
            global terminate
            terminate = True
            break
        if event in (None, 'Repeat'):  # if user presses repeat
            playsound('audio.mp3')
        if event in (None, 'Ok'):  # if user presses ok
            values[1] = simplify(values[1])
            print(phrase)
            if values[1] == simplify(phrase) or (values[1]
                                                 == simplify(translit)
                                                 and needs_translit == True):
                window.close()
                verifycard(meaning, phrase, image, windowname, lan)
                break
        if event in (None, 'Speech to text'):
            with sr.Microphone(sample_rate=48000) as source:
                r = sr.Recognizer()
                r.adjust_for_ambient_noise(source)
                print("Say Something!")
                audio = r.listen(source)
                try:
                    text = r.recognize_google(audio, language=glang)
                    showspeechresults(text)
                except sr.UnknownValueError:
                    print(
                        "Google Speech Recognition could not understand audio")
                except sr.RequestError as e:
                    print(
                        "Could not request results from Google Speech Recognition service; {0}"
                    ).format(e)
    window.close()
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()
        cv2.putText(image, label, (box[0], box[1] - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    end_drawing = time.time()

    print("[INFO] " + "FPS: %.2f (excluding drawing time of %.2fms)" %
          (1 / (end - start), (end_drawing - start_drawing) * 1000))

    if H > 900:
        image = ResizeWithAspectRatio(image, height=900)
    if W > 1600:
        image = ResizeWithAspectRatio(image, width=1600)

    # show the output image
    imgbytes = cv2.imencode('.png', image)[1].tobytes()  # ditto

    layout = [[sg.Text('Yolo Output')], [sg.Image(data=imgbytes)],
              [sg.OK(), sg.Cancel(), sg.Stretch()]]

    win2 = sg.Window('Orange Detection YOLOv4',
                     text_justification='right',
                     resizable=True,
                     auto_size_text=False).Layout(layout)
    event, values = win2.Read()
    win2.Close()

    # cv2.imshow("Image", image)
    cv2.waitKey(0)

win.close()
예제 #23
0
    start = True
    window.Close()

while start:
    image = 'circuit.png'
    values = ['Listbox 1', 'Listbox 2', 'Listbox 3']
    column = [
        [sg.Text('Gate Arena')],
        # [sg.Text('Player 0'), sg.Input(key='_0_',size=(5,1))],
        # [sg.Text('Player 1'), sg.Input(key='_1_',size=(5,1))],
        [sg.Button('Player 1')],
        [sg.Button('Player 2')],
        [sg.Button('Play')]
    ]

    layout = [[sg.Image(image, key='_CHANGE_')],
              [sg.Image('circuit.png', key='_GRAPH_'),
               sg.Column(column)], [sg.Button('Exit')]]
    window = sg.Window('QuantumPokerGame', layout)
    while True:  # Event Loop
        event, values = window.Read()
        print(event, values)
        if event is None or event == 'Exit':
            start = False
            break
        if event == 'Play':
            # Update the "output" element to be the value of "input" element
            if player1_play == '':
                #print(player2_play)
                #print(type(player2_play))
                sg.Popup("Player 1 didn't make a move")
예제 #24
0
def classify(folder: Path = typer.Argument("./output")):
    """
    GUI for processing the output of either ``images`` or ``video`` commands.
    Prepares an output ready the ``upload`` command.
    """
    # --------------------------------- Define Layout ---------------------------------
    left_col = [
        [
            sg.Text('Folder'),
            sg.In(size=(15, 1), enable_events=True, key='-FOLDER-'),
            sg.FolderBrowse(initial_folder=str(folder))
        ],
        [
            sg.Listbox(values=[],
                       enable_events=True,
                       size=(30, 10),
                       key='-IMAGE LIST-')
        ],
        [
            sg.Listbox(values=[],
                       enable_events=True,
                       size=(30, 6),
                       key='-VEHICLE LIST-')
        ],
        [
            sg.Listbox(values=[],
                       enable_events=True,
                       size=(30, 6),
                       key='-PLATE LIST-')
        ],
    ]
    images_col = [
        [sg.Image(key='-VEHICLE IMAGE-')],
        [sg.Image(key='-PLATE IMAGE-')],
    ]
    right_col = [
        [sg.Text('Plate'),
         sg.Input(enable_events=True, key='-FORM PLATE-')],
        [
            sg.Text('Vote'),
            sg.Radio('No Vote', 'form_vote', key='-FORM NOVOTE-'),
            sg.Radio('Upvote', 'form_vote', key='-FORM UPVOTE-'),
            sg.Radio('Downvote', 'form_vote', key='-FORM DOWNVOTE-')
        ],
        [sg.Button('SAVE')],
    ]
    # ----- Full layout -----
    layout = [
        [
            sg.Column(
                left_col,
                element_justification='c',
            ),
            sg.VSeperator(),
            sg.Column(images_col, element_justification='c'),
            sg.VSeperator(),
            sg.Column(right_col),
        ],
    ]
    # --------------------------------- Create Window ---------------------------------
    window = sg.Window('Multiple Format Image Viewer', layout, resizable=True)
    # --------------------------------- Event Loop ---------------------------------
    while True:
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        if event == '-FOLDER-':  # Folder name was filled in, make a list of image folders in the folder
            folder = values['-FOLDER-']
            try:
                vehicle_data = open_vehicle_data(folder)
            except:
                print(f'** Error opening vehicle data **')
                break
            try:
                image_dir_list = os.listdir(folder)
            except:
                image_dir_list = []
            window['-IMAGE LIST-'].update(image_dir_list, set_to_index=0)
        elif event == '-IMAGE LIST-':  # An image folder selected; show vehicles within
            try:
                directory = Path(
                    values['-FOLDER-']) / values['-IMAGE LIST-'][0]
                handle_image_selection(window, directory, vehicle_data)
            except Exception as e:
                print(f'**Error {e} **')
                pass
        elif event == '-VEHICLE LIST-':  # A vehicle image selected; show image and plates
            try:
                vehicle_filename = Path(
                    values['-FOLDER-']
                ) / values['-IMAGE LIST-'][0] / values['-VEHICLE LIST-'][0]
                handle_vehicle_selection(window, vehicle_filename,
                                         vehicle_data)
            except Exception as e:
                print(f'**Error {e} **')
                pass
        elif event == 'SAVE':
            vehicle_filename = Path(
                values['-FOLDER-']
            ) / values['-IMAGE LIST-'][0] / values['-VEHICLE LIST-'][0]
            plate = values['-FORM PLATE-']
            upvote = values['-FORM UPVOTE-']
            downvote = values['-FORM DOWNVOTE-']
            vote = True if upvote else False if downvote else None
            # import pdb; pdb.set_trace()
            vehicle_data[str(vehicle_filename)] = dict(
                plate=plate,
                vote=vote,
            )
            try:
                save_vehicle_data(values['-FOLDER-'], vehicle_data)
            except:
                break
    # --------------------------------- Close & Exit ---------------------------------
    window.close()
예제 #25
0
import PySimpleGUI as sg
from Functions import NewMember

sg.theme("Material2")

id = 0

layout = [
    [sg.Image("Library.png", size=(800, 160))],
    [
        sg.Text(
            "Hello and Welcome to our Library, fully dedicated to The Physics Department",
            font=("Simplified Arabic Fixed", 11),
            pad=(50, 30),
            key='text1'),
        sg.Text("You have to create an id to proceed with the library",
                font=("Simplified Arabic Fixed", 11),
                pad=(150, 30),
                key='text3',
                visible=False)
    ],
    [
        sg.Text("Are you New Here  ",
                font=("Simplified Arabic Fixed", 13),
                pad=(300, 50),
                key='text2'),
        sg.Text("Enter Your Name  ",
                font=("Simplified Arabic Fixed", 13),
                pad=(300, 10),
                key='text4',
                visible=False)
예제 #26
0
 def image(self, addr):
     self.layout[self.row].append(sg.Image(addr))
     self.is_compiled = False
     g.debug.prn(self, f'Added image to row {self.row}.')
예제 #27
0
        sg.In(size=(25, 1), enable_events=True, key="-FOLDER-"),
        sg.FolderBrowse(),
    ],
    [
        sg.Listbox(values=[],
                   enable_events=True,
                   size=(40, 20),
                   key="-FILE LIST-")
    ],
]

# For now will only show the name of the file that was chosen
image_viewer_column = [
    [sg.Text("Choose an image from list on left:")],
    [sg.Text(size=(40, 1), key="-TOUT-")],
    [sg.Image(key="-IMAGE-")],
]

# ----- Full layout -----
layout = [[
    sg.Column(file_list_column),
    sg.VSeperator(),
    sg.Column(image_viewer_column)
]]

window = sg.Window("Image Viewer", layout)

# Run the Event Loop
while True:
    event, values = window.read()
    if event == "Exit" or event == sg.WIN_CLOSED:
예제 #28
0
import PySimpleGUI as sg

kolom1 = [[sg.Text('Baris 1 kolom 1'),
           sg.Text('ini kolom tambahan')], [sg.Text('Baris 2 kolom 1')]]

kolom2 = [[sg.Text('Baris 1 kolom 2')], [sg.Text('Baris 2 kolom 2')],
          [sg.Button('Tombol', key='-BUT-')], [sg.Submit('Submit')],
          [sg.Cancel('Cancel')], [sg.Checkbox('Checkbox')],
          [sg.Image(key='-IMA-')], [sg.In(key='-IN-', size=(40, 1))]]

layout = [
    #[sg.Column(kolom1)],
    [sg.Column(kolom2)]
]

window = sg.Window('Aplikasi Latihan', layout)
print(dir(window))

while True:
    event, values = window.read()
    if event == 'Exit' or event == sg.WIN_CLOSED:
        break

window.close()
예제 #29
0
    [frame(9)] # just add more frames here
]
T2_col2 = [
    [sg.Text(tr.gui_output[lang], size=(20, 1), font=("arial", 12), key="T2_title2")],
    [sg.Checkbox(tr.gui_gamma[lang], size=(20, 1), key="T2_gamma")],
    [sg.Checkbox("sRGB", size=(20, 1), key="T2_srgb")],
    [sg.HorizontalSeparator()],
    [sg.Checkbox(tr.gui_single[lang], size=(22, 1), enable_events=True, key="T2_single")],
    [sg.Input(size=(22, 1), disabled=True, disabled_readonly_background_color="#3A3A3A", key="T2_path"), sg.FileBrowse(button_text=tr.gui_browse[lang], size=(6, 1), disabled=True, key="T2_browse")],
    [sg.Checkbox(tr.gui_system[lang], size=(26, 1), enable_events=True, key="T2_system")],
    [sg.InputCombo(filters.get_sets(), size=(26, 1), enable_events=True, disabled=True, key="T2_filter")],
    [sg.T("")],
    [sg.Text(tr.gui_folder[lang], key="T2_folderN")],
    [sg.Input(size=(27, 1), enable_events=True, key="T2_folder"), sg.FolderBrowse(button_text=tr.gui_browse[lang], size=(6, 1), key="T2_browse_folder")],
    [sg.Button(tr.gui_preview[lang], size=(15, 1), disabled=True, key="T2_show"), sg.Button(tr.gui_process[lang], size=(15, 1), disabled=True, key="T2_process")],
    [sg.Image(background_color="black", size=T2_preview, key="T2_preview")]
]
T2_num = len(T2_col1) - 1

T3_col1 = [
    [sg.Text(tr.gui_settings[lang], size=(20, 1), font=("arial", 12), key="T3_title1")],
    [sg.Text(tr.gui_tags[lang], size=(7, 1), key="T3_tagsN"), sg.InputCombo(tag_list(), default_value="featured", size=(14, 1), enable_events=True, key="T3_tags")],
    [sg.HorizontalSeparator()],
    [sg.Checkbox(tr.gui_gamma[lang], size=(16, 1), enable_events=True, default=True, key="T3_gamma")],
    [sg.Checkbox("sRGB", enable_events=True, size=(16, 1), key="T3_srgb")],
    [sg.HorizontalSeparator()],
    [sg.Text(tr.gui_br[lang][0], size=(18, 1), key="T3_br_mode")],
    [sg.Radio(tr.gui_br[lang][1], "T3_rad", size=(15, 1), enable_events=True, default=True, key="T3_br_mode0")],
    [sg.Radio(tr.gui_br[lang][2], "T3_rad", size=(15, 1), enable_events=True, key="T3_br_mode1")],
    [sg.Radio(tr.gui_br[lang][3], "T3_rad", size=(15, 1), enable_events=True, key="T3_br_mode2")],
    [sg.HorizontalSeparator()],
예제 #30
0
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()