Example #1
0
import requests

import PySimpleGUI as sg

req = requests.session()

sg.theme("Reddit")
# Layout
layout = [
    [sg.Text("Seu CEP: "), sg.InputText(key="sCEP")],
    [sg.Text("CEP:"), sg.Text(key="rCEP", size=(9, 1))],
    [sg.Text("Logradouro:"),
     sg.Text(key="rLog", size=(39, 1))],
    [sg.Text("Complemento:"),
     sg.Text(key="rComple", size=(25, 1))],
    [sg.Text("Bairro:"),
     sg.Text(key="rBair", size=(20, 1))],
    [sg.Text("Localidade:"),
     sg.Text(key="rLoca", size=(20, 1))],
    [sg.Text("Estado:"), sg.Text(key="rUf", size=(3, 1))],
    [sg.Button("Buscar"),
     sg.Text(key="success", size=(25, 1))],
]
# Janela
janela = sg.Window("Buscador de CEP", layout, font="arial")
# Ler os eventos
while True:
    eventos, valores = janela.read()

    if (eventos == sg.WINDOW_CLOSED):
        break
Example #2
0
if sys.version_info[0] >= 3:
    import PySimpleGUI as sg
else:
    import PySimpleGUI27 as sg

import turtle
"""
    Demo showing how to integrate drawing on a Canvas using  Turtle with PySimpleGUI
    The patern to follow:
        Create Window & Finalize
        Get the tkinter Canvas from the Canvas element
        Draw on the tkinter Canvas using turtle commands.
        Results are shown on the canvas immiedately after button press / drawing command
"""

layout = [[sg.Text('My layout')], [sg.Canvas(size=(500, 500), key='_canvas_')],
          [sg.RButton('F'),
           sg.RButton('B'),
           sg.RButton('L'),
           sg.RButton('R')]]

window = sg.Window('My new window').Layout(layout).Finalize()

canvas = window.FindElement('_canvas_').TKCanvas

t = turtle.RawTurtle(canvas)
t.pencolor("#ff0000")  # Red

t.penup()  # Regarding one of the comments
t.pendown()  # Regarding one of the comments
import PySimpleGUI as PSG

rows = [
            [PSG.Slider(range=(1, 100),
                        orientation="h",
                        size=(10, 20),
                        default_value=25,
                        key="mySlider")],
            [PSG.Multiline("type a \n story here",
                        key="myMultiline")],
            [PSG.ReadFormButton("Submit values")]
       ]

form = PSG.FlexForm("This is a form.")
form.Layout(rows)

while True:
    button, value = form.Read()
    print("Slider value: " + str(value["mySlider"]))
    print(value["myMultiline"])
def validate(values, checklist, issue_types):
    issue_type = None
    for itype in issue_types:
        if values[itype]:
            issue_type = itype
            break
    if issue_type is None:
        sg.popup_error('Must choose issue type')
        return False
    if values['-OS WIN-']:
        operating_system = 'Windows'
        os_ver = values['-OS WIN VER-']
    elif values['-OS LINUX-']:
        operating_system = 'Linux'
        os_ver = values['-OS LINUX VER-']
    elif values['-OS MAC-']:
        operating_system = 'Mac'
        os_ver = values['-OS MAC VER-']
    elif values['-OS OTHER-']:
        operating_system = 'Other'
        os_ver = values['-OS OTHER VER-']
    else:
        sg.popup_error('Must choose Operating System')
        return False

    if os_ver == '':
        sg.popup_error('Must fill in an OS Version')
        return False

    checkboxes = any([values[('-CB-', i)] for i in range(len(checklist))])
    if not checkboxes:
        sg.popup_error(
            'None of the checkboxes were checked.... you need to have tried something...anything...'
        )
        return False

    title = values['-TITLE-'].strip()
    if len(title) == 0:
        sg.popup_error("Title can't be blank")
        return False
    elif title[1:len(title) - 1] == issue_type:
        sg.popup_error(
            "Title can't be blank (only the type of issue isn't enough)")
        return False

    if len(values['-ML DETAILS-']) < 4:
        sg.popup_error("A little more details would be awesome")
        return False

    return True
 def HelpText(text):
     return sg.Text(text, size=(80, None), font=text_font)
Example #6
0
                                       'csdj.cfg')) == False:
            shutil.copy(f'{os.path.join(os.getcwd(),"csdj.cfg")}',
                        f"{os.path.join(dest,'csgo','cfg')}")
        cfg.close()


def layoutbuild():
    layout = []
    for i in os.listdir(os.path.join(os.getcwd(), 'cache')):
        name = i.replace(".wav", '')
        if i not in ['.gitkeep', 'voice_input.wav']:
            layout.append(name)
    return layout


layout = [[sg.Text("Select from available songs or add from YouTube : ")],
          [
              sg.Listbox(values=layoutbuild(),
                         size=(40, 2 * len(layoutbuild())),
                         enable_events=True,
                         key="-FILES-")
          ]]
sg.theme('Dark Blue 14')
layout.append([sg.HSeparator()])
layout.append([sg.Button("Add from YouTube", key='yt')])
window = sg.Window('CSDJ', layout)
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Cancel':
        break
    elif event == 'yt':
Example #7
0
 def __init__(self):
     self.valor_minimo = 1
     self.valor_maximo = 6
     # layout
     self.layout = [[sg.Button("Jogar o dado")], [sg.Text("Resultado:")],
                    [sg.Output(size=(5, 0))]]
Example #8
0
    def layout(self):
        friends = list_friends(self.params['user'])
        print('\nFRIENDS: ', friends)
        l = [[sg.Text(friend[0])] for friend in friends]

        return l + [[sg.Button("Back", key="main")]]
