Ejemplo n.º 1
0
def download(*args):
    try:
        log = open('gslogs.txt', 'a')
        episode = args[2]
        latest_episode = check(args[0])

        if latest_episode.endswith('Season Finale'):
            latest_episode = latest_episode.replace('-', ' ')
            new_lat_epi = latest_episode.split()
            epi_join = '-'.join(new_lat_epi)

            if episode == epi_join[:10].lower():
                episode = epi_join

        while latest_episode == 'Connection failed':
            log.write('Connection error' + '\n')
            retry = messagebox.askretrycancel('Connection Error', 'Connection Failed. Reconnect and try again')
            if retry == True:
                continue
            else:
                break
        else:

            try:
                # checks to see if the requested episode is available
                num = latest_episode[8:11]
                if int(args[2][8:11]) > int(num):
                    retry = messagebox.showerror('Download Error',
                                                 'Episode not available. Use the Check button to make sure the episode is available')

                else:
                    # puts the required season and episode in the url to get the episode page
                    url_list = list(args[0])
                    season = args[1] + '/'
                    url_list.insert(-11, (season + episode + '/'))
                    download_page = make_request(''.join(url_list))
                    soup = bs4.BeautifulSoup(download_page.text, 'html.parser')
                    links = soup.select('.data a')  # gets the link for all downloadable episode formats
                    re_episode = links[0].get('href')

                    # checks to see if internet download manager is installed on the system. If it is, it uses IDM to download episode.

                    webbrowser.open(re_episode)  # opens webbrowser to download requested episode



            except(ValueError, IndexError) as er:
                messagebox.showerror('Download Error',
                                     'Episode not available. Use the Check button to make sure the episode is available')

    except (ConnectionResetError, requests.packages.urllib3.exceptions.ProtocolError,
            requests.exceptions.ChunkedEncodingError,
            requests.exceptions.ConnectionError, ConnectionError,
            requests.packages.urllib3.exceptions.MaxRetryError,
            requests.packages.urllib3.exceptions.NewConnectionError, gaierror) as e:
        messagebox.askretrycancel('Connection Error', 'Connection failed. Reconnect and try again')
    log.close()
Ejemplo n.º 2
0
def tv(*args):
    global serie_entry
    global season_entry
    global season_max
    global max_seas
    global max_epi

    if int_var.get() != 1:
        seri = serie_entry.get()

        with open('series.txt', 'r') as urls:
            for url in urls:
                if seri.lower() in url:
                    check(url)

                    while season_max == None:
                        messageBox = messagebox.askretrycancel('Connection Error',
                                                               'Connection Failed. Reconnect and try again')

                        if messageBox == True:
                            continue
                        else:
                            break
                    else:
                        try:
                            new_seasons = ['Season-0{}'.format(i) if len(str(i)) == 1 else 'Season-{}'.format(i) for i
                                           in range(1, season_max)]

                            season_entry['values'] = new_seasons[0:]
                            season_entry.current(0)
                        except TypeError:
                            pass
    else:
        seri = serie_entry.get().lower()
        if '.' in seri or "'" in seri:
            seri = seri.replace('.', '-')
            seri = seri.replace("'", '-')

        with open('today.txt', 'r') as today:
            series = [serie_url.strip('\n') for serie_url in today.readlines() if seri in serie_url]
            try:

                while hdCheck(series[0]) == 'Connection failed':
                    sea = messagebox.askretrycancel('Connection Error', 'Connection Failed. Reconnect and try again')
                    if sea == True:
                        continue
                    else:
                        break
                else:
                    season_entry['values'] = ['S0{}'.format(i) if len(str(i)) == 1 else 'S{}'.format(i) for i in
                                              range(1, max_seas)][0:]
                    season_entry.current(0)
            except (TypeError, IndexError) as e:
                pass
Ejemplo n.º 3
0
def test3():

	ok = messagebox.askretrycancel("Title","Installation failed, try again?")
	if ok == True:
		print(ok)
	else:
		print(ok)
Ejemplo n.º 4
0
 def gather_data():
     """
     Gather the data from the text entries and convert it to floating point numbers
     :return:
     """
     plant.data.append(get_ph.get())
     plant.data.append(get_soil_temperature.get())
     plant.data.append(get_soil_moisture.get())
     plant.data.append(get_illuminance.get())
     plant.data.append(get_env_temperature.get())
     plant.data.append(get_env_humidity.get())
     try:
         plant.data = [float(i) for i in plant.data]
     except ValueError:
         answer = messagebox.askretrycancel(
             "Question", "Incorrect input, try again?")
         if answer:
             frame_2.destroy()
             get_data_input()
         else:
             frame_2.destroy()
             self.log += "Incorrect input @[" + str(
                 time.perf_counter()) + "]"
             print("Log: Incorrect input @[" +
                   str(time.perf_counter()) + "]")
             self.gui_init()
Ejemplo n.º 5
0
 def action_message(self, message_type=None, **kwargs):
     '''Generic message box
     message_type can be one of:
         'showinfo'  (default)
         'showwarning'
         'showerror'
         'askretrycancel'
     Parameter options are:
         title='This is a message box',
         message='This is the message',
         detail='Some more details',
     '''
     if not message_type:
         message = messagebox.showinfo(parent=self, **kwargs)
     elif 'askretrycancel' in message_type:
         message = messagebox.askretrycancel(parent=self, **kwargs)
     elif 'showerror' in message_type:
         message = messagebox.showerror(parent=self, **kwargs)
     elif 'showwarning' in message_type:
         message = messagebox.showwarning(parent=self, **kwargs)
     elif 'showinfo' in message_type:
         message = messagebox.showinfo(parent=self, **kwargs)
     else:
         raise ValueError('message_type must be one of:\t\nshowinfo\t'
                          '(default)\n\t'
                          'showwarning\n\t'
                          'showerror\n\t'
                          'askretrycancel')
     return message
Ejemplo n.º 6
0
def ImportPortfolio():
    """File -> Portfolio
    Read the portfolio from a file"""

    with open(PORTFOLIO, 'w') as f:
        portfolio = GetPortfolio()
        keys = portfolio.keys()
        count = 1
        for stock in sorted(keys):
            if portfolio[stock]['units'] > 0.1:
                found = False
                while not found:
                    symbol = askstring('Symbols',
                                       '(%d/%d) Enter symbol for:\n%s' % \
                                       (count, len(keys), stock))
                    if symbol != None:
                        price = GetPriceForSymbol(symbol)

                        if price > 0.0:
                            if askyesno(symbol, 'Is %.2f correct?' % (price * 0.01)):
                                scaling = 0.01
                            else:
                                scaling = 1.0
                          
                            f.write(Stock(symbol, stock, 'TICKER', 0.01, 0.00, '20130811202000', scaling ).ToCSV())
                            found = True
                        else:
                            if not askretrycancel('Symbols',
                                                  'Cannot find symbol %s' % \
                                                  symbol):
                                found = False
                    else:
                        found = True
                count += 1
Ejemplo n.º 7
0
def getQuestions():
    answer = messagebox.askokcancel("Question",
                                    "Do you want to open this file?")
    answer = messagebox.askretrycancel("Question",
                                       "Do you want to try that again?")
    answer = messagebox.askyesno("Question", "Do you like Python?")
    answer = messagebox.askyesnocancel("Question", "Continue playing?")
Ejemplo n.º 8
0
def cmd():
    '''弹框提示'''
    global n
    global str_var
    n += 1
    if n == 1:
        r = messagebox.askokcancel('消息框', 'askokcancel')
        print('askokcancel:', r)
        str_var.set('askquestion')
    elif n == 2:
        r = messagebox.askquestion('消息框', 'askquestion')
        print('askquestion:', r)
        str_var.set('askyesno')
    elif n == 3:
        r = messagebox.askyesno('消息框', 'askyesno')
        print('askyesno:', r)
        str_var.set('askretrycancel')
    elif n == 4:
        r = messagebox.askretrycancel('消息框', 'askretrycancel')
        print('askretrycancel:', r)
        str_var.set('showerror')
    elif n == 5:
        r = messagebox.showerror('消息框', 'showerror')
        print('showerror:', r)
        str_var.set('showinfo')
    elif n == 6:
        r = messagebox.showinfo('消息框', 'showinfo')
        print('showinfo:', r)
        str_var.set('showwarning')
    else:
        r = messagebox.showwarning('消息框', 'showwarning')
        print('showwarning:', r)
        str_var.set('askokcancel')
        n = 0
Ejemplo n.º 9
0
    def _clear_data_base(self):
        var = tm.askretrycancel("Are you sure?")

        if var == True:
            global _clear_database
            _clear_database = var
            root.destroy()
Ejemplo n.º 10
0
def hddownload():
    global int_var
    global serie_entry
    global season_entry
    global episode_entry

    try:
        log = open('gslogs.txt', 'a')
        with open('today_epi.txt', 'r') as epi:
            today_list = [ep.strip('\n') for ep in epi.readlines()]
        seri = tvres()
        if '.' in seri or "'" in seri:
            seri = seri.replace('.', '-')
            seri = seri.replace("'", '-')

        if int_var.get() == 1:
            for series in today_list:
                if tvres() in series:
                    try:
                        messagebox.showinfo('Download',
                                            'Your browser will be launched and your download will begin shortly. Please be patient')
                        while todaySeries(series, seaS() + epiSeas()) == 'Connection failed':
                            retry = messagebox.askretrycancel('Connection Error',
                                                              'Connection failed. Reconnect and try again')
                            if retry == True:
                                continue
                            else:
                                break
                    except selenium.common.exceptions.ElementNotVisibleException:
                        messagebox.showinfo('Done', 'Please click the skip button')
    except IndexError as wire_error:
        log.write('Wire.exe not in PATH' + '\n')
        raise IndexError()
        messagebox.showwarning('File not found', 'Please add the selenium directory to your system PATH')
    log.close()
def divya():
    ans = tsmg.askretrycancel('divya se dosti karoge',
                              'sorrt diviya nahi manegi appki dost')
    if ans:
        print('retry karne ka koi faeda nhi he')
    else:
        print('shi he chod diya nhi to bohot petthe')
Ejemplo n.º 12
0
def guess_letter(ch):
    global userans,qword,miss,life,imgno
    if (ch.isalpha() and (ch not in userans) and (ch not in miss)):
        if ch not in qword:
            miss.append(ch)
            life-=1
            imgno+=1
            canvas.create_image(0, 0, image = imagelist[imgno], anchor = NW)
            if(life==0):
                response=messagebox.askretrycancel('Game Over','you lose')
                if(response):
                    readygame()
                else:
                    root.destroy()
            
        while( ch in qword):
            index=qword.index(ch)
            userans[index]=ch
            qword[index]='%'
            updblank(userans)
            if('_' not in userans):
                messagebox.showinfo('Won','You Guessed all letters correctly')
                readygame()
    else:
        pass
    print("qword=",qword)
    print("userans=",userans)
    print("miss=",miss)
    print("------------")
Ejemplo n.º 13
0
def askretrycancelbox():
    result = messagebox.askretrycancel("Intell-eyes",
                                       "Your facebook password is wrong!")
    if result == true:
        print("Retrying enter your password here!")
    else:
        print("Don't you use password")
Ejemplo n.º 14
0
def clicked03():
    if (rb_selected.get() == 1):
        # Needs import messagebox above
        messagebox.showinfo('Message Box Title', 'Message Box Content - Info')
    elif (rb_selected.get() == 2):
        # Needs import messagebox above
        messagebox.showwarning('Message Box Title',
                               'Message Box Content - Warning')
    elif (rb_selected.get() == 3):
        # Needs import messagebox above
        messagebox.showerror('Message Box Title',
                             'Message Box Content - Error')

    progress.step(10)
    YesNoTrueFalse = messagebox.askquestion(
        'Message Box Title', 'Message Box Content - askquestion')
    progress.step(10)
    YesNoTrueFalse = messagebox.askyesno('Message Box Title',
                                         'Message Box Content - askyesno')
    progress.step(10)
    OkCancelTrueFalse = messagebox.askokcancel(
        'Message Box Title', 'Message Box Content - askokcancel')
    progress.step(10)
    RetryCancelTrueFalse = messagebox.askretrycancel(
        'Message Box Title', 'Message Box Content - askretrycancel')
    progress.step(10)

    YesNoCancelTrueFalseNone = messagebox.askyesnocancel(
        'Message Box Title', 'Message Box Content - askyesnocancel')
    progress.step(10)
Ejemplo n.º 15
0
def retrycancel():
    response = msgbox.askretrycancel(
        "Retry / Cancel", "It's error is temporary. How about try again?")
    if response == 1:
        print("Retry")
    elif response == 0:
        print("Cancel")
 def nemonicos(self):
     direccion = "nemonicos.nem"
     try:
         archivo = open(direccion, "r")
     except IOError:
         root = Tk()
         root.withdraw()
         direccion = ""
         while not direccion:
             if messagebox.askyesno(
                     message=
                     "El archivo nemonicos.nem no existe en el directorio por default, ¿desea buscarlo en otro directorio?",
                     title="No se encontro el archivo nemonicos.nem"):
                 direccion = askopenfilename(initialdir="./",
                                             filetypes=[("NEM", "*.nem")])
                 if not direccion:
                     if not messagebox.askretrycancel(
                             message=
                             "No se selecciono ningun archivo, ¿Desea reintentarlo?",
                             title="No se selecciono archivo"):
                         return False
         self.listaNemonicos.clear()
         archivo = open(direccion, "r")
         for linea in archivo.readlines():
             linea = linea.strip()
             if not linea.startswith(self.COMENTARIO):
                 linea = linea.split(self.SEPARADOR_COMA)
                 self.listaNemonicos.append(linea)
     else:
         self.listaNemonicos.clear()
         for linea in archivo.readlines():
             linea = linea.strip()
             if not linea.startswith(self.COMENTARIO):
                 linea = linea.split(self.SEPARADOR_COMA)
                 self.listaNemonicos.append(linea)
Ejemplo n.º 17
0
    def getCI_Atual(self):
        flag = False
        while flag == False:

            try:
                _path = os.path.abspath(os.path.join(self.pathLocation, self.ano, f"{self.meses[strftime('%B')]}.cfg"))
                with open(_path, 'r', encoding=ENCODING) as file:
                    atual = file.readline().rstrip()

                return atual
            except IOError:

                message = """Arquivo "%s" não localizado na pasta "%s"!""" % (
                    self.meses[strftime("%B")],
                    self.ano
                )
                if messagebox.askretrycancel(parent=self.pedido.getFrame(),
                                             title="Erro!", message=message):
                    # Retry
                    flag = False

                else:
                    # Cancel
                    # C.I sempre será um numero positivo,
                    # por isso retorna negativo para ERROR!!
                    return -667
