Deleting a file
from Tkinter import *
import socket, sys, os
import tkMessageBox
root = Tk()
root.title("File Deleter v1.0")
root.config(bg='black')
root.resizable(0, 0)
text = Text()
text3 = Text()
frame = Frame(root)
frame.config(bg="black")
frame.pack(pady=10, padx=5)
frame1 = Frame(root)
frame1.config(bg="black")
frame1.pack(pady=10, padx=5)
text.config(width=35, height=1, bg="black", fg="white")
text.pack(padx=5)
def button1():
try:
x = text.get("1.0", END)
os.remove(x)
except WindowsError:
text3.insert(END, "File Not Found... Try Again\n")
def clear():
text.delete("1.0", END)
c = Button(frame1, text="Clear", width=10, height=2, command=clear)
c.config(fg="white", bg="black")
c.pack(side=LEFT, padx=5)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text3.config(width=35, height=15, bg="black", fg="white")
text3.pack(side=LEFT, fill=Y)
scrollbar.config(command=text3.yview)
text3.config(yscrollcommand=scrollbar.set)
w = Label(frame, text="Delete A File")
w.config(bg='black', fg='white')
w.pack(side=TOP, padx=5)
b = Button(frame1, text="Enter", width=10, height=2, command=button开发者_高级运维1)
b.config(fg="white", bg="black")
b.pack(side=LEFT, padx=5)
root.mainloop()
I dont get why the delete code is not working, I get a "File not Found" even if the file exist.
When I run this code on Linux and place a breakpoint in button1()
, I see that the value of x
includes a trailing newline character. That means the os.remove()
call won't work, because the filename I typed in didn't actually contain a newline. If I remove the trailing newline, the code works.
I believe gnibbler is on track with whitespace being the problem. The Text Widget gives you endline characters \n. Try adding a .strip() to the end of your text.get or you can use an Entry widget as opposed to a Text Widget since your Text widget is only one line anways.
x = text.get('1.0', END).strip()
Perhaps x is not what you think it is, just a guess but maybe there a some whitespace there or somthing, try this to check
def button1():
try:
x = text.get("1.0", END)
print repr(x)
os.remove(x)
except WindowsError, e:
print e
text3.insert(END, "File Not Found... Try Again\n")
精彩评论