2012-01-01 152 views
1

我有一個快速的問題,它聽起來很愚蠢。但對於我的愛,我無法在網上或自己找到解決方案!我正在嘗試爲我自己製作一個使用python的FTP客戶端,並且我試圖在Tkinter中創建一個列表框,以顯示FTP服務器上的所有文件名。但我無法顯示文字!這裏是我到目前爲止下面的代碼:Python 2.7 Tkinter和ftplib

# 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() 

回答

2

你得到「傳輸完成」,因爲retrlines返回響應代碼,而不是上市。如果您檢查文檔,您會看到除了該命令之外,還有第二個參數,即回調函數,將針對每個返回的行調用它。默認情況下,它只是將行打印到標準輸出。

lines = [] 
def append_line(line): 
    lines.append(line) 
ftp.retrlines('LIST', append_line) 
+0

你會碰巧知道回電是什麼嗎? – user1114215 2012-01-01 14:54:13

+1

我已經添加了一些代碼來解釋如何做到這一點。你可以使它更加緊湊:'ftp.retrlines('LIST',lines.append)' – 2012-01-01 14:56:15

+0

注意:在示例代碼中,'ftp.retrlines'返回後,'lines'包含一個列表,其中每個元素是一個FTP服務器回覆的行數。現在,由您來處理它們:) – 2012-01-01 14:57:29