Ejemplo n.º 18
0
    def save_key(self):
        fname = filedialog.asksaveasfilename(parent=self,
                                             title='Save Key File',
                                             filetypes=(("secret key",
                                                         "*.pri"),
                                                        ("all files", "*.*")))
        if len(fname) == 0:
            return
        negpos = fname.rfind('.')
        if negpos == -1 or negpos + 4 < len(fname):
            fname += '.pri'
        mh = hashlib.new('ripemd160')
        passwd0 = PasswdInput(self, self.glob.mfont).show()
        passwd1 = PasswdInput(self, self.glob.mfont,
                              text="Renter Password").show()
        while passwd0 != passwd1 and mesgbox.askretrycancel(
                "Error", "Password Confirmation Failed!"):
            passwd0 = PasswdInput(self, self.glob.mfont).show()
            passwd1 = PasswdInput(self,
                                  self.glob.mfont,
                                  text="Renter Password").show()
        if passwd0 != passwd1:
            mesgbox.showwarning("Warning", "Keys Not Saved")
            return

        mh.update(passwd0.encode('utf-8'))
        passwd = mh.digest()
        self.glob.save_key(fname, passwd[:16])
Ejemplo n.º 19
0
 def login(self, player):
     i = 3
     while i >= 0:
         pin = dlg.askstring("pin", "enter your pin", show="*")
         if not pin:
             self.reset_cur_player()
             self.waiting_player_list.set('')
             return False
         i = i - 1
         if not self.gym.check_player(player, pin):
             if i > 0:
                 if not mb.askretrycancel('wrong pin', 'wrong pin, retry?'):
                     self.reset_cur_player()
                     self.waiting_player_list.set('')
                     return False
             else:
                 mb.showerror(
                     "wrong pin",
                     "3 attempts failed. Please talk to front desk.")
                 self.reset_cur_player()
                 self.waiting_player_list.set('')
                 return False
         else:
             return True
     return False
Ejemplo n.º 20
0
def popup(root):
    response = messagebox.showinfo('My Pop-Up', 'Hello World')
    label = createLabel(root, f'showinfo: { response }')
    label.pack()
    response = messagebox.showwarning('My Pop-Up', 'Hello World')
    label = createLabel(root, f'showwarning: { response }')
    label.pack()
    response = messagebox.showerror('My Pop-Up', 'Hello World')
    label = createLabel(root, f'showerror: { response }')
    label.pack()
    response = messagebox.askquestion('My Pop-Up', 'Hello World')
    label = createLabel(root, f'askquestion: { response }')
    label.pack()
    response = messagebox.askokcancel('My Pop-Up', 'Hello World')
    label = createLabel(root, f'askokcancel: { response }')
    label.pack()
    response = messagebox.askretrycancel('My Pop-Up', 'Hello World')
    label = createLabel(root, f'askretrycancel: { response }')
    label.pack()
    response = messagebox.askyesno('My Pop-Up', 'Hello World')
    label = createLabel(root, f'askyesno: { response }')
    label.pack()
    response = messagebox.askyesnocancel('My Pop-Up', 'Hello World')
    label = createLabel(root, f'askyesnocancel: { response }')
    label.pack()
Ejemplo n.º 21
0
def divya():
    ans = tmsg.askretrycancel("Divya se dosti karlo",
                              "Sorry divya nahi banegi aapki dost")
    if ans:
        print("Retry karne par bhi kuch nahi hoga")
    else:
        print("Bohot bhadiya bahi cancel kar diya varna pit-te")
Ejemplo n.º 22
0
def retrycancel():
    response = msgbox.askretrycancel(
        "재시도 / 취소", "일시적인 오류입니다. 다시 시도하시겠습니까?")  # 사용자에게 retry, cancel을 물어봄
    if response == 1:  # 재시도
        print("재시도")
    else:  # 취소
        print("취소")
Ejemplo n.º 23
0
 def submit_button_user(self):
     file_list = os.listdir(os.getcwd())
     username = self.username.get() + '.txt'
     if username in file_list:
         # Password Label
         fontStyle = tkf.Font(family="Arial", size=10)
         self.lbl2 = Label(self.master,
                           text="Enter Password",
                           font=fontStyle)
         self.lbl2.place(x=0, y=170)
         # Password Entry
         self.password = Entry(self.master, width=40)
         self.password.place(x=130, y=170)
         self.lbl3 = Label(self.master,
                           text="Re-Enter Password",
                           font=fontStyle)
         self.lbl3.place(x=0, y=200)
         # Password Entry
         self.password_re = Entry(self.master, width=40)
         self.password_re.place(x=130, y=200)
         # Submit Button
         self.submit_but_pass = Button(self.master,
                                       text="SUBMIT",
                                       command=self.update_password)
         self.submit_but_pass.place(x=140, y=250, width=120)
     else:
         c = tkm.askretrycancel("Change Password Error",
                                "User Doesn't Exist")
         if not c:
             self.master.destroy()
Ejemplo n.º 24
0
def false_warning():
    global response
    response = messagebox.askretrycancel("WARNING!", "SALAH WOI")
    if response == True:
        start()
    else:
        root.quit()
Ejemplo n.º 25
0
def retry():
    value = tmsg.askretrycancel("Fail", "Application Fail")
    if value == True:
        value = "Retrying"
    else:
        value = "Close Application"
    tmsg.showinfo("Status", value)
Ejemplo n.º 26
0
    def excel_cmp(self):
        if self.file_1.get() == self.file_2.get():
            responses = messagebox.askretrycancel(title='Wrong',
                                                  message='请不要选择同一个文件!')
        # print('confirm')
        # try:
        temp = xlcmp.XlCmp(
            self.file_1.get(),
            self.file_2.get())  #这里要捕获异常,捕获文件占用的异常,并且弹出警告;其它的异常需要打印出来
        if temp.same:
            response = messagebox.showinfo(title='Nice', message='数据一致!')
            pass  #表示数据一致
        else:
            # print(temp.diff)
            # print('different!')
            workbook = xlwt.Workbook()
            pattern = xlwt.Pattern()  # Create the Pattern
            pattern.pattern = xlwt.Pattern.SOLID_PATTERN  # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
            pattern.pattern_fore_colour = 5  # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
            style = xlwt.XFStyle()  # Create the Pattern
            style.pattern = pattern  # Add Pattern to Style
            for k, v in temp.diff.items():
                worksheet = workbook.add_sheet(k)
                for i in v:
                    worksheet.write(i[0], i[1], i[2], style)

            download = messagebox.askyesno(title='下载', message='是否下载校验结果?')
            if download:
                here = tkinter.filedialog.asksaveasfilename(
                    filetypes=[('Excel文件', '.xls')])  #获取保存地址
                here = here + '.xls'
                # print(here)
                workbook.save(here)  #保存文件
            pass  #弹出窗口下载文件
Ejemplo n.º 27
0
    def __init__(self, root):
        self.return_value = ""
        self.root = root
        self.status = tk.StringVar()
        self.status.set("Building up connection...")

        try:
            self.client = seafileapi.connect(server=SERVER,
                                             username=USERNAME,
                                             password=PASSWORD)
        except:
            answer = messagebox.askretrycancel(
                "Connection Error!",
                "The internet-connection could not be established!" +
                " Please check your connection and hit retry. Or upload the annotation-results"
                +
                "by hand. They are in the .tmp Folder where the .exe file is")
            if answer is None:
                exit(1)
            elif answer == "retry":
                self.__init__(root)
                return
        self.repo_list = [rp.name for rp in self.client.repos.list_repos()]
        self.repo = self.client.repos.get_repo(REPOSITORY)
        self.current_folders = self.repo.list_directories('/')
        self.status = tk.StringVar()
        self.status.set("Connected to server...")
        self.label = tk.Label(self.root, textvariable=self.status)
        self.label.pack()