Example #9
0
 def layout(self):
     return [[sg.Button('Efeitos sonoros', key="musicas")], \
     [sg.Button('Skins', key="skins")], \
     [sg.Button('Items', key="items")], \
     [sg.Button('Habilidades', key="habilidades")],\
     [sg.Button('Back', key='main')]]
Example #10
0
def check_user():
    #check if user file is already present and is not empty(a password is writen)
    if check_file(".user.txt") and os.stat(".user.txt").st_size!=0:
        global pw_read                              #refer to global password for login
        pw_read = read_string_fromfile(".user.txt") #read in th user password
    else:#if password is not writen/file is corrupted
        #setup layout for first login
        layout = [
            [ui.Text("Set Password", font = ('AppleGothic',12))],                           #Texfield above password input
            [ui.InputText(key="-PWFIRST-",do_not_clear=False, font = ('AppleGothic',12))],  #First password input
            [ui.Text("Confirm Paswword", font = ('AppleGothic',12))],                       #Text above password confirmation
            [ui.InputText(key="-PWSECOND-",do_not_clear=False, font = ('AppleGothic',12))], #Input of password confirmaton
            #button panel for confirmation, cancel, clearing or to add random password
            [ui.B("Confirm",bind_return_key=True, font = ('AppleGothic',12)),ui.B("Cancel", font = ('AppleGothic',12)), ui.B("Random PW", font = ('AppleGothic',12), key="-RANDOM-"),ui.B("Clear", font = ('AppleGothic',12), key="-CLEAR-")]
        ]
        #Create window
        window = ui.Window("New user",layout)
        #event loop
        while True:
            event,values = window.read()                    #read from the window
            if event == 'Cancel' or event == ui.WIN_CLOSED: #if window is closed or cancel is pressed
                break                                       #break the loop
            else:                                           
                if event == "Confirm":                      #if confirm has been pressed
                    pw_first = values["-PWFIRST-"]          #asign pwFirst with input values
                    pw_second = values ["-PWSECOND-"]       #asign pwSecond with input values
                    if not pw_first or not pw_second:
                        ui.popup_error("Please fill in all values",keep_on_top=True, font = ('AppleGothic',12))         #if empty popup_error to remind to fullfill
                        continue
                    else:
                        if pw_first == pw_second:               #check if passwords match
                            ui.popup("Success, Password set", auto_close=True, auto_close_duration=0.75, keep_on_top=True)  #pop for success
                            window.close()                      #close the window
                        else:
                            ui.popup_error("Passwords don't match", font = ('AppleGothic',12))  #popup, error occured
                if event =="-RANDOM-":                      #if user wants random password
                    random = generate_password()            #generate a password and asign to random
                    window["-PWFIRST-"].update(random)      #set generated passord to inputs
                    window["-PWSECOND-"].update(random)
                if event =="-CLEAR-":                       #if clear is clicked empty the inputs
                    window["-PWFIRST-"].update("")
                    window["-PWSECOND-"].update("")
                    
        #Convert PW to hash
        global hash_pw   #refer to gloal password hash (string)
        hash_pw = hashlib.md5(pw_first.encode('utf-8')) #asign hash of first password to hash_pw string
        with open(".user.txt", 'w') as writer:         #write pw hash to file
            writer.write(hashPW.hexdigest())           #write a string of the password hash into the file
            writer.close()
        global log                                     #Set log to 1 to see that pw has been writen first time
        log = 1
    return 1                                           #return 1 (success)
Example #11
0
def login():
        #check if passwords file exists
        check_file(".passwords.txt")
        #create the layout
        layout = [
            #login field with seperator between input and textfield
            [ui.Text("Enter Password",font = ('AppleGothic',14)),ui.VerticalSeparator(),ui.InputText(size= (25,2) ,key="-PWINPUT-",do_not_clear=False,font = ('AppleGothic',12))],
            #button panel
            [ui.B("Confirm",bind_return_key=True,auto_size_button=True, font = ('AppleGothic',12)),ui.B("Cancel", font = ('AppleGothic',12))]
        ]
        #build the window
        window = ui.Window("Login", layout,size=(250,100))
        #event loop
        while True:
            event,values = window.read()
            if event == 'Cancel' or event == ui.WIN_CLOSED:     #if window is closed or cancel is pressed
                return 0                                        # 0 to End programm
            else:
                if event == "Confirm":                          #if confirm is pressed
                    loading_bar()                               #display loading bar
                    entered_pw = hashlib.md5(values["-PWINPUT-"].encode('utf-8')) #encode entered password as hash value
                    #log == 0 -> program has been opened before
                    if log == 0:
                        if pw_read == entered_pw.hexdigest():                     #Compare compare the hash strings of read and typed password
                            #strings match -> entered password is correct
                            ui.popup("Login Succesfull",keep_on_top=True, auto_close=True, auto_close_duration=0.75, font = ('AppleGothic',12)) #auto closed after 0.75 seconds
                            window.close()  #close login window
                            return 1        #return 1 for success
                        else:               #something went wrong
                            #login failed -> show error
                            ui.popup_error("Login failed, check data and try again",keep_on_top=True, font = ('AppleGothic',12)) 
                    #log == 1 -> A new user password has been set
                    if log == 1:
                        if hash_pw.hexdigest() == entered_pw.hexdigest():   #compare entered password and set password in check_user
                            ui.popup("Login Succesfull",keep_on_top=True, auto_close=True, auto_close_duration=0.75, font = ('AppleGothic',12)) #popip for success
                            return 1
                            window.close()  #close the window
                        else:
                            ui.popup_error("Login failed, check data and try again",keep_on_top=True, font = ('AppleGothic',12))    #error popup
Example #12
0
def add_password(): 
    #create empty strings for website,password and username
    web = ""
    user = ""
    pw = ""
    #create the layout
    layout = [
            [ui.Text("Website", font = ('AppleGothic',12))],                                #Textfield above Website Input
            [ui.InputText(key="-WEBSITE-",do_not_clear=True, font = ('AppleGothic',12))],   #Website Input
            [ui.Text("Username", font = ('AppleGothic',12))],                               #text above username input
            [ui.InputText(key="-USERNAME-",do_not_clear=True, font = ('AppleGothic',12))],  #username input
            [ui.Text("Password", font = ('AppleGothic',12))],                               #text above password input
            [ui.InputText(key="-PASSWORD-",do_not_clear=True, font = ('AppleGothic',12))],  #username input
            #Button Panel to confirm, cancel or add a random password
            [ui.B("Confirm",bind_return_key=True, font = ('AppleGothic',12)),ui.B("Cancel", font = ('AppleGothic',12)), ui.B("Random PW", font = ('AppleGothic',12), key="-RANDOM-"),ui.B("Clear", font = ('AppleGothic',12), key="-CLEAR-")]
        ]
    #build window with layout
    window = ui.Window("New Password",layout)
    #Event read loop    
    while True:
        event, values = window.read()                       #read the window
        if event == 'Cancel' or event == ui.WIN_CLOSED:     #if cancel is clicked or window is closed return 0 and close window
            window.close()
            return 0
        else:               
            if event == "Confirm":                          #if confirm is pressed
                if  not values["-WEBSITE-"] or not values["-USERNAME-"] or not values ["-PASSWORD-"]:               #check if inputs arent empty
                    ui.popup_error("Please fill in all values",keep_on_top=True, font = ('AppleGothic',12))         #if empty popup_error to remind to fullfill 
                    continue                                                                                        #continue to read values from user input
                else:
                    if ui.popup_yes_no("Set password ?",keep_on_top=True, font = ('AppleGothic',12)) == "Yes":      #pop for confirmation if password should be set
                        web = values["-WEBSITE-"]          #asign values of inputs to variables
                        user = values["-USERNAME-"]        #-"-
                        pw = values ["-PASSWORD-"]         #-"-
                        write_password(web,user,pw)        #write the password into the file
                        ui.popup("Success!", auto_close=True, auto_close_duration=0.75, font = ('AppleGothic',12))  #popup to confirm success
                        read_all_passwords()               #refresh pw_dict with new values
                        continue #continue adding passwords
                    else:
                        return 0 #Failed
            if event == "-RANDOM-":               #if user wants random password
                pw = generate_password()          #asign random password to pw variable
                window["-PASSWORD-"].update(pw)   #update password-input with generated password
            if event =="-CLEAR-":                 #if clear is clicked empty the inputs
                    window["-WEBSITE-"].update("")
                    window["-USERNAME-"].update("")
                    window["-PASSWORD-"].update("")
Example #13
0
            if event == "-ALLPW-":                      #if all passwords are searched
                read_all_passwords()                    #update the dictionary
                for x in keys:                          #print loop fr all keys
                    print_result(x,window)              #print key and value pair
            if event == "-SEARPW-":                         #Search PW Button pressed
                result_sear = search_password()             #asign search result to result
                if result_sear == 0:                        #if the search is canceled or a failure occured
                    continue                                #continue the loop
                else:
                    print_result(result_sear,window)        #print the result of the search
            if event =="-ADDPW-":                       #Add PW Button pressed
                result_add = add_password()             #asign result of add_password to result_add
                if result_add == 0:                     #if adding is canceled continure
                    continue   
            if event =="-DELPW-":                       #if delete is pressed
                result_del = delete_password()          #asign result of delete_password to result_del
                read_all_passwords()                    #refresh the dictionary
                if result_del == 1:
                    for x in keys:                      #print loop fr all keys
                        print_result(x,window)          #print key and value pair
                if result_del == 0:                     #if deletion is canceled continue
                    continue

#------------Main------------#
ui.theme('DefaultNoMoreNagging') #add a theme for beautification
loading_bar()                    #display the loading bar 
check_user()                     #check if a user is registered
if login() == 1:                 #if login is successfull
    mainframe()                  #grant acces to mainframe
else:
    exit()                       #otherwise exit
Example #14
0
#print(voorbeeld, Tape0Lengte)

#exit()
##Kan weg code


def TapeLayout(label, left, head, right, name):
    return [
        sg.Text(size=(12, 1), key=left, justification='right', text=label),
        sg.Text(size=(1, 1), key=head, justification='center'),
        sg.Text(size=(12, 1), key=right, justification='left'),
        sg.Text(name)
    ]


sg.theme('Dark Blue 3')

