-2
def delFile(self, num):
    if os.path.exists("quiz"+str(num)+".txt"):
        os.remove("quiz"+str(num)+".txt")
        tkinter.messagebox.showinfo("Removed!", "Quiz successfully Removed!")
    else:
        tkinter.messagebox.showinfo("Error!", "Quiz file not found!")

    if os.path.exists("answer"+(num)+".txt"):
        os.remove("answer"+(num)+".txt")
        tkinter.messagebox.showinfo("Removed!", "Answers successfully Removed!")
    else:
        tkinter.messagebox.showinfo("Error!", "Answer file not found!")

delete = quizEdit("a")
root = Tk()
root.geometry("450x320")
root.title("Remove a text file")

label1 = Label(root, text = "What to remove?")
label1.place(x=70, y = 140)

entry1 = Entry(root)
entry1.place(x = 180, y = 140)

et = entry1.get()

button1 = Button(root, text = "Remove", command=lambda : delete.delFile(et))
button1.place(x=210, y=200)


root.mainloop()

I'm trying to make it so that the delFile method can delete a text file from the directory based on whatever is entered from the entry in the GUI. However when I press the button it just outputs the else clause messagebox.

delFile is a method of a class called quizEdit.

Ra1den
  • 1
  • You are calling the `get()` method about a millisecond after you create the entry. The user won't have an opportunity to enter any data. – Bryan Oakley Mar 15 '20 at 19:46
  • 2
    First you have to understand [Event-driven programming](https://stackoverflow.com/a/9343402/7414759) – stovfl Mar 15 '20 at 19:55
  • @BryanOakley Alright I fixed it by simply passing the get() method as the parameter instead of using a variable. Thanks a lot. – Ra1den Mar 15 '20 at 20:14

1 Answers1

-1

The problem is that you're calling .get() about a millisecond after creating the entry widget, well before the user even sees the entry widget.

As a rule of thumb, GUI functions need to request data at the point that they need it. In your case I would make a callback specifically designed to get the value and then call your function.

...
def do_delete():
    num = entry1.get()
    delete.delFile(num)
...
button1 = Button(root, text = "Remove", command=do_delete)
...

This isn't the only solution, but for me it's the cleanest. You could set the command to a lambda which calls get(), but I find that sort of pattern to be harder to understand and harder to debug. Another option would to be call get() inside delFile, but that tightly couples the UI to the quizEdit object which may or may not be desirable.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685