简体   繁体   English

python图形窗口中的按钮

[英]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. 在python图形窗口中,我试图创建一个按钮来打开文件,用户在其中输入名称。 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. 但是,如果文件不存在,则会出现错误, while True循环不再运行,这意味着用户无法输入另一个文件来尝试打开。 I can't seem to understand why this is happening. 我似乎无法理解为什么会这样。

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

The try except block worked perfectly and this is what I got: 尝试try块工作完美,这就是我得到的:

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. lst只是在读取时分配给文件中任何内容的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM