Python 2.7 Tkinter and ftplib
-
11-04-2021 - |
Question
I have quick question, and it may sound dumb. But for the love of me I can't find a solution online or by myself! I am trying to make a FTP client using python for my self, and I am trying to make a listbox in Tkinter display all the filenames on the FTP server. But I can't get the text to display! Here is the code I have so far below:
# Import the FTP object from ftplib
from ftplib import FTP
from Tkinter import *
app = Tk()
app.title("FTP")
app.geometry("300x500")
def handleDownload(block):
file.write(block)
print ".",
def login():
ftp.login(username.get(),password.get())
# This is where I am held up I tried ftp.retrlines('LIST') but it would
# not be inserted into to the list box instead it inserted "Tranfer Complete" at the end!
# Any suggetion?
h = ?
stuff = Listbox(app)
stuff.insert(END, h)
stuff.pack()
filename = "Steam Engine Poster.pdf"
Label(app, text ='Opening local file ' + filename).pack()
file = open(filename, 'wb')
Label(app, text = "Downloading Steam Engine Poster.pdf").pack()
ftp.retrbinary('RETR ' + filename, handleDownload)
Label(app, text = "Closing FTP connection!").pack()
ftp.close()
ftp = FTP('sciphigames.com')
Label(app, text = "Login").pack()
username = StringVar(None)
username = Entry(app, text = "Username: ")
username.pack()
password = StringVar(None)
password = Entry(app, text = "Password: ")
password.pack()
button = Button(app, text = "Login!", command = login)
button.pack()
app.mainloop()
Solution
You get "Transfer Complete" because retrlines
returns the response code, not the listing. If you check the documentation, you'll see that apart from the command, there's a second argument, a callback, that will be called for each line returned. By default it just prints the line to the standard output.
lines = []
def append_line(line):
lines.append(line)
ftp.retrlines('LIST', append_line)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow