涉及到开发桌面程序,尤其是文本处理,剪贴板就很常用,不像 java 中那么烦锁,wxpython 中访问剪贴板非常简单,寥寥几句足以。
# 取得剪贴板并确保其为打开状态
text_obj = wx.textdataobject()
wx.theclipboard.open()
if wx.theclipboard.isopened() or wx.theclipboard.open():
# do something…
wx.theclipboard.close()
取值:
if wx.theclipboard.getdata(text_obj):
text = text_obj.gettext()
写值:
text_obj.settext(‘要写入的值’)
wx.theclipboard.setdata(text_obj)
下面的例子中,点击 copy 会将文本框中的值复制到剪贴板,点击 paste 会将剪贴板中的文本粘贴到文本框中。
“””
get text from and put text on the clipboard.
“””
import wx
class myframe(wx.frame):
def __init__(self):
wx.frame.__init__(self, none, title=’accessing the clipboard’, size=(400, 300))
# components
self.panel = wx.panel(self)
self.text = wx.textctrl(self.panel, pos=(10, 10), size=(370, 220))
self.copy = wx.button(self.panel, wx.id_any, label=’copy’, pos=(10, 240))
self.paste = wx.button(self.panel, wx.id_any, label=’paste’, pos=(100, 240))
# event bindings.
self.bind(wx.evt_button, self.oncopy, self.copy)
self.bind(wx.evt_button, self.onpaste, self.paste)
def oncopy(self, event):
text_obj = wx.textdataobject()
text_obj.settext(self.text.getvalue())
if wx.theclipboard.isopened() or wx.theclipboard.open():
wx.theclipboard.setdata(text_obj)
wx.theclipboard.close()
def onpaste(self, event):
text_obj = wx.textdataobject()
if wx.theclipboard.isopened() or wx.theclipboard.open():
if wx.theclipboard.getdata(text_obj):
self.text.setvalue(text_obj.gettext())
wx.theclipboard.close()
app = wx.app(false)
frame = myframe()
frame.show(true)
app.mainloop()