微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我从文本文件将名称加载到 Combobox 时,为什么我的函数会出现 OSError?

如何解决当我从文本文件将名称加载到 Combobox 时,为什么我的函数会出现 OSError?

def clock_in(): #  triggered with a button in tkinter
    employee = employee_drop_list.get() # get name selected from ComboBox
    employee_drop_list.delete(0,tk.END) # delete name after button clicked

    working = "Employee Time Records\\Employees_Working.txt" # folder & file
    date = datetime.datetime.Now().strftime("%Y-%m-%d,%I:%M %p") # date format
    filename = datetime.datetime.Now().strftime("Week_%V_%Y") # file name prefix
    location = "Employee Time Records" # folder in same location as code
    connected = os.path.join(location,filename + "_" + employee + ".txt")

    Employee_List = "Employee Time Records\\Employee_List.txt" # list to check

    if employee not in open(working).read() and employee in open(Employee_List).read():
        with open(connected,"a") as file:
            file.write(employee + "_" + date + "_" + "Clocked In" + "\n")
            label['text'] = login_success()
            with open(working,"a") as t:
                t.write(employee + "\n")
    else:
        label['text'] = login_fail()

这是我如何将名称加载到组合框的代码。如果我将值加载到 ComboBox代码中而不是从文本文件加载并且我不明白为什么,那么错误就会消失并且工作正常。

employees = []
with open("Employee Time Records\\Employee_List.txt") as listFile:
    employees = [line for line in listFile]

employee_drop_list = ttk.ComboBox(frame,font=20,state="normal")
employee_drop_list['values'] = list(employees)
employee_drop_list.place(relwidth=.5,relx=.125,height=60)

我得到的错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\rorym\AppData\Local\Programs\Python\python37\lib\tkinter\__init__.py",line 1705,in __call__
    return self.func(*args)
  File "E:/Programming/PYTHON FOR WINDOWS/tkinter/MT Systems employee time clock/text_test/TimeClock.py",line 161,in <lambda>
    clock_in_button = ttk.Button(frame,text="Clock In",command=lambda: clock_in())
  File "E:/Programming/PYTHON FOR WINDOWS/tkinter/MT Systems employee time clock/text_test/TimeClock.py",line 47,in clock_in
    with open(connected,"a") as file:
OSError: [Errno 22] Invalid argument: 'Employee Time Records\\Week_07_2021_Amador Espinoza\n.txt'

解决方法

这可能有两个原因。一,可能是您的代码无法找到该文件夹​​。确保它与 .py 文件位于同一目录中。其次,可能是因为您没有指定模式。尝试在 ,"r" 调用的末尾添加 open

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。