Ejemplo n.º 28
0
def trycancel():
    response = msg.askretrycancel("재시도 / 취소 ", "일시적인 오류입니다. 다시시도하시겠습니까 ? ")
    print("응답 : ", response) # True False None -> 예 :1 아니오 :0  그외
    if response == 1:
        print("재시도")
    elif response == 0:
        print(" 취소 ")
Ejemplo n.º 29
0
def retryorskip(target_file_nm):
    # ********************************************************************************************************
    # * Set up logging
    # * To turn on logging, set root_logger.disabled = False
    # * To turn off logging, set root_logger.disabled = True
    # ********************************************************************************************************
    root_logger = logging.getLogger()
    root_logger.disabled = True  # Set to false to see debugging info
    logging.basicConfig(level=logging.DEBUG,
                        format=' %(asctime)s - %(levelname)s - %(message)s')

    if root_logger.disabled == False:
        file_name = inspect.stack()[0][
            3]  # This is slow, so only run it when logging
        called_from = lambda n=1: sys._getframe(n + 1).f_code.co_name
        logging.debug('Start of ' + file_name + ' function' +
                      " Called from: " + called_from.__module__)

    TF = (messagebox.askretrycancel(
        "Rename Error", "Need to rename " + target_file_nm + '\n' +
        "File my be in use. Retry?"))
    if TF:
        return return_retry()
    else:
        return return_skip()
Ejemplo n.º 30
0
def main():
    root = Tk()
    root.withdraw()
    direccion = ""
    """FINAL"""
    while not direccion:
        direccion = askopenfilename(initialdir="./",
                                    filetypes=[("ASM", "*.asm")])
        if not direccion:
            if not messagebox.askretrycancel(
                    message=
                    "No se selecciono ningun archivo, ¿Desea reintentarlo?",
                    title="No se selecciono archivo"):
                return
    """PARA DEBUG"""
    # direccion = ".\Practicas\Practica_01\codigoFuente\prueba.asm"
    """PARA PRUEBAS DIRECTAS DE ARCHIVO"""
    # direccion = "prueba.asm"

    archivo = open(direccion, "r")

    analizador = AnalizadorInstruccion()

    for linea in archivo.readlines():
        (etiqueta, nemonico, operadores,
         comentarios) = analizador.analizarInstruccion(linea)
        # print(analizador.analizarInstruccion(linea))
        imprimir(linea, etiqueta, nemonico, operadores, comentarios)

    archivo.close()
 def directivas(self):
     direccion = "src/directivas.dir"
     try:
         archivo = open(direccion, "r")
     except IOError:
         root = Tk()
         root.withdraw()
         direccion = ""
         while not direccion:
             if messagebox.askyesno(
                     message=
                     "El archivo directivas.dir no existe en el directorio por default, ¿desea buscarlo en otro directorio?",
                     title="No se encontro el archivo directivas.dir"):
                 direccion = askopenfilename(initialdir="./src/",
                                             filetypes=[("DIR", "*.dir")])
                 if not direccion:
                     if not messagebox.askretrycancel(
                             message=
                             "No se selecciono ningun archivo, ¿Desea reintentarlo?",
                             title="No se selecciono archivo"):
                         return False
             else:
                 return
         self.listaDirectivas.clear()
         archivo = open(direccion, "r")
         for linea in archivo.readlines():
             linea = linea.strip()
             self.listaDirectivas.append(linea)
     else:
         self.listaDirectivas.clear()
         for linea in archivo.readlines():
             linea = linea.strip()
             self.listaDirectivas.append(linea)
Ejemplo n.º 32
0
def start_timer():
    global counter, cpm
    timer_label.config(text=counter)
    if counter > 0:
        counter -= 1
        timer = window.after(1000, start_timer)
    else:
        timer_label.config(text="00")
        game_over_label.config(
            text=
            f"Time's Up!\nYou typed {cpm} characters correct\nYour score is {cpm/5} WPM"
        )
        retry = messagebox.askretrycancel("Time's Up!",
                                          "Do you want to retry?")
        if retry:
            cpm = 0
            missed = 0
            counter = 60
            timer_label.config(text=counter)
            game_over_label.config(
                text="Start the timer and \nafter typing the word press Enter")
            generate_word()
            player_entry.delete(0, END)
        else:
            window.quit()
def oro():
    ans = tmsg.askretrycancel("Text")
    if ans:
        print("TXT1")

    else:
        print("TXT2")
Ejemplo n.º 34
0
def check(New_User_Name, New_Password
          ):  #check for empty fields and then for username uniqueness

    if New_Password != '' and New_User_Name != '':  # avoiding empty fields

        with open('UserNames.txt', 'r+') as UserName_check:
            if os.stat("UserNames.txt").st_size != 0:  # to check empty file
                if New_User_Name in UserName_check.readlines()[0].split(','):
                    msgbox.askretrycancel("Error",
                                          "This UserName already exist")
                    return False
            return True

    else:
        msgbox.showinfo('Empty Fields',
                        'You left UserName/Password field empty')
Ejemplo n.º 35
0
def main():
    # 为了不让空窗口出现,必须导入主Tkinter模块并实例化顶层Tk对象.然后通过调用withdraw()让对象不可见
    tk = tkinter.Tk()
    tk.withdraw()  # 去掉空窗口

    print(dir(mb))

    # 注意,一些函数返回字符串,比如ok,而其他函数则返回布尔结果.最好在交互式提示符上实验它们,以便知道返回值的类型.
    # 注意,当出现Cancel时,单击它会返回None
    mb.showinfo("Title", "Your message here")
    mb.showerror("An Error", "Oops!")
    mb.showwarning("Title", "This may not work...")
    mb.askyesno("Title", "Do you love me?")
    mb.askokcancel("Title", "Are you well?")
    mb.askquestion("Title", "How are you?")
    mb.askretrycancel("Title", "Go again?")
    mb.askyesnocancel("Title", "Are you well?")
Ejemplo n.º 36
0
 def projDown(e=None, yx=None):
     if not yx:
         yx = sd.askinteger('Enter Project ID', 'Enter the project ID that can be found at the end of the URL of a project.')
     s = downloadProject(yx)
     if s['status'] == 'error':
         try:
             s['stack']
         except:
             stack = True
         else:
             stack = s['stack']
         if stack:
             r = db.askretrycancel('Project Downloader', 'Error: Could not download project: ' + str(s['error']) + '\nStacktrace:\n' + str(traceback.format_exc()) + '\nError Code ' + str(error_code) + ': ' + error_codes[s['code']][0] + '. ' + error_codes[s['code']][1])
         else:
             r = db.askretrycancel('Project Downloader', 'Error: Could not download project: ' + str(s['error']) + '\nError Code ' + str(s['code']) + ': ' + error_codes[s['code']][0] + '. ' + error_codes[s['code']][1])
         if r:
             projDown(yx=yx)
Ejemplo n.º 37
0
def askRetryCancel(message):
    if has_tk():
        if py3:
            from tkinter.messagebox import askretrycancel
        else:
            from tkMessageBox import askretrycancel
        response = askretrycancel(TK_TITLE, message)
        tk_flush()
        return response
Ejemplo n.º 38
0
 def messages(self):
     print("info", showinfo("Spam", "Egg Information"))
     print("warning", showwarning("Spam", "Egg Warning"))
     print("error", showerror("Spam", "Egg Alert"))
     print("question", askquestion("Spam", "Question?"))
     print("proceed", askokcancel("Spam", "Proceed?"))
     print("yes/no", askyesno("Spam", "Got it?"))
     print("yes/no/cancel", askyesnocancel("Spam", "Want it?"))
     print("try again", askretrycancel("Spam", "try again?"))
