Kika 是一个连接至 ftp 站点的图形脚本. 如果登录成功,Kika 就在状态栏展示一个连接图标.
否则就显示断开图标.
专题:wxpython中文教程
使用了来自 python标准库的 ftplib 模块.
如没有 ftp 帐号的话,可以尝试登录到一些匿名 ftp 站点.
例子:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#kika.py
from ftplib import FTP, all_errors
import wx
class MyStatusBar(wx.StatusBar):
def __init__(self, parent):
wx.StatusBar.__init__(self, parent)
self.SetFieldsCount(2)
self.SetStatusText('欢迎来到 Kika', 0)
self.SetStatusWidths([-5, -2])
self.icon = wx.StaticBitmap(self, -1, wx.Bitmap
('icons/disconnected-16.png'))
self.Bind(wx.EVT_SIZE, self.OnSize)
self.PlaceIcon()
def PlaceIcon(self):
rect = self.GetFieldRect(1)
self.icon.SetPosition((rect.x+3, rect.y+3))
def OnSize(self, event):
self.PlaceIcon()
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(250, 270))
wx.StaticText(self, -1, 'FTP 站点', (10, 20))
wx.StaticText(self, -1, '登入', (10, 60))
wx.StaticText(self, -1, '口令', (10, 100))
self.ftpsite = wx.TextCtrl(self, -1, 'wxpython.cn',
(110, 15), (120, -1))
self.login = wx.TextCtrl(self, -1, '', (110, 55), (120, -1))
self.password = wx.TextCtrl(self, -1, '', (110, 95),
(120, -1), style=wx.TE_PASSWORD)
self.ftp = None
con = wx.Button(self, 1, '连 接', (10, 160))
discon = wx.Button(self, 2, '断开连接', (120, 160))
self.Bind(wx.EVT_BUTTON, self.OnConnect, id=1)
self.Bind(wx.EVT_BUTTON, self.OnDisConnect, id=2)
self.Bind(wx.EVT_TEXT, self.OnParaChange,
id=self.password.GetId())
self.Bind(wx.EVT_TEXT, self.OnParaChange,
id=self.login.GetId())
self.statusbar = MyStatusBar(self)
self.SetStatusBar(self.statusbar)
self.Center()
def OnConnect(self, event):
if not self.ftp:
ftpsite = self.ftpsite.GetValue()
login = self.login.GetValue()
password = self.password.GetValue()
try:
self.ftp = FTP(ftpsite)
var = self.ftp.login(login, password)
self.statusbar.SetStatusText('用户已连接')
self.statusbar.icon.SetBitmap
(wx.Bitmap('icons/connected-16.png'))
except AttributeError:
self.statusbar.SetForegroundColour(wx.RED)
self.statusbar.SetStatusText('错误的连接参数')
self.ftp = None
def OnDisConnect(self, event):
if self.ftp:
self.ftp.quit()
self.ftp = None
self.statusbar.SetStatusText('用户已断开')
self.statusbar.icon.SetBitmap
(wx.Bitmap('icons/disconnected-16.png'))
def OnParaChange(self, event):
self.statusbar.SetStatusText('')
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'Kika')
frame.Center()
frame.Show(True)
return True
app = MyApp(0)
app.MainLoop()
请注意,当窗口每次缩放时,我们必须将图标重新放到新的位置上去.
图:Kika