pythonpython-3.xtkinter

tkinter window produces the same result unless window is closed and re-opened


I am trying to build a novice inventory system that collects an item description via a tkinter entry window and stores it in a txt file. It also produces a coinciding barcode png. So far, I have gotten the barcode png to be produced and the numbers to be written to the txt file, but the tkinter window does not seem to be reloading a new number when the submit button is pressed. It is supposed to not generate duplicate numbers from the txt file, as well.

Some things to note:

Below is the function that runs when the button is clicked on the tkinter window.

# generate a random number
number = str(random.randint(100000000000, 999999999999))
# open the text file where the data is stored for reading and writing
def onClick():
    # open the text file where the data is stored for reading and writing
    file1 = open("barcode_numbers.txt", "a+")
    file2 = open("item_description.txt", "a+")
    # do not repeat numbers
    if number not in file1.read():
        # have a success message show up with the barcode number
        tkinter.messagebox.showinfo("Success!", number)
        # write the number to a new line in its text file
        file1.write(number + "\n")
        # generate a barcode
        new_code = EAN13(number, writer=ImageWriter())
        # save barcode as a png with associated number
        new_code.save(number)
        # save the item description to a new line in its text file
        file2.write(number + ": " + item.get() + "\n")
    # if the number repeats, offer a messagebox error
    else:
        tkinter.messagebox.askretrycancel("ERROR", "Duplicate barcode generated. Quit or try again.")
    # close the text file
    file1.close()
    file2.close()

Solution

  • The a+ mode will place the file read pointer at the end of the file, so file.read() will be empty.

    You'd need to file.seek(0) before reading, then seek to the end before writing again (so as not to truncate the file).

    However it might be better to use a structured format such as JSON for the files - for one, if the contents of the file are 12346419\n73197369\n49731979, and number is 419, it would be found in the file since you're not e. g. splitting it by new lines before using if... in.