-1

I have a problem, and I have no idea why it doesn't work!! :o I want to remove text files via tkinter, so when the 'user' writes the text file's name and clicks on the button, it will be removed.

from tkinter import *
import tkinter.messagebox
import os, time

root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')

def remove():
    if et in os.listdir():
        os.remove(et)
        tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
    else:
        tkinter.messagebox.showerror('Error!', 'File not found!')


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

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

#To fix extension bug
et = entry1.get()
if '.txt' not in et:
    et += '.txt'

button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)

root.mainloop()
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
NikolaTEST
  • 100
  • 11

2 Answers2

1

You were getting the value of et before the user had entered anything. Try this:

from tkinter import *
import tkinter.messagebox
import os, time

root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')

def remove():
    #To fix extension bug
    et = entry1.get()
    if '.txt' not in et:
        et += '.txt'
    if et in os.listdir():
        os.remove(et)
        tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
    else:
        tkinter.messagebox.showerror('Error!', 'File not found!')


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

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


button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)

root.mainloop()
Vaibhav Sagar
  • 2,208
  • 15
  • 21
0

Here, check this out: How to pass arguments to a Button command in Tkinter? (Edit: This is actually not so relevant to the question, but really useful knowledge with TkInter ;)

(In your code's remove function, "et" is not correctly set with the input field's content)

Actually, here's it fixed:

from tkinter import *
import tkinter.messagebox
import os, time

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)

def remove():
    #To fix extension bug
    et = entry1.get()
    if '.txt' not in et:
        et += '.txt'

    print(os.listdir())
    print(et)
    if et in os.listdir():
        print("os.remove(",et,")")
        tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
    else:
        tkinter.messagebox.showerror('Error!', 'File not found!')

button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)

root.mainloop()
Community
  • 1
  • 1
riot
  • 46
  • 7