Ejemplo n.º 39
0
    def process(self, validate_only=False):
        filename = self.askopen()

        #messagebox.showwarning('hello', 'validating')
        #messagebox.showinfo('hello', 'validating')
        #messagebox.showerror('hello', 'validating')
        while messagebox.askretrycancel('question', 'another'):
            pass

        if not validate_only:
            print('processing also')
Ejemplo n.º 40
0
 def setDefaultDomainInner():
     if validateDomain(domain):
         configurations[2] = domain.get()
         updateConf(configurations)
         domain.set(domain.get())
         messagebox.showinfo(title='Successful operation',
                             message='Default server domain address changed sucessfully.')
         close(root, t)
     else:
         flag = messagebox.askretrycancel(
             title='Domain address invalidation', message='Domain address is not valid.', icon='error')
         if flag:
             e.delete(0, 'end')
             e.focus()
Ejemplo n.º 41
0
 def setDefaultIPInner():
     if validateIP(ip):
         configurations[0] = ip.get()
         updateConf(configurations)
         ip.set(ip.get())
         messagebox.showinfo(title='Successful operation',
                             message='Default server IP address changed sucessfully.')
         close(root, t)
         goForDomain()
     else:
         flag = messagebox.askretrycancel(
             title='IP address invalidation', message='IP address is not valid.', icon='error')
         if flag:
             e.delete(0, 'end')
             e.focus()
Ejemplo n.º 42
0
def update_list():
    while grab_episodes() == 'Connection Failed':
        retry = messagebox.askretrycancel('Connection Error', 'Connection Failed. Reconnect and try again')
        if retry == True:
            continue
        else:
            break
    else:

        with open('today_epi.txt', 'w') as t_epi, open('today.txt', 'w') as today, open('episodes.txt',
                                                                                        'w') as epi, open('series.txt',
                                                                                                          'w') as series, open(
                'episode_new.txt', 'r') as file, open('series_new.txt', 'r') as epis, open('today_new.txt',
                                                                                           'r') as today1, open(
                'today_epi_new.txt', 'r') as today_epi_n:
            for lines in today_epi_n.readlines():

                if ':-' in lines or "'" in lines:
                    lines = lines.replace(':-', '-')
                    lines = lines.replace("'", '-')
                    t_epi.write(lines.lower())

                elif '.-' in lines:
                    lines = lines.replace('.-', '-')
                    t_epi.write(lines.lower())

                elif '.' in lines:
                    lines = lines.replace('.', '-')
                    t_epi.write(lines.lower())

                else:
                    t_epi.write(lines.lower())

            for t_lines in today1.readlines():
                today.write(t_lines.lower())

            for f_lines in file.readlines():
                epi.write(f_lines.lower())

            for e_lines in epis.readlines():
                series.write(e_lines.lower())

        files = ['episode_new.txt',
                 'series_new.txt',
                 'today_new.txt',
                 'today_epi_new.txt']
        for txts in files:
            os.remove(txts)
Ejemplo n.º 43
0
def askInternetLogon(parent, url, quotedUrl, dialogCaption, dialogText, untilDoneEvent, result):
    # received Html suggests url may require web page logon (due to receivedHtml)
    r = messagebox.askyesnocancel(dialogCaption, dialogText)
    if r is None:
        result.append("cancel")
    elif r == False:
        result.append("no")
    else:
        import webbrowser
        webbrowser.open(quotedUrl, new=1, autoraise=True)
        r = messagebox.askretrycancel(dialogCaption,
                                      _("After logging on (by web browser, if applicable) click 'retry' to reload web file"))
        if r:
            result.append("retry")
        else:
            result.append("cancel")
    untilDoneEvent.set()
Ejemplo n.º 44
0
    def deleteAcc(*args):
        account = []
        accName = aName.get()
        create_table()
        for row in cursor.execute("SELECT accName FROM User_Accounts "):
            account.append(row)
        if (accName,) not in account:
            exists = 0
            if exists == 0:
                retry = messagebox.askretrycancel(message='This account does not exist',
	               icon='error', title='Error', parent = window2)
                if retry>0:
                    aName.get()
                    aName.set('')
                    delete_entry.focus()                    
                else:
                    aName.get()
                    aName.set('')
                    D_destroy()
        elif accName:
            question = messagebox.askyesno(message='Are you sure you want to delete this account?',
	               icon='question', title='Delete?', parent = window2)
            if question < 1:
                aName.get()
                aName.set('')
                delete_entry.focus()
            else:
                aName.get()
                aName.set('')
                delete_entry.focus()
                cursor.execute("delete from User_Accounts where accName = ? ", [(accName)])
                conn.commit()
                after_d = []
                
                for row in cursor.execute("SELECT accName FROM User_Accounts "):
                        after_d.append(row)
                if len(after_d)==1 and question == 1:
                    messagebox.showinfo(message='You have successfully deleted the '+accName+' account. \n\
You have '+ str(len(after_d))+ ' encrypted account on file now.',
	                    title='Account ', parent = window2)
                elif len(after_d)==0 or len(after_d)>1 and question == 1:
                    messagebox.showinfo(message='You have successfully deleted the '+accName+' account.\n\
You have '+ str(len(after_d))+ ' encrypted accounts on file now.',
	                    title='Accounts ', parent = window2)      
Ejemplo n.º 45
0
def vault():
	#door(break down)
	#monster filled vault
	messagebox.showinfo("Mr.Bones","What is this? you are in an office like room.")
	messagebox.showinfo("Mr.Bones","There! On the table! There is some equipment to escape with!")
	messagebox.showinfo("Mr.Bones","You cautiosly take the equipment. Nothing strange happens.")
	messagebox.showinfo("Mr.Bones","Could this be? Could this finally be an exit?")
	messagebox.showinfo("Mr.Bones","you see a old wooden door, Its barred and marked. 'there is no escape'")
	messagebox.showinfo("Mr.Bones","It looks like Mr.Bones wanted to hide this door from me....")
	lq= messagebox.askquestion("Mr.Bones","Will you break down the door?")
	if lq=="yes":
		paq= messagebox.askretrycancel("Mr.Bones","The door breaks a little, but not enough to open it.")
		if paq=="retry":
			messagebox.showinfo("Mr.Bones","The door breaks!")
			messagebox.showinfo("Mr.Bones","There is a big safe door in there with the sign 'Vault' on it.")
			oqa=messagebox.askquestion("Mr.Bones","Open the door?")
			if oqa=="yes":
				messagebox.showinfo("Mr.Bones","The door opens and you are blinded")
				messagebox.showinfo("Mr.Bones","It's sunlight! You did it! You escaped!")
				messagebox.showerror("Mr.Bones","You were slaughtered by a horde of monsters.")
				exec("GAME OVER")
			else:
				messagebox.showinfo("Mr.Bones","The Vault suddenly opens.")
				messagebox.showinfo("Mr.Bones","Light suddenly shines on you, are you finally free?")
				messagebox.showerror("Mr.Bones","nope. There was a horde of monsters in there.")
				messagebox.showinfo("Mr.Bones","Artificial rooms sure are sweet huh?")
				exec("GAME OVER")

		else:
			messagebox.showinfo("Mr.Bones","You lay down and begin to cry.")
			messagebox.showinfo("Mr.Bones","You cried so much that you are dehydrated.")
			messagebox.showerror("Mr.Bones","You drowned in your own tears.")
			exec("GAME OVER")

	else:
		messagebox.showinfo("Mr.Bones","You take your equipment and go back.")
		messagebox.showerror("Mr.Bones","You bump into Mr.Bones!")
		messagebox.showwarning("Mr.Bones","You're not supposed to be here...")
		messagebox.showinfo("Mr.Bones","Mr.Bones impales you with his sharp cane.")
		exec("GAME OVER")
Ejemplo n.º 46
0
def askRetryCancel(title = "Retry?", message = "", **kw):
	return messagebox.askretrycancel(title, message, **kw)
Ejemplo n.º 47
0
def load(): # Reusable call load()
    showsplash()
    try:
        requests.get('https://scratch.mit.edu')
    except:
        if db.askretrycancel('Could Not Connect', 'Could not connect to the Scratch website.'):
            splash.destroy()
            load()
            os._exit(1)
        else:
            os._exit(1)
    splash.destroy()
    passinfo = getpassword(title='Login to Scratch account', prompt=['Enter Username', 'Enter Password'])
    if not passinfo:
        os._exit(1)
    auth = (passinfo[0], passinfo[1])
    showsplash()
    global s
    s = requests.session()
    s.get('https://scratch.mit.edu/csrf_token/',headers={"Accept":"*/*","Referer":"https://scratch.mit.edu","X-Requested-With":"XMLHttpRequest"},auth=auth)
    csrf = str(requests.utils.dict_from_cookiejar(s.cookies)['scratchcsrftoken'])
    global headers
    headers = {"Accept":"*/*", "Referer":"https://scratch.mit.edu","Origin":"https://scratch.mit.edu","Content-Type":"application/json","X-CSRFToken":csrf, "X-Requested-With":"XMLHttpRequest"}
    login = str(json.dumps({'csrfmiddlewaretoken':str(csrf),'username':str(passinfo[0]),'password':str(passinfo[1]),'captcha_challenge':'','captcha_response':'','embed_captcha':False,'timezone':'America/New_York'}))
    l = s.post("https://scratch.mit.edu/login/", headers={"Accept":"application/json, text/javascript, */*; q=0.01","Referer":"https://scratch.mit.edu","Origin":"https://scratch.mit.edu","Content-Type":"application/json","X-CSRFToken":csrf,"X-Requested-With":"XMLHttpRequest"}, data=login)
    user_info = s.get('https://scratch.mit.edu/fragment/account-nav.json',headers=headers)
    user_page_info = s.get('https://scratch.mit.edu/api/v1/user/' + passinfo[0] + '/?format=json',headers=headers)
    global proj
    proj = s.get('https://scratch.mit.edu/site-api/projects/all/',headers=headers)
    try:
        proj = proj.json()
        proj[0]["pk"]
        backpack = s.get('https://scratch.mit.edu/internalapi/backpack/Dylan5797/get/',headers=headers).json()
        user_page_info = user_page_info.json()
    except:
        r = s.get('https://scratch.mit.edu/users/' + passinfo[0] + '/')
        if r.status_code == 404:
            db.showerror('Login','Couldn\'t find that user.')
        else:
            db.showerror('Login','Incorrect Password.')
        splash.destroy()
        load()
        os._exit(1)
    def projIcon(e=None):
        class x: pass
        ch = Tk()
        ch.title('Change Project Icon')
        x.lb = Listbox(ch, height=35, width=75); x.lb.grid(row=0,column=0)
        for y in proj:
            x.lb.insert('end', y['fields']['title'])
    def openPage(e=None):
        webbrowser.open('https://scratch.mit.edu/users/' + passinfo[0] + '/')
    def backPack(e=None):
        print(backpack)
    def projDown(e=None, yx=None):
        if not yx:
            yx = sd.askinteger('Enter Project ID', 'Enter the project ID that can be found at the end of the URL of a project.')
        s = downloadProject(yx)
        if s['status'] == 'error':
            try:
                s['stack']
            except:
                stack = True
            else:
                stack = s['stack']
            if stack:
                r = db.askretrycancel('Project Downloader', 'Error: Could not download project: ' + str(s['error']) + '\nStacktrace:\n' + str(traceback.format_exc()) + '\nError Code ' + str(error_code) + ': ' + error_codes[s['code']][0] + '. ' + error_codes[s['code']][1])
            else:
                r = db.askretrycancel('Project Downloader', 'Error: Could not download project: ' + str(s['error']) + '\nError Code ' + str(s['code']) + ': ' + error_codes[s['code']][0] + '. ' + error_codes[s['code']][1])
            if r:
                projDown(yx=yx)
    class w: pass
    splash.destroy()
    wm = tkinter.Tk()
    wm.title(passinfo[0] + '\'s Profile')
    w.t = Label(wm, text=passinfo[0],font=['Calabri',14],cursor="hand2");w.t.grid(row=2,column=0,sticky='w')
    w.cnty = Label(wm, text=user_page_info['userprofile']['country'],font=['Calabri',9]);w.cnty.grid(row=3,column=0,sticky='w')
    w.bio = sct.ScrolledText(wm,height=3,width=70);w.bio.grid(row=4,sticky='w')
    w.bio.insert('1.0', user_page_info['userprofile']['bio'])
    w.bio.config(state='disabled')
    w.sta = sct.ScrolledText(wm,height=3,width=70);w.sta.grid(row=5,sticky='w')
    w.sta.insert('1.0', user_page_info['userprofile']['status'])
    w.sta.config(state='disabled')
    w.m = Button(wm, text='Backpack...',command=backPack); w.m.grid(row=6,sticky='w')
    w.t.bind('<Button-1>', openPage)
    w.ch = Button(wm, text='Change Project Icon', command=projIcon); w.ch.grid(row=7,column=0,sticky='w')
    w.dl = Button(wm, text='Download Project', command=projDown); w.dl.grid(row=8,sticky='w')
    wm.mainloop()
Ejemplo n.º 48
0
def pop_up_msg(issue,message):    
    if tkMessageBox.askretrycancel(issue,message,parent=root):
        print("RESET")
        reset()
    else:
        GUI.close()
Ejemplo n.º 49
0
	def retryorcancel(self, qbtitle, qbtext, qbicon="question"):
		a=messagebox.askretrycancel(qbtitle, qbtext, icon=qbicon)
		return a
Ejemplo n.º 50
0
    print(notes_dir)
    if not notes_dir:
        return False

    config.set("NoteBag", "Notes Directory", notes_dir)
    save_config(config, CONFIG_FILENAME)
    return True


if __name__ == "__main__":
    print("NoteBag {0}".format(__version__))
    print("Copyright (C) {0}".format(__copyright__))

    # Hide the main root window, and only show the dialogs.
    root = Tk()
    root.withdraw()
    while not maybe_first_time_setup():
        success = messagebox.askretrycancel(
                "Try Again?",
                "It looks like your first-time setup failed. Would you like to try setting up NoteBag again?")
        if not success:
            root.destroy()
            exit(1)
    root.destroy()

    # Create the main window
    root = Tk()
    root.title("NoteBag")
    notebag = NoteBag(root)
    root.mainloop()
