1
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'
4

2 回答 2

0

要解决此问题,我只需使用 strip() 删除空格。

with open("Employee Time Records\\Employee_List.txt", "r") as listFile:
    employees = listFile.read().split("\n")

employee_drop_list = ttk.Combobox(frame, font=20, state="normal")
employee_drop_list['values'] = tuple(employees)
employee_drop_list.place(relwidth=.5, relx=.125, height=60)
    
于 2021-11-09T00:48:27.043 回答
-1

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

于 2021-02-20T20:00:25.187 回答