frame_TapeCommando = [[
    sg.Button('INIT Tapes', key='INIT', font='Courier 10', size=[20, 1])
],
                      [
                          sg.Button('Write Tape',
                                    key='write',
                                    font='Courier 10',
                                    size=[20, 1]),
                          sg.Input(key='-WST-', size=(1, 1)),
                          sg.Input(key='-WRA-', size=(1, 1)),
                          sg.Input(key='-WRB-', size=(1, 1)),
                          sg.Input(key='-WS-', size=(1, 1))
                      ],
                      [
Example #15
0
# verify module (.py) file exists; only then add it to the "list"
def pickModules():
    global indx
    global mlist
    
    script_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scripts', 'artifacts')

    indx = 1000     # arbitrary number to not interfere with other controls
    for key, val in tosearch.items():
        plugin_path = os.path.join(script_path, key + '.py')
        disabled = False if key != 'lastBuild' else True # lastBuild.py is REQUIRED
        mlist.append( CheckList(key + '.py [' + val[0] + ']', indx, key, disabled) )
        indx = indx + 1
        
sg.theme('DarkAmber')   # Add a touch of color
# All the stuff inside your window.

normal_font = ("Helvetica", 12)
mlist = []
# go through list of available modules and confirm they exist on the disk
pickModules()
GuiWindow.progress_bar_total = len(ileapp.tosearch)


layout = [  [sg.Text('iOS Logs, Events, And Plists Parser', font=("Helvetica", 22))],
            [sg.Text('https://github.com/abrignoni/iLEAPP', font=("Helvetica", 14))],
            [sg.Frame(layout=[
                    [sg.Input(size=(97,1)), 
                     sg.FileBrowse(font=normal_font, button_text='Browse File', key='INPUTFILEBROWSE'),
                     sg.FolderBrowse(font=normal_font, button_text='Browse Folder', target=(sg.ThisRow, -2), key='INPUTFOLDERBROWSE')
Example #16
0
 def layout():
     return [[sg.Button('Este é um nivel', key="main")]]
Example #17
0
def CheckList(mtxt, lkey, mdstring, disable=False):
    return [sg.CBox(mtxt, default=True, key=lkey, metadata=mdstring, disabled=disable)]
Example #18
0
 def layout(self):
     # Nao sei o que fazer com os mapas ainda
     return [[sg.Text("Username"), sg.Input(), sg.Text()], \
      [sg.Text("Password"), sg.Input()], \
      [sg.Button('LogIn', key="main")]]
"""
    Demo program that shows you how to integrate the PySimpleGUI Debugger
    into your program.
    In this example, the debugger is not started initiallly. You click the "Debug" button to launch it
    There are THREE steps, and they are copy and pastes.
    1. At the top of your app to debug add
            import PySimpleGUIdebugger
    2. Initialize the debugger at the start of your program by calling:
            PySimpleGUIdebugger.initialize()
    3. At the top of your app's Event Loop add:
            PySimpleGUIdebugger.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
import PySimpleGUI as sg
from entities import listings
from utils import utils

Heading = "TheAter Concession Sales"
concession_sales_info = utils.get_view_list(
    "concession sale", "databases/concession_sales_db.txt")

concession_sales_list = listings.list_factory.create_list(
    "concession sale", concession_sales_info)
concession_sales_screen = concession_sales_list.generate_list()

adminLayout = [[sg.Text("TheAter Concession Sales")],
               [
                   sg.Listbox(concession_sales_screen,
                              size=(100, len(concession_sales_screen)),
                              key='-List-',
                              enable_events=True)
               ], [sg.Button('Back To Menu')]]
Example #21
0
import sys, os, re, glob
from scripts.search_files import *
from scripts.ilapfuncs import *
import argparse
from argparse import RawTextHelpFormatter
from six.moves.configparser import RawConfigParser
from time import process_time
import  tarfile
import shutil
import webbrowser
from scripts.report import *
from zipfile import ZipFile
from tarfile import TarFile
import PySimpleGUI as sg

sg.theme('LightGreen5')   # Add a touch of color
# All the stuff inside your window.

layout = [  [sg.Text('Android Logs, Events, And Protobuf Parser.', font=("Helvetica", 25))], #added font type and font size
			[sg.Text('https://github.com/abrignoni/ALEAPP', font=("Helvetica", 18))],#added font type and font size
			[sg.Text('Select the file type or directory of the target Android full file system extraction for parsing.', font=("Helvetica", 16))],#added font type and font size
			[sg.Radio('.Tar', "rad1", default=True, font=("Helvetica", 14)), sg.Radio('Directory', "rad1", font=("Helvetica", 14)), sg.Radio('.Zip', "rad1", font=("Helvetica", 14))], #added font type and font size
			[sg.Text('File:', size=(8, 1), font=("Helvetica", 14)), sg.Input(), sg.FileBrowse(font=("Helvetica", 12))], #added font type and font size
			[sg.Text('Directory:', size=(8, 1), font=("Helvetica", 14)), sg.Input(), sg.FolderBrowse(font=("Helvetica", 12))], #added font type and font size
			[sg.Checkbox('Generate CSV output (Additional processing time)', size=(50, 1), default=False, font=("Helvetica", 14))],
			[sg.Output(size=(100,40))], #changed size from (88,20)
			[sg.Submit('Process',font=("Helvetica", 14)), sg.Button('Close', font=("Helvetica", 14))] ] #added font type and font size
			

# Create the Window
window = sg.Window('ALEAPP', layout)
Example #22
0
	Juan Pablo Sanchez Magariños
'''
import config
import sopa
import PySimpleGUI as sg

def existe_archivo_de_configuracion():
	''' Para ver si existe la configuración me fijo si la función devuelve el elemento vacío que es cuando lo inicializa'''
	_,_,res = config.cargar_configuracion()
	cond = res != []
	return cond

color_fondo = config.colores(config.cargar_configuracion()[0])['splash']
sg.SetOptions(	background_color = color_fondo[1],
				text_element_background_color=color_fondo[1],
				element_background_color=color_fondo[1],
				text_color=color_fondo[0]
				)
menu_princ = [	['&Opciones', ['Configuración::Menu', 'Exit::Menu'  ]],    
				['&Ayuda', '&Acerca de...::Menu']
			]
layout = [
			[sg.Menu(menu_princ, key='Menu' )],
			[sg.Text('Sopa de Letras', font = ('Fixedsys',25), pad = (90,8),justification = 'center')],
			[sg.Button('',image_filename='img/jugar.png', image_size =(450, 210), image_subsample=1, border_width=0, 
				key='_jugar_', pad = (55,(8,55)), button_color = color_fondo)]
		]

window = sg.Window('Sopa de Letras en PySimpleGUI').Layout(layout)

while True:				 # Event Loop
def _github_issue_help():
    heading_font = '_ 12 bold underline'
    text_font = '_ 10'

    def HelpText(text):
        return sg.Text(text, size=(80, None), font=text_font)

    help_why = \
""" Let's start with a review of the Goals of the PySimpleGUI project
1. To have fun
2. For you to be successful

This form is as important as the documentation and the demo programs to meeting those goals.

The GitHub Issue GUI is here to help you more easily log issues on the PySimpleGUI GitHub Repo. """

    help_goals = \
""" The goals of using GitHub Issues for PySimpleGUI question, problems and suggestions are:
* Give you direct access to engineers with the most knowledge of PySimpleGUI
* Answer your questions in the most precise and correct way possible
* Provide the highest quality solutions possible
* Give you a checklist of things to try that may solve the problem
* A single, searchable database of known problems and their workarounds
* Provide a place for the PySimpleGUI project to directly provide support to users
* A list of requested enhancements
* An easy to use interface to post code and images
* A way to track the status and have converstaions about issues
* Enable multiple people to help users """

    help_explain = \
""" GitHub does not provide a "form" that normal bug-tracking-databases provide. As a result, a form was created specifically for the PySimpleGUI project.

The most obvious questions about this form are
* Why is there a form? Other projects don't have one?
* My question is an easy one, why does it still need a form?

The answer is:
I want you to get your question answered with the highest quality answer possible as quickly as possible.

The longer answer - For quite a while there was no form. It resulted the same back and forth, multiple questions comversation.  "What version are you running?"  "What OS are you using?"  These waste precious time.

If asking nicely helps... PLEASE ... please fill out the form.

I can assume you that this form is not here to punish you. It doesn't exist to make you angry and frustrated.  It's not here for any purpose than to try and get you support and make PySimpleGUI better. """

    help_experience = \
""" Not many Bug-tracking systems ask about you as a user. Your experience in programming, programming in Python and programming a GUI are asked to provide you with the best possible answer.  Here's why it's helpful.  You're a human being, with a past, and a some amount of experience.  Being able to taylor the reply to your issue in a way that fits you and your experience will result in a reply that's efficient and clear.  It's not something normally done but perhaps it should be. It's meant to provide you with a personal response.

If you've been programming for a month, the person answering your question can answer your question in a way that's understandable to you.  Similarly, if you've been programming for 20 years and have used multiple Python GUI frameworks, then you are unlikely to need as much explanation.  You'll also have a richer GUI vocabularly. It's meant to try and give you a peronally crafted response that's on your wavelength. Fun & success... Remember those are our shared goals"""

    help_steps = \
""" The steps to log an issue are:
1. Fill in the form
2. Click Post Issue """
    layout = [[sg.T('Goals', font=heading_font, pad=(0, 0))],
              [HelpText(help_goals)],
              [sg.T('Why?', font=heading_font, pad=(0, 0))],
              [HelpText(help_why)],
              [sg.T('FAQ', font=heading_font, pad=(0, 0))],
              [HelpText(help_explain)],
              [sg.T('Experience (optional)', font=heading_font)],
              [HelpText(help_experience)],
              [sg.T('Steps', font=heading_font, pad=(0, 0))],
              [HelpText(help_steps)], [sg.B('Close')]]
    sg.Window('GitHub Issue GUI Help', layout,
              keep_on_top=True).read(close=True)

    return
Example #24
0
def main():
    def GetCurrentTime():
        '''
        Get the current system time in milliseconds
        :return: milliseconds
        '''
        return int(round(time.time() * 1000))

    pback = PlayerGUI()

    button, values = pback.PlayerChooseSongGUI()
    if button != 'PLAY':
        g.MsgBoxCancel('Cancelled...\nAutoclose in 2 sec...',
                       auto_close=True,
                       auto_close_duration=2)
        exit(69)
    if values['device']:
        midi_port = values['device'][0]
    else:
        g.MsgBoxCancel('No devices found\nAutoclose in 2 sec...',
                       auto_close=True,
                       auto_close_duration=2)

    batch_folder = values['folder']
    midi_filename = values['midifile']
    # ------ Build list of files to play --------------------------------------------------------- #
    if batch_folder:
        filelist = os.listdir(batch_folder)
        filelist = [
            batch_folder + '/' + f for f in filelist
            if f.endswith(('.mid', '.MID'))
        ]
        filetitles = [os.path.basename(f) for f in filelist]
    elif midi_filename:  # an individual filename
        filelist = [
            midi_filename,
        ]
        filetitles = [
            os.path.basename(midi_filename),
        ]
    else:
        g.MsgBoxError('*** Error - No MIDI files specified ***')
        exit(666)

    # ------ LOOP THROUGH MULTIPLE FILES --------------------------------------------------------- #
    pback.PlayerPlaybackGUIStart(
        NumFiles=len(filelist) if len(filelist) <= 10 else 10)
    port = None
    # Loop through the files in the filelist
    for now_playing_number, current_midi_filename in enumerate(filelist):
        display_string = 'Playing Local File...\n{} of {}\n{}'.format(
            now_playing_number + 1, len(filelist), current_midi_filename)
        midi_title = filetitles[now_playing_number]
        # --------------------------------- REFRESH THE GUI ----------------------------------------- #
        pback.PlayerPlaybackGUIUpdate(display_string)

        # ---===--- Output Filename is .MID --- #
        midi_filename = current_midi_filename

        # --------------------------------- MIDI - STARTS HERE ----------------------------------------- #
        if not port:  # if the midi output port not opened yet, then open it
            port = mido.open_output(midi_port if midi_port else None)

        try:
            mid = mido.MidiFile(filename=midi_filename)
        except:
            print(
                '****** Exception trying to play MidiFile filename = {}***************'
                .format(midi_filename))
            g.MsgBoxError('Exception trying to play MIDI file:', midi_filename,
                          'Skipping file')
            continue

        # Build list of data contained in MIDI File using only track 0
        midi_length_in_seconds = mid.length
        display_file_list = '>> ' + '\n'.join([
            f for i, f in enumerate(filetitles[now_playing_number:]) if i < 10
        ])
        paused = cancelled = next_file = False
        ######################### Loop through MIDI Messages ###########################
        while (True):
            start_playback_time = GetCurrentTime()
            port.reset()

            for midi_msg_number, msg in enumerate(mid.play()):
                #################### GUI - read values ##################
                if not midi_msg_number % 4:  # update the GUI every 4 MIDI messages
                    t = (GetCurrentTime() - start_playback_time) // 1000
                    display_midi_len = '{:02d}:{:02d}'.format(
                        *divmod(int(midi_length_in_seconds), 60))
                    display_string = 'Now Playing {} of {}\n{}\n              {:02d}:{:02d} of {}\nPlaylist:'.\
                        format(now_playing_number+1, len(filelist), midi_title, *divmod(t, 60), display_midi_len)
                    # display list of next 10 files to be played.
                    pback.SliderElem.Update(t,
                                            range=(1, midi_length_in_seconds))
                    rc = pback.PlayerPlaybackGUIUpdate(display_string + '\n' +
                                                       display_file_list)
                else:  # fake rest of code as if GUI did nothing
                    rc = PLAYER_COMMAND_NONE
                if paused:
                    rc = PLAYER_COMMAND_NONE
                    while rc == PLAYER_COMMAND_NONE:  # TIGHT-ASS loop waiting on a GUI command
                        rc = pback.PlayerPlaybackGUIUpdate(display_string)
                        time.sleep(.25)

                ####################################### MIDI send data ##################################
                port.send(msg)

                # -------  Execute GUI Commands  after sending MIDI data ------- #
                if rc == PLAYER_COMMAND_EXIT:
                    cancelled = True
                    break
                elif rc == PLAYER_COMMAND_PAUSE:
                    paused = not paused
                    port.reset()
                elif rc == PLAYER_COMMAND_NEXT:
                    next_file = True
                    break
                elif rc == PLAYER_COMMAND_RESTART_SONG:
                    break

            if cancelled or next_file:
                break
        #------- DONE playing the song   ------- #
        port.reset()  # reset the midi port when done with the song

        if cancelled:
            break
    exit(69)
def main_open_github_issue():
    font_frame = '_ 14'
    issue_types = ('Question', 'Bug', 'Enhancement', 'Error Message')
    # frame_type = [[sg.Radio('Question', 1, size=(10,1), enable_events=True, k='-TYPE: QUESTION-'),
    #               sg.Radio('Bug', 1, size=(10,1), enable_events=True, k='-TYPE: BUG-')],
    #              [sg.Radio('Enhancement', 1, size=(10,1), enable_events=True, k='-TYPE: ENHANCEMENT-'),
    #               sg.Radio('Error Message', 1, size=(10,1), enable_events=True, k='-TYPE: ERROR`-')]]
    frame_type = [[sg.Radio(t, 1, size=(10, 1), enable_events=True, k=t)]
                  for t in issue_types]

    v_size = (15, 1)
    frame_versions = [
        [
            sg.T('Python', size=v_size),
            sg.In(sg.sys.version, size=(20, 1), k='-VER PYTHON-')
        ],
        [
            sg.T('PySimpleGUI', size=v_size),
            sg.In(sg.ver, size=(20, 1), k='-VER PSG-')
        ],
        [
            sg.T('tkinter', size=v_size),
            sg.In(sg.tclversion_detailed, size=(20, 1), k='-VER TK-')
        ],
    ]

    frame_platforms = [
        [sg.T('OS                 '),
         sg.T('Details')],
        [
            sg.Radio('Windows',
                     2,
                     sg.running_windows(),
                     size=(8, 1),
                     k='-OS WIN-'),
            sg.In(size=(8, 1), k='-OS WIN VER-')
        ],
        [
            sg.Radio('Linux',
                     2,
                     sg.running_linux(),
                     size=(8, 1),
                     k='-OS LINUX-'),
            sg.In(size=(8, 1), k='-OS LINUX VER-')
        ],
        [
            sg.Radio('Mac', 2, sg.running_mac(), size=(8, 1), k='-OS MAC-'),
            sg.In(size=(8, 1), k='-OS MAC VER-')
        ],
        [
            sg.Radio('Other', 2, size=(8, 1), k='-OS OTHER-'),
            sg.In(size=(8, 1), k='-OS OTHER VER-')
        ],
    ]

    frame_experience = [
        [sg.T('Optional Experience Info')],
        [sg.In(size=(4, 1), k='-EXP PROG-'),
         sg.T('Years Programming')],
        [sg.In(size=(4, 1), k='-EXP PYTHON-'),
         sg.T('Years Writing Python')],
        [sg.CB('Previously programmed a GUI', k='-CB PRIOR GUI-')],
        [sg.T('Share more if you want....')],
        [sg.In(size=(25, 1), k='-EXP NOTES-')]
    ]

    checklist = ((
        'Searched main docs for your problem', 'www.PySimpleGUI.org'
    ), (
        'Looked for Demo Programs that are similar to your goal ',
        'http://Demos.PySimpleGUI.org'
    ), ('If not tkinter - looked for Demo Programs for specific port', ''), (
        'For non tkinter - Looked at readme for your specific port if not PySimpleGUI (Qt, WX, Remi)',
        ''
    ), (
        'Run your program outside of your debugger (from a command line)', ''
    ), (
        'Searched through Issues (open and closed) to see if already reported',
        'http://Issues.PySimpleGUI.org'
    ), ('Tried using the PySimpleGUI.py file on GitHub. Your problem may have already been fixed vut not released.',
        ''))

    frame_checklist = [[
        sg.CB(c, k=('-CB-', i)),
        sg.T(t, k='-T{}-'.format(i), enable_events=True)
    ] for i, (c, t) in enumerate(checklist)]

    frame_details = [[
        sg.Multiline(size=(65, 10), font='Courier 10', k='-ML DETAILS-')
    ]]
    frame_code = [[
        sg.Multiline(size=(80, 10), font='Courier 8', k='-ML CODE-')
    ]]
    frame_markdown = [[
        sg.Multiline(size=(80, 10), font='Courier 8', k='-ML MARKDOWN-')
    ]]

    top_layout = [
        [
            sg.Col([[
                sg.Text('Open A GitHub Issue (* = Required Info)', font='_ 15')
            ]],
                   expand_x=True),
            sg.Col([[sg.B('Help')]])
        ],
        [
            sg.Frame('Title *', [[
                sg.Input(k='-TITLE-', size=(50, 1), font='_ 14', focus=True)
            ]],
                     font=font_frame)
        ],
        sg.vtop([
            sg.Frame('Platform *', frame_platforms, font=font_frame),
            sg.Frame('Type of Issue *', frame_type, font=font_frame),
            sg.Frame('Versions *', frame_versions, font=font_frame),
            sg.Frame('Experience', frame_experience, font=font_frame),
        ]),
        [
            sg.Frame('Checklist * (note that you can click the links)',
                     frame_checklist,
                     font=font_frame)
        ], [sg.HorizontalSeparator()],
        [
            sg.
            T(sg.SYMBOL_DOWN +
              ' If you need more room for details grab the dot and drag to expand',
              background_color='red',
              text_color='white')
        ]
    ]

    bottom_layout = [
        [
            sg.TabGroup([[
                sg.Tab('Details', frame_details),
                sg.Tab('Code', frame_code),
                sg.Tab('Markdown', frame_markdown)
            ]],
                        k='-TABGROUP-')
        ],
        # [sg.Frame('Details',frame_details, font=font_frame, k='-FRAME DETAILS-')],
        # [sg.Frame('Minimum Code to Duplicate',frame_code, font=font_frame, k='-FRAME CODE-')],
        [sg.Text(size=(12, 1), key='-OUT-')],
        [sg.B('Post Issue'),
         sg.B('Create Markdown Only'),
         sg.B('Quit')]
    ]

    layout = [[sg.Pane([sg.Col(top_layout), sg.Col(bottom_layout)])]]

    window = sg.Window('Open A GitHub Issue',
                       layout,
                       finalize=True,
                       resizable=True,
                       enable_close_attempted_event=False)
    for i in range(len(checklist)):
        window['-T{}-'.format(i)].set_cursor('hand1')
    window['-TABGROUP-'].expand(True, True, True)
    window['-ML CODE-'].expand(True, True, True)
    window['-ML DETAILS-'].expand(True, True, True)
    window['-ML MARKDOWN-'].expand(True, True, True)
    # window['-FRAME CODE-'].expand(True, True, True)
    # window['-FRAME DETAILS-'].expand(True, True, True)

    while True:  # Event Loop
        event, values = window.read()
        # print(event, values)
        if event in (sg.WINDOW_CLOSE_ATTEMPTED_EVENT, 'Quit'):
            if sg.popup_yes_no(
                    'Do you really want to exit?',
                    'If you have not clicked Post Issue button and then clicked "Submit New Issue" button '
                    'then your issue will not have been submitted to GitHub.'
                    'Do no exit until you have PASTED the information from Markdown tab into an issue?'
            ) == 'Yes':
                break
        if event == sg.WIN_CLOSED:
            break
        if event in ['-T{}-'.format(i) for i in range(len(checklist))]:
            webbrowser.open_new_tab(window[event].get())
        if event in issue_types:
            title = str(values['-TITLE-'])
            if len(title) != 0:
                if title[0] == '[' and title.find(']'):
                    title = title[title.find(']') + 1:]
                    title = title.strip()
            window['-TITLE-'].update('[{}] {}'.format(event, title))
        if event == 'Help':
            _github_issue_help()
        elif event in ('Post Issue', 'Create Markdown Only'):
            issue_type = None
            for itype in issue_types:
                if values[itype]:
                    issue_type = itype
                    break
            if issue_type is None:
                sg.popup_error('Must choose issue type')
                continue
            if values['-OS WIN-']:
                operating_system = 'Windows'
                os_ver = values['-OS WIN VER-']
            elif values['-OS LINUX-']:
                operating_system = 'Linux'
                os_ver = values['-OS LINUX VER-']
            elif values['-OS MAC-']:
                operating_system = 'Mac'
                os_ver = values['-OS MAC VER-']
            elif values['-OS OTHER-']:
                operating_system = 'Other'
                os_ver = values['-OS OTHER VER-']
            else:
                sg.popup_error('Must choose Operating System')
                continue
            checkboxes = [
                'X' if values[('-CB-', i)] else ' '
                for i in range(len(checklist))
            ]

            if not validate(values, checklist, issue_types):
                continue

            markdown = make_markdown(
                issue_type, operating_system, os_ver, 'tkinter',
                values['-VER PSG-'], values['-VER TK-'],
                values['-VER PYTHON-'], values['-EXP PROG-'],
                values['-EXP PYTHON-'],
                'Yes' if values['-CB PRIOR GUI-'] else 'No',
                values['-EXP NOTES-'], *checkboxes, values['-ML DETAILS-'],
                values['-ML CODE-'])
            window['-ML MARKDOWN-'].update(markdown)
            link = make_github_link(values['-TITLE-'],
                                    window['-ML MARKDOWN-'].get())
            if event == 'Post Issue':
                webbrowser.open_new_tab(link)
            else:
                sg.popup('Your markdown code is in the Markdown tab',
                         keep_on_top=True)

    window.close()
Example #26
0
    def PlayerChooseSongGUI(self):

        # ---------------------- DEFINION OF CHOOSE WHAT TO PLAY GUI ----------------------------
        with g.FlexForm('MIDI File Player',
                        auto_size_text=False,
                        default_element_size=(30, 1),
                        font=("Helvetica", 12)) as form:
            layout = [[
                g.Text('MIDI File Player',
                       font=("Helvetica", 15),
                       size=(20, 1),
                       text_color='green')
            ], [
                g.Text('File Selection', font=("Helvetica", 15), size=(20, 1))
            ],
                      [
                          g.Text('Single File Playback',
                                 justification='right'),
                          g.InputText(size=(65, 1), key='midifile'),
                          g.FileBrowse(size=(10, 1),
                                       file_types=(("MIDI files", "*.mid"), ))
                      ],
                      [
                          g.Text('Or Batch Play From This Folder',
                                 auto_size_text=False,
                                 justification='right'),
                          g.InputText(size=(65, 1), key='folder'),
                          g.FolderBrowse(size=(10, 1))
                      ],
                      [g.Text('_' * 250, auto_size_text=False, size=(100, 1))],
                      [
                          g.Text('Choose MIDI Output Device', size=(22, 1)),
                          g.Listbox(values=self.PortList,
                                    size=(30, len(self.PortList) + 1),
                                    key='device')
                      ],
                      [g.Text('_' * 250, auto_size_text=False, size=(100, 1))],
                      [
                          g.SimpleButton('PLAY',
                                         size=(12, 2),
                                         button_color=('red', 'white'),
                                         font=("Helvetica", 15),
                                         bind_return_key=True),
                          g.Text(' ' * 2, size=(4, 1)),
                          g.Cancel(size=(8, 2), font=("Helvetica", 15))
                      ]]

        self.Form = form
        return form.LayoutAndRead(layout)
Example #27
0
import subprocess
import sys
import PySimpleGUI as sg
"""
	Demo Program - Realtime output of a shell command in the window
		Shows how you can run a long-running subprocess and have the output
		be displayed in realtime in the window.
"""

sg.theme('Black')


def main():
    layout = [
        [
            sg.Button('Launch',
                      bind_return_key=True,
                      button_color=('white', 'springgreen4')),
            sg.Button('Exit', button_color=('white', 'black'))
        ],
        [sg.Output(size=(110, 30))],
        #[sg.T('Promt> '), sg.Input(key='-IN-', do_not_clear=False)],
        #[sg.Button('Run', bind_return_key=True), sg.Button('Exit')] ]
    ]

    window = sg.Window('Standalone PF RING', layout)

    while True:  # Event Loop
        event, values = window.read()
        # print(event, values)
        if event in (None, 'Exit'):
Example #28
0
    def PlayerPlaybackGUIStart(self, NumFiles=1):
        # -------  Make a new FlexForm  ------- #

        image_pause = './ButtonGraphics/Pause.png'
        image_restart = './ButtonGraphics/Restart.png'
        image_next = './ButtonGraphics/Next.png'
        image_exit = './ButtonGraphics/Exit.png'

        self.TextElem = g.T('Song loading....',
                            size=(70, 5 + NumFiles),
                            font=("Helvetica", 14),
                            auto_size_text=False)
        self.SliderElem = g.Slider(range=(1, 100),
                                   size=(50, 8),
                                   orientation='h',
                                   text_color='#f0f0f0')
        form = g.FlexForm('MIDI File Player',
                          default_element_size=(30, 1),
                          font=("Helvetica", 25))
        layout = [[
            g.T('MIDI File Player', size=(30, 1), font=("Helvetica", 25))
        ], [self.TextElem], [self.SliderElem],
                  [
                      g.ReadFormButton('PAUSE',
                                       button_color=g.TRANSPARENT_BUTTON,
                                       image_filename=image_pause,
                                       image_size=(50, 50),
                                       image_subsample=2,
                                       border_width=0),
                      g.T(' '),
                      g.ReadFormButton('NEXT',
                                       button_color=g.TRANSPARENT_BUTTON,
                                       image_filename=image_next,
                                       image_size=(50, 50),
                                       image_subsample=2,
                                       border_width=0),
                      g.T(' '),
                      g.ReadFormButton('Restart Song',
                                       button_color=g.TRANSPARENT_BUTTON,
                                       image_filename=image_restart,
                                       image_size=(50, 50),
                                       image_subsample=2,
                                       border_width=0),
                      g.T(' '),
                      g.SimpleButton(
                          'EXIT',
                          button_color=g.TRANSPARENT_BUTTON,
                          image_filename=image_exit,
                          image_size=(50, 50),
                          image_subsample=2,
                          border_width=0,
                      )
                  ]]

        form.LayoutAndRead(layout, non_blocking=True)
        self.Form = form
Example #29
0
import PySimpleGUI as sg

sg.Popup('Mi  primera ventanita', button_color=('black', 'red'))

sg.PopupYesNo('Mi  primera ventanita', button_color=('black', 'green'))

sg.PopupOKCancel('Mi  primera ventanita', button_color=('black', 'grey'))

texto = sg.PopupGetText('Titulo', 'Ingresá algo')
sg.Popup('Resultados', 'Ingresaste el siguiente texto: ', texto)
Example #30
0
# python3.8.2
import io
import PySimpleGUI as sg
from PIL import Image, ImageTk

# Practice with Event-Based Programming.
sg.theme('DarkAmber')
j_str = "Jester.png"

img = Image.open(j_str)
# First time opening of Image is tricky.
# This avoids RuntimeError: Too early to create image
bio = io.BytesIO()
img.save(bio, format="PNG")
j_img = bio.getvalue()
jester = sg.Image(data=j_img)
layout = [[sg.Text("Total Axis Manipulation")],
          [sg.Text("Axis 1"), sg.InputText()], [jester],
          [sg.Button('OK'), sg.Button('Cancel')]]
main_win = sg.Window('Inverted Dimension Multiplier', layout)

while True:
    event, values = main_win.read()
    if event in (None, 'Cancel'):
        break
    print('You entered ', values[0])
    if values[0] == 'x':
        img = img.transpose(Image.FLIP_LEFT_RIGHT)
        jester.update(data=ImageTk.PhotoImage(img))
        print('Here, have a horizontal flip.')
    if values[0] == 'y':