Ejemplo n.º 51
0
def start(*args):
    global logs
    global season1
    global serie_combo
    global get_img
    global img_src

    try:
        serie = serie_combo.get()

        if serie == 'Friends':
            while check('http://o2tvseries.com/Friends/index.html') == 'Connection failed':
                check_fail = messagebox.askretrycancel('Connection Error', 'Connection Failed. Reconnect and try again')
                if check_fail:
                    continue
                else:
                    break
            else:
                tplvl = TopLevel()
                name = os.path.basename(img_src)
                if os.path.exists('imgs'):
                    file = os.path.join('imgs', name)
                    with open(file, 'wb')as path:
                        for chunks in get_img.iter_content(1000):
                            path.write(chunks)

                else:
                    os.mkdir('imgs')
                    file = os.path.join('imgs', name)
                    with open(file, 'wb')as path:
                        for chunks in get_img.iter_content(1000):
                            path.write(chunks)

                pik = Image.open(file)
                tk_pik = ImageTk.PhotoImage(pik)
                label = Label(tplvl, image=tk_pik)
                label.image = tk_pik
                label.grid(row=0, column=0)

                lab2 = Label(tplvl, text=season1 + ': ' + check('http://o2tvseries.com/Friends/index.html'))
                lab2.grid(row=1, column=0)

                close_button = Button(tplvl, text='Close', command=tplvl.destroy, relief=GROOVE)
                close_button.grid(row=3, column=0)
                os.remove(file)
        with open('series.txt', 'r') as serie_txt:
            url = [serie_url.strip('\n') for serie_url in serie_txt.readlines() if serie.lower() in serie_url]

        while check(url[0]) == 'Connection failed':
            check_fail = messagebox.askretrycancel('Connection Error', 'Connection Failed. Reconnect and try again')
            if check_fail:
                continue
            else:
                break
        else:
            if len(url) > 0:
                tplvl = Toplevel()
                name = os.path.basename(img_src)
                if os.path.exists('imgs'):
                    file = os.path.join('imgs', name)
                    with open(file, 'wb') as path:
                        for chunks in get_img.iter_content(1000):
                            path.write(chunks)

                else:
                    os.mkdir('imgs')
                    file = os.path.join('imgs', name)
                    with open(file, 'wb')as path:
                        for chunks in get_img.iter_content(1000):
                            path.write(chunks)

            pik = Image.open(file)
            tk_pik = ImageTk.PhotoImage(pik)
            label = Label(tplvl, image=tk_pik)
            label.image = tk_pik
            label.grid(row=0, column=0)

            lab2 = Label(tplvl, text=season1 + ': ' + check(url[0]))
            lab2.grid(row=1, column=0)

            close_button = Button(tplvl, text='Close', command=tplvl.destroy, relief=GROOVE)
            close_button.grid(row=3, column=0)
            os.remove(file)

    except IndexError:
        pass
Ejemplo n.º 52
0
def btn7_clicked():
    msgbox.askretrycancel("Retry", "Askretrycancel test.")
 def retrycancel_demo(self):
     self.print_result(messagebox.askretrycancel('Retry', 'Do you want to retry or not?'))
Ejemplo n.º 54
0
    def enter_data(*args):
        global mass_pass
        create_table()
        get_ID()
        global num
        global alpha_num
        global gsalt      
        m_pass = mass_pass.get()
        accName = aName.get()
        accountID = accID.get()
        salt = randomise.get()
        makeSalt(salt)
        password = accPass.get()
        secretQ = secQ.get()
        SecretQans = secA.get()
        Account_Notes = text.get('1.0', 'end')       
        if len(Account_Notes)-1 > 120:
                length = len(Account_Notes)- 120
                e_message = messagebox.askretrycancel(message='The length of your Account Notes \
exceeds 120 characters.' ,title='Error', parent = window1)
                if e_message < 1:          
                    text.delete(1.0, END)
                    text.focus()           
                else:
                    text.delete(1.0, END)
                    text.insert(END, Account_Notes[:len(Account_Notes)-length])
                    text.focus()                       
        else:           
            password = encrypt_it(password,key_for_acc_pass(m_pass))
            accountID = encrypt_it(accountID,key_update_for_field(m_pass,alpha_num[11:21])) 
            secretQ = encrypt_it(secretQ,key_update_for_field(m_pass,alpha_num[60:70]))  
            SecretQans = encrypt_it(SecretQans,key_update_for_field(m_pass,alpha_num[40:55]))
            Account_Notes = encrypt_it(Account_Notes,key_update_for_field(m_pass,alpha_num[45:60]))       
            ID = 1+num
            account_check = []
            for row in cursor.execute("SELECT accName FROM User_Accounts "):
                account_check.append(row)
            if (accName,) in account_check:
                exists = 1
                if exists == 1:
                    question = messagebox.askyesno(message='This account already exists. \n\
Do you want to replace it?',
	                   icon='question', title='Confirm', parent = window1, default = 'no')
                    if question < 1:
                        clear()
                        accName_entry.focus()
                    else:
                        cursor.execute("delete from User_Accounts where accName = ? ", [(accName)])
                        conn.commit()
                        cursor.execute("INSERT INTO User_Accounts (ID, accName, accountID, salt, password, secretQ,"+\
                      "SecretQans, Account_Notes) VALUES(?,?,?,?,?,?,?,?)",
                  (ID, accName, accountID, salt, password, secretQ, SecretQans, Account_Notes))
                        conn.commit()
                        num = num +1
                        e_message = messagebox.askokcancel(message='You have successfully encrypted the '
                                            +accName+' account.\n\
To view this data in encrypted format, press OK.\n\
Else, CANCEL to continue.', title='Account Encrypted', parent = window1)
                        if e_message < 1:
                            clear()
                            accName_entry.focus()
                        else:
                            e_message = messagebox.showinfo(message='You have successfully encrypted the '
                                            +accName+' account.\n\
\n\
Account ID encrypted as: \n\
'+ accountID+ '\n\
Password encrypted as: \n\
'+ password+'\n\
Secret Question encrypted as: \n\
'+ secretQ+'\n\
Secret Question Answer encrypted as: \n\
'+ SecretQans+'\n\
Account Notes encrypted as: \n\
'+ Account_Notes+'\n\
',  
                                                    
	                title='Data Encrypted as', parent = window1)
                            clear()
                            accName_entry.focus()

            else:
                cursor.execute("INSERT INTO User_Accounts (ID, accName, accountID, salt, password, secretQ,"+\
                      "SecretQans, Account_Notes) VALUES(?,?,?,?,?,?,?,?)",
                  (ID, accName, accountID, salt, password, secretQ, SecretQans, Account_Notes))
                conn.commit()
                num = num +1
                e_message = messagebox.askokcancel(message='You have successfully encrypted the '
                                            +accName+' account.\n\
To view this data in encrypted format, press OK.\n\
Else, CANCEL to continue.', title='Account Encrypted', parent = window1)
                if e_message < 1:
                    clear()
                    accName_entry.focus()
                else:
                    e_message = messagebox.showinfo(message='You have successfully encrypted the '
                                            +accName+' account.\n\
\n\
Account ID encrypted as: \n\
'+ accountID+ '\n\
Password encrypted as: \n\
'+ password+'\n\
Secret Question encrypted as: \n\
'+ secretQ+'\n\
Secret Question Answer encrypted as: \n\
'+ SecretQans+'\n\
Account Notes encrypted as: \n\
'+ Account_Notes+'\n\
',  
                                                    
	                title='Data Encrypted as', parent = window1)
                    clear()
                    accName_entry.focus()
Ejemplo n.º 55
0
	def askq4(self):
		tkmb.askretrycancel("Question", "Could not find it.\nDo you want to try again?")
