Python Forum
try except/ if else
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try except/ if else
#1
Although the code is working as expected, I can't figure out the if else inside the try except does not work as intended.
If results > 0 is returned print the results else print a message.
The results > 0 works but, when the results are == 0 it throws the except.
The except should only be for the database connection.
I took out all the bloat eg(made just the if/else inside the try/except and it works correct.
It just does not work in the coding. Any help would be great.
I usually don't like posting all code but, not sure where the error is located.
Thanks
#! /usr/bin/env python3.8

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import string
import pymysql
from functools import partial


class MainWindow:
    #Globals Vars
    HOST = 'myhost'
    USER = 'myusername'
    PASSWORD = 'secret'
    DB = 'mydb'


    def __init__(self, master):
        self.master = master

        ############ Main Window ##################################
        self.main_frame_style = ttk.Style()
        self.main_frame_style.configure('MainFrame.TFrame', background = 'slategray')
        self.main_frame = ttk.Frame(self.master, style = 'MainFrame.TFrame')
        self.main_frame.grid(column = 0, row = 0, sticky = ('n','s','e','w'))
        for i in range(26):
            self.main_frame.grid_columnconfigure(i, weight = 3, uniform = 'john')

        ############ Header Widget ################################
        self.header_style = ttk.Style()
        self.header_style.configure('Header.TLabel', background = 'slategray3', relief = 'groove', anchor = 'center', padding = (2,2,2,2))
        load = Image.open('cookbook_logo.png')
        render = ImageTk.PhotoImage(load)
        self.header = ttk.Label(self.main_frame, image = render, style = 'Header.TLabel')
        self.header.grid(column = 0, row = 0, columnspan = 26, ipadx = 10, ipady = 5, sticky = ('n','s','e','w'))
        self.header_img = render




        ############ Make letter menu #############################
        self.button_style = ttk.Style()
        self.button_style.configure('MY_Button.TButton', width = 3, padding = (2,2,2,2), background = 'skyblue')
        letters = string.ascii_uppercase
        i=0
        for letter in letters:
            self.button = ttk.Button(self.main_frame, text = letter, style = 'MY_Button.TButton', command=partial(self.widgetDestroy, letter))
            self.button.grid(column = i, row = 1, sticky = ('n','s','e','w'))
            i += 1



        ############ Right Widget Displays Instructions ###########
        self.right_label_style = ttk.Style()
        self.right_label_style.configure('Right.TLabel', background = 'slategray3', relief = 'groove', padding = (8,8,8,8))
        self.right_label = ttk.Label(self.main_frame, text = 'Just some text on the right', style = 'Right.TLabel')
        self.right_label.grid(columnspan = 18, column = 8, row = 2, sticky = ('n','s','e','w'))

        ############ Footer Information ###########################
        self.footer_style = ttk.Style()
        self.footer_style.configure('My_Footer.TLabel', font = ('Sans', 10, 'normal'), anchor = 'center', relief = 'groove', background = 'slategray3', foreground = 'navy')
        self.footer = ttk.Label(self.main_frame, text = 'My footer text', style = 'My_Footer.TLabel')
        self.footer.grid(columnspan = 26, column = 0, row = 3,  sticky = ('n','s','e','w'))

        ############ Resize config ################################
        self.master.columnconfigure(0, weight = 1)
        self.master.rowconfigure(0, weight = 1)
        self.main_frame.columnconfigure(0, weight = 3)
        # self.left_label.columnconfigure(0, weight = 3)
        self.right_label.columnconfigure(0, weight = 3)
        self.button.rowconfigure(1, weight = 3)



    def widgetDestroy(self,letter):
        self.left_frame.destroy()
        self.left_frame = ttk.Frame(self.main_frame)
        self.left_frame.grid(columnspan=8,column = 0, row = 2, sticky = ('n','s','e','w'))
        self.left_frame.columnconfigure(0, weight = 3)
        self.leftWidget(letter=letter)

    def leftWidget(self, letter = 'a'):
        ############ Left Widget Displays Recipe Titles ###########
        self.left_frame = ttk.Frame(self.main_frame)
        self.left_frame.grid(columnspan=8,column = 0, row = 2, sticky = ('n','s','e','w'))
        self.left_frame.columnconfigure(0, weight = 3)

        try:
            conn = pymysql.connect(host = self.HOST, user = self.USER, password = self.PASSWORD, db = self.DB)
            cur = conn.cursor()
            query = f'select title from homepages_post where title like "{letter}%"'
            cur.execute(query)
            results = cur.fetchall()

            print(len(results))

            if len(results) > 0:
                self.left_label_style = ttk.Style()
                self.left_label_style.configure('Left.TLabel', background = 'slategray3', relief = 'groove', padding = (8,8,8,8))
                i = 0
                for result in results:
                    self.left_label = ttk.Label(self.left_frame, style = 'Left.TLabel', text = result[0])
                    self.left_label.grid(column = 0, row = i, sticky = ('n','s','e','w'))
                    self.left_label.columnconfigure(0, weight = 3)
                    i += 1
            else:
                self.left_label_style = ttk.Style()
                self.left_label_style.configure('Left.TLabel', background = 'slategray3', relief = 'groove', padding = (8,8,8,8))
                self.left_label = ttk.Label(self.left_frame, text = f'I cound not find any listing for {letter}', style = 'Left.TLabel')
                self.left_label.grid(column = 0, row = 0, sticky = ('n','s','e','w'))
                self.left_label.coulnconfigure(0, weight = 3)

            conn.close()

        except:
            self.left_label_style = ttk.Style()
            self.left_label_style.configure('Left.TLabel', background = 'slategray3', relief = 'groove', padding = (8,8,8,8))

            self.left_label = ttk.Label(self.left_frame, style = 'Left.TLabel', text = 'Error: Could not connect to database')

            self.left_label.grid(column = 0, row = 0, sticky = ('n','s','e','w'))
            self.left_label.columnconfigure(0, weight = 3)

def main():
    root = tk.Tk()
    root.title("Johnny's CookBook")
    root.configure(borderwidth = 5, highlightcolor = 'slategray', highlightbackground = 'slategray', highlightthickness = 4)
    window = MainWindow(root)
    window.leftWidget()
    root.mainloop()

if __name__ == '__main__':
    main()

It was a typo. Sorry for the post. Guess sometimes you got to step back take a breath and look with again.
I would remove post but I do not see a link for it.
Thanks again.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#2
you should give except the exception condition like:
except ValueError:
    ...
# or
except (ValueError, BufferError):
Otherwise exceptions caused by something outside of your code block will not get caught
Then you can test by throwing a known illegal value to the code
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020