malabeh
malabeh

Reputation: 101

Button in python graphic window

def read_inventory(fname):
    file=open(fname,'r')
    lst=file.readlines()
    return lst


while True:
    c=win.getMouse()#c=click
    if p2.x<c.x<p1.x and p2.y<c.y<p1.y:
        lst=read_inventory(file_name_E.getText())
        print(lst)

In a python graphic window, I'm trying to make a button that opens a file in which the name is input by the user. However, if the file does not exist, I get an error and the while True loop does not run anymore, meaning that the user cannot enter another file to try and open. I can't seem to understand why this is happening.

Upvotes: 1

Views: 99

Answers (2)

malabeh
malabeh

Reputation: 101

The try except block worked perfectly and this is what I got:

def read_inventory(fname):
    file=open(fname,'r')
    lst=file.readlines()
    return lst

while True:
    c=win.getMouse() #c=click
    if p2.x<c.x<p1.x and p2.y<c.y<p1.y:
        try:
            lst=read_inventory(file_name_E.getText())
            print(lst)
        except:
            print("File name '{}' does not exist.".format(file_name_E.getText()))

lst is just the variable assigned to whatever is in the file at the time of reading.

Upvotes: 1

Ace
Ace

Reputation: 155

Try this:

def read_inventory(fname):
    file=open(fname,'r')
    lst=file.readlines()
    return lst

while True:
        try:
            c=win.getMouse()#c=click
            if p2.x<c.x<p1.x and p2.y<c.y<p1.y:
                lst=read_inventory(file_name_E.getText())
                print(lst)
        except:
            pass

Upvotes: 1

Related Questions