0

I am using python and tkinter and my question consists of two parts :

Example : connection to a database

  • In my code , how do I say for example , if login successful do this and that ...
  • How can I display the actual exception / error message that appeared during the execution to Tkinter ? For example , there were wrong credentials . I want to have that message displayed using messagebox.showerror

Code written :

sql_connection():
global facility
facility=facilityname.get()
global username
username=uname.get()
global password
password=key.get()
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0}; Server='+facility+'; uid='+username+'; pwd='+password+'; Database = test_DB; Trusted_Connection=No;')
c=conn.cursor()
messagebox.showinfo("LOGIN ","Login Successful")

Thank you

  • What did you already try yourself? Please add something of it to the question that clarifies your actual problem. – Wolf May 05 '20 at 11:27
  • @Wolf I updated to the question – sameh grami May 05 '20 at 11:38
  • there is **one path of execution** put `try:` in the line before `conn = pyodbc.connect [...]` and `except` in the line after `messagebox.showinfo [...]`, see [my answer](https://stackoverflow.com/a/61614382/2932052) for a complete example of this pattern. – Wolf May 05 '20 at 13:34

2 Answers2

1

Maybe you did not use exceptions before. I don't see what the problem could be, independently whether you use tkinter or not. It's exactly one path that the execution takes. Either no exception occurs, then the try block is executed until its end (and the except block skipped), or, an exception occurs, then the try block is left before its end and the except block gets executed.

For example, this output

success
Error: 'something bad happened'

will be produced by the following code

def check_something(bad):
    if bad:
        raise Exception('something bad happened')
    pass


def run_xcheck(x):
    try:
        check_something(x)
        print('Success')
    except Exception as e:
        print('Error: "{}"'.format(e))

run_xcheck(False)
run_xcheck(True)

For the sake of completeness, the following is (a kind of) proof that it works the same way together with tkinter. It takes into account the fact that the conversion of the input can fail if the user does not enter a number. In this case python raises the ValueError exception, that you can catch as to display the specific error message:

import tkinter as tk
from tkinter import messagebox

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title('Exception Test')
        self.pack(padx=8, pady=8) # fill='both', 
        self.create_widgets()

    def create_widgets(self):
        self.content = tk.StringVar(value='1')
        self.label = tk.Label(self, 
            text='Enter number:'
        ).pack(side='left')
        self.entry = tk.Entry(self, 
            textvariable=self.content
        ).pack(side='left')
        self.button = tk.Button(self, 
            text='Square it!',
            command=self.square_pressed
        ).pack()

    def square_pressed(self):
        try:
            i = int(self.content.get())  # conversion may fail
            messagebox.showinfo(message='{}² → {}'.format(i, i**2))
        except ValueError as e:
            messagebox.showerror(message='error: "{}"'.format(e))

root = tk.Tk()
app = Application(master=root)
app.mainloop()

You should look up the actual exception class(es) that `pyodbc.connect' can raise to get the maximum amount of information. Maybe how to catch specific pyodbc error message could be worth reading.

Wolf
  • 9,679
  • 7
  • 62
  • 108
0

Try the following:

try:
   # call whatever code that might throw an exception

except Exception as e:
     messagebox.showerror(title "Exception raised",message = str(e))
Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20
  • but how to test if there was a successful login or not to decide which message to display ? Meaning if successful , display " success" , if not , show the error message – sameh grami May 05 '20 at 11:36
  • You need to check the possible error values/exception raised by `pyodbc.connect` to know what to expect in case connection fails. Ie return value might be `None` or an exception might be raised. Once you know how connect reports an error it is trivial to code for this error and display the messagebox. – Jean-Marc Volle May 05 '20 at 11:52