Ejemplo n.º 56
0
Archivo: view.py Proyecto: pybee/duvet
    def load_coverage(self):
        "Load and display coverage data"
        # Store the old list of files that have coverage data.
        # We do this so we can identify stale data on the tree.
        old_files = set(self.coverage_data['lines'].keys())
        old_total_coverage = self.coverage_data['total_coverage']

        loaded = False
        retry = True
        while not loaded and retry:
            try:
                # Load the new coverage data
                cov = coverage.coverage()
                cov.load()

                # Override precision for coverage reporting.
                coverage.results.Numbers.set_precision(1)

                if cov.data.measured_files():
                    self.coverage_data = {
                        'lines': {},
                        'missing': {},
                    }
                    totals = coverage.results.Numbers()

                    # Update the coverage display of every file mentioned in the file.
                    for filename in cov.data.measured_files():
                        filename = os.path.normcase(filename)
                        node = nodify(filename)
                        dirname, basename = os.path.split(filename)

                        # If the normalized version of the filename is the same as the
                        # filename, then the file *isn't* under the project root.
                        if filename == self.filename_normalizer(filename):
                            file_tree = self.global_file_tree
                        else:
                            file_tree = self.project_file_tree

                        try:
                            # # Make sure the file exists on the tree.
                            file_tree.insert_filename(dirname, basename)

                            # Compute the coverage percentage
                            analysis = cov._analyze(filename)

                            self.coverage_data['lines'][filename] = analysis.statements
                            self.coverage_data['missing'][filename] = analysis.missing
                            file_coverage = analysis.numbers.pc_covered

                            totals = totals + analysis.numbers

                            file_tree.set(node, 'coverage', analysis.numbers.pc_covered_str)
                            # file_tree.set(node, 'branch_coverage', str(len(lines)))

                            # Set the color of the tree node based on coverage
                            if file_coverage < 70.0:
                                file_tree.item(node, tags=['file', 'code', 'bad'])
                            elif file_coverage < 80.0:
                                file_tree.item(node, tags=['file', 'code', 'poor'])
                            elif file_coverage < 90.0:
                                file_tree.item(node, tags=['file', 'code', 'ok'])
                            elif file_coverage < 99.9:
                                file_tree.item(node, tags=['file', 'code', 'good'])
                            else:
                                file_tree.item(node, tags=['file', 'code', 'perfect'])

                        except coverage.misc.NoSource:
                            # could mean the file was deleted after running coverage
                            file_tree.item(node, tags=['bad'])

                        # We've updated the file, so we know it isn't stale.
                        try:
                            old_files.remove(filename)
                        except KeyError:
                            # File wasn't loaded before; ignore this.
                            pass

                        # Clear out any stale coverage data
                        for filename in old_files:
                            node = nodify(filename)
                            if file_tree.exists(node):
                                file_tree.set(node, 'coverage', '')
                                file_tree.item(node, tags=['file', 'code'])

                    # Compute the overall coverage
                    total_coverage = totals.pc_covered
                    self.coverage_data['total_coverage'] = total_coverage

                    coverage_text = u'%.1f%%' % total_coverage

                    # Update the text with up/down arrows to reflect change
                    if old_total_coverage is not None:
                        if total_coverage > old_total_coverage:
                            coverage_text = coverage_text + u' ⬆'
                        elif total_coverage < old_total_coverage:
                            coverage_text = coverage_text + u' ⬇'

                    self.coverage_total_summary.set(coverage_text)

                    # Set the color based on coverage level.
                    if total_coverage < 70.0:
                        self.coverage_total_summary_label.configure(foreground='red')
                    elif total_coverage < 80.0:
                        self.coverage_total_summary_label.configure(foreground='orange')
                    elif total_coverage < 90.0:
                        self.coverage_total_summary_label.configure(foreground='blue')
                    elif total_coverage < 99.9:
                        self.coverage_total_summary_label.configure(foreground='cyan')
                    else:
                        self.coverage_total_summary_label.configure(foreground='green')

                    # Refresh the file display
                    current_file = self.code._filename
                    if current_file:
                        self.code._filename = None
                        self.show_file(current_file)

                    loaded = True
                else:
                    retry = tkMessageBox.askretrycancel(
                        message="Couldn't find coverage data file. Have you generated coverage data? Is the .coverage in your current working directory",
                        title='No coverage data found'
                    )
            except Exception as e:
                retry = tkMessageBox.askretrycancel(
                    message="Couldn't load coverage data -- data file may be corrupted (Error was: %s)" % e,
                    title='Problem loading coverage data'
                )

        return loaded
Ejemplo n.º 57
0
    def change(self, index):
        # Clear the label for the return label        
        self.info_label.configure(text="")

        #==== Start of Simple, "OK" button only Messages" ====
        if self.buttons[index].configure("text")[4] == self.labels[0]:
            self.info_label2.configure(text='b_return = messagebox.showinfo'
                '("Messagebox", "showinfo.\\n\\nOne OK button.")')

            b_return = messagebox.showinfo("Messagebox", "showinfo."
                    "\n\nOne OK button. ")
            print("info", b_return)
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        if self.buttons[index].configure("text")[4] == self.labels[1]:
            self.info_label2.configure(text='b_return = messagebox.showwarning'
                '("Messagebox", "showwarning.\\n\\nOne OK button.")')

            b_return = messagebox.showwarning("Messagebox", "showwarning."
                    "\n\nOne OK button.")
            print("warning", b_return)
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        if self.buttons[index].configure("text")[4] == self.labels[2]:
            self.info_label2.configure(text='b_return = messagebox.showerror'
                '("Messagebox", "showerror.\\n\\nOne OK button.")')
            b_return = messagebox.showerror("Messagebox", "showerror."
                    "\n\nOne OK button.")
            print("error", b_return)
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        #==== End of Simple, "OK" Button Only Messages ====

        #==== Start of Multiple Button Messages" ====
        if self.buttons[index].configure("text")[4] == self.labels[3]:
            self.info_label2.configure(text='b_return = messagebox.askquestion'
                '("Messagebox", "Ask Question?\\n\\nYes or No buttons '
                'return yes or no")')
            b_return = messagebox.askquestion("Messagebox", "Ask Question?"
                    "\n\nYes or No buttons return yes or no")
            print("question", b_return)
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        if self.buttons[index].configure("text")[4] == self.labels[4]:
            self.info_label2.configure(text='b_return = messagebox.askokcancel'
                '("Messagebox", "Proceed?\\n\\nOK or Cancel buttons '
                'return True of False.")')
            b_return = messagebox.askokcancel("Messagebox", "Proceed?"
                    "\n\nOK or Cancel buttons return True of False.")
            print("proceed", b_return)
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        if self.buttons[index].configure("text")[4] == self.labels[5]:
            self.info_label2.configure(text='b_return = messagebox.askyesno'
                '("Messagebox", "Got it?\\n\\nYes or No buttons '
                'return True or False.")')            
            b_return = messagebox.askyesno("Messagebox", "Got it?"
                    "\n\nYes or No buttons return True or False.")
            print("yes/no", b_return)
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        if self.buttons[index].configure("text")[4] == self.labels[6]:
            self.info_label2.configure(text='b_return = messagebox.'
                'askyesnocancel("Messagebox", "Want it? \\n\\nYes, No or '
                'Cancel buttons return True False and None.")')
            b_return = messagebox.askyesnocancel("Messagebox", "Want it? "
                "\n\nYes, No or Cancel buttons return True False and None.")
            print("yes/no/cancel", b_return)
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        if self.buttons[index].configure("text")[4] == self.labels[7]:
            self.info_label2.configure(text='b_return = messagebox.'
                'askretrycancel("Messagebox", "Try Again?\\n\\nRetry or '
                'Cancel buttons return True or False.")')
            b_return = messagebox.askretrycancel("Messagebox", "Try Again?" 
                "\n\nRetry or Cancel buttons return True or False.")
            print("retry/cancel", b_return) 
            self.info_label.configure(text="Returned value: {}".
                format(b_return))

        #==== End of Multiple Button Messages" ====

        if self.buttons[index].configure("text")[4] == self.labels[8]:
            self.info_label2.configure(text='')
            self.info_label.configure(text=HELP_MESSAGE )