wxPython 教程(九) wxPython 拖拽

转自:http://thisis.yorven.site/blog/index.php/2017/10/09/wxpython-tuozhuai/

维基百科:在电脑图形用户界面里,拖拽是指点击一个虚拟对象并拖移至另一个位置或者另一个虚拟对象之上。一般来说,它可以被用来发起多种行为,或者创建两个抽象对象之间的各种关联。
拖拽是图形用户界面中最显眼的操作,通过它可以做很多复杂的事情。
在拖拽中,我们将一些数据从一个源位置移动到目标位置,所以我们必须有:

  • 一些数据
  • 一个数据来源
  • 一个数据目标

在 wxPython 中,我们有两个预定义的数据目标:wx.TextDropTarget 和 wx.FileDropTarget。

wx.TextDropTarget

文本拖拽

#!/usr/bin/python

# dragdrop.py

import os
import wx

class MyTextDropTarget(wx.TextDropTarget):
def __init__(self, object):
wx.TextDropTarget.__init__(self)
self.object = object

def OnDropText(self, x, y, data):
self.object.InsertStringItem(0, data)


class DragDrop(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(650, 500))

splitter1 = wx.SplitterWindow(self, -1, style=wx.SP_3D)
splitter2 = wx.SplitterWindow(splitter1, -1, style=wx.SP_3D)
self.dir = wx.GenericDirCtrl(splitter1, -1, dir='/home/', style=wx.DIRCTRL_DIR_ONLY)
self.lc1 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)
self.lc2 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)

dt = MyTextDropTarget(self.lc2)
self.lc2.SetDropTarget(dt)
self.Bind(wx.EVT_LIST_BEGIN_DRAG, self.OnDragInit, id=self.lc1.GetId())

tree = self.dir.GetTreeCtrl()

splitter2.SplitHorizontally(self.lc1, self.lc2)
splitter1.SplitVertically(self.dir, splitter2)

self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelect, id=tree.GetId())

self.OnSelect(0)
self.Centre()
self.Show(True)

def OnSelect(self, event):
list = os.listdir(self.dir.GetPath())
self.lc1.ClearAll()
self.lc2.ClearAll()
for i in range(len(list)):
if list[i][0] != '.':
self.lc1.InsertStringItem(0, list[i])

def OnDragInit(self, event):
text = self.lc1.GetItemText(event.GetIndex())
tdo = wx.TextDataObject(text)
tds = wx.DropSource(self.lc1)
tds.SetData(tdo)
tds.DoDragDrop(True)


app = wx.App()
DragDrop(None, -1, 'dragdrop.py')
app.MainLoop()

wx.FileDropTarget

在下面的例子中,我们将开发一个特别方便的功能,即将文件拖至编辑器显示其内容。

#!/usr/bin/python

# filedrop.py

import wx

class FileDrop(wx.FileDropTarget):
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window

def OnDropFiles(self, x, y, filenames):

for name in filenames:
try:
file = open(name, 'r')
text = file.read()
self.window.WriteText(text)
file.close()
except IOError, error:
dlg = wx.MessageDialog(None, 'Error opening filen' str(error))
dlg.ShowModal()
except UnicodeDecodeError, error:
dlg = wx.MessageDialog(None, 'Cannot open non ascii filesn' str(error))
dlg.ShowModal()

class DropFile(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size = (450, 400))

self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
dt = FileDrop(self.text)
self.text.SetDropTarget(dt)
self.Centre()
self.Show(True)


app = wx.App()
DropFile(None, -1, 'filedrop.py')
app.MainLoop()

这一节简要简述了 wxPython 拖拽 。

wxPython 教程(九) wxPython 拖拽

https://www.laoyuyu.me/2019/02/14/wxpython/wx_python_9/

作者

AriaLyy

发布于

2019-02-14

许可协议

CC BY-NC-SA 4.0

评论