командная функция, показывающая неожиданные результаты - PullRequest
0 голосов
/ 18 июня 2019

Моя программа управления посещаемостью в основном сохраняет количество пропусков в простом текстовом файле и позволяет пользователю увеличить их. проблема в том, что код обновляет только одну тему, несмотря на выбор пользователя.

Я считаю, что проблема в 10-й строке функции "menubutton", при компиляции последний субъект застревает в аргументе.

from tkinter import *

window = Tk()
window.geometry("400x550")
window.configure(background = "black")
window.title("My Attendance Program")
dic = {}
files = open("filehandling.txt", 'w+')
files.close()
############declaration of functions:

def submit_subject():#function works fine
    files = open("filehandling.txt", 'r+')
    entered_subject = subject_val.get()
    output1.delete(0.0, END)
    for line in files:
        splitline = line.split()
        dic["{}".format(splitline[0])] = int(splitline[1])
    if entered_subject == "":
        output1.insert(END, "don't enter null string")
    elif entered_subject in dic.keys():
        output1.insert(END, "subject already exists")
    else:
        files.writelines(entered_subject+" "+"0"+"\n")
        output1.insert(END, "subject "+ entered_subject+ " added")
    files.close()

def view_subject():
    files = open("filehandling.txt", 'r+')
    output2.delete(0.0, END)
    for line in files:
        splitline = line.split()
        dic["{}".format(splitline[0])] = int(splitline[1])
    output2.insert(END, ', '.join(dic.keys()))
    files.close()

def donothing():
    print("hello")

def increment_in_file(strings):
    print(strings +" has been updated")
    files = open("filehandling.txt", 'r+')
    for line in files:
        splitline = line.split()
        dic["{}".format(splitline[0])] = int(splitline[1])
    files.close()
    files = open("filehandling.txt", 'w')
    for keys in dic:
        if keys == strings:
            files.writelines(keys + " " + "{}\n".format(dic[keys] + 1))
        else:
            files.writelines(keys + " " + "{}\n".format(dic[keys]))
    files.close()


#####################################function that is causing problem
def menubutton(): 
    but = Menubutton(window, text = "choose subject")
    but.grid(row = 7, column = 0, sticky = W)
    but.menu = Menu(but)
    but["menu"] = but.menu
    files = open("filehandling.txt", 'r+')
    output2.delete(0.0, END)
    for line in files:
        splitline = line.split()
        dic["{}".format(splitline[0])] = int(splitline[1])
        but.menu.add_command(label = "{}".format(splitline[0]), command = lambda: increment_in_file("{}".format(splitline[0]))) 
    files.close()
    # print(dic)



###############increment_in_file("{}".format(splitline[0]))

#ask for entry of subject row 0 and 1
Label(window, bg = "black", fg = "yellow", text = "Enter subject",anchor = W, width = 40).grid(row = 0, column = 0, sticky = W)
#entry window
subject_val = Entry(window, width = 40)
subject_val.grid(row = 1, column = 0, sticky = W)

#button for submission of subject  along with result row 2 and 3
Button(window, text = "Submit", width = 8, command = submit_subject).grid(row = 2, column = 0, sticky = W)
output1 = Text(window, wrap = WORD, width = 40, height = 1)
output1.grid(row = 3, column = 0, sticky = W)

#button and output for the entered subjects row 4 and 5
Button(window, text = "View Subject", width = 15, height = 1, command = view_subject).grid(row = 4, column = 0, sticky = W)
output2 = Text(window, wrap = WORD, width = 40, height = 3)
output2.grid(row = 5, column = 0, sticky = W)



#button to mark attendance row 6 and 7
Button(window, text = "Mark attendance", width = 15, height = 1, command = menubutton).grid(row = 6, column = 0, sticky = W)





window.mainloop()

1 Ответ

0 голосов
/ 18 июня 2019

Да, проблема в строке (внутри menubutton()):

but.menu.add_command(label = "{}".format(splitline[0]), command = lambda: increment_in_file("{}".format(splitline[0])))

Значение, переданное в increment_in_file(), всегда будет последним назначенным значением splitline цикла for, когдафункция выполняется.

Вам необходимо передать требуемое значение через значение по умолчанию параметра:

but.menu.add_command(label=splitline[0], command=lambda subj=splitline[0]: increment_in_file(subj))

Поскольку значение по умолчанию будет построено из заданного значения при создании лямбды.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...