Search code examples
pythontkintermessagebox

How do you add an error alert then return to main function within same loop


How do you return to user input to try again in tkinter after the user searches for a value in excel that is not found whereby an error pop up is displayed?

In my submit function below it works for valid entries (values in the excel file) but if a value is entered that is not found in the excel sheet it correctly displays the error but then it continues to display the error when a valid value is entered for any subsequent searches

import tkinter
from tkinter import *
import tkinter as tk
from tkinter import scrolledtext
import openpyxl
from tkinter import messagebox


main = Tk()
main.title("Customer Search App")
main.geometry("1000x600")
main.configure(bg='blue')

excel_path = r".\Customer_Lookup.xlsx"

     
def submit():

        search_id = service_id.get()

           
        file = openpyxl.load_workbook(excel_path)

        sheet = file['Sheet1']


        for cell in sheet.iter_rows(min_row=1, max_row=sheet.max_row, 
            min_col=1, max_col=15, values_only=True):


            if cell[0] == search_id:
                date.insert(0, cell[1])
                account.insert(0, cell[2])
                name.insert(0, cell[3])
                comments.insert(1.0, cell[4])

            else:
                tk.messagebox.showerror("Error", "Service ID not found")


                break







main.mainloop()

Solution

  • I now realise what is wrong I needed a second if statement outside of the for loop also without needing a break statement as well