使用wxPython获取系统剪贴板中的数据的教程

yipeiwu_com5年前Python基础

涉及到开发桌面程序,尤其是文本处理,剪贴板就很常用,不像 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()


相关文章

Python 余弦相似度与皮尔逊相关系数 计算实例

Python 余弦相似度与皮尔逊相关系数 计算实例

夹角余弦(Cosine) 也可以叫余弦相似度。 几何中夹角余弦可用来衡量两个向量方向的差异,机器学习中借用这一概念来衡量样本向量之间的差异。 (1)在二维空间中向量A(x1,y1)与向量...

python DataFrame 取差集实例

需求:给定一个dataframe和一个list,list中存放的是dataframe中某一列的元素,删除dataframe中与list元素重复的行(即取差集)。 在网上搜了一圈,好像没看...

Pandas+Matplotlib 箱式图异常值分析示例

我就废话不多说了,直接上代码吧! # -*- coding: utf-8 -*- import pandas as pd import matplotlib.pyplot as...

Python文件操作函数用法实例详解

这篇文章主要介绍了Python文件操作函数用法实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 字符编码 二进制和字符之间的转换...

python写xml文件的操作实例

本文实例讲述了python写xml文件的操作的方法,分享给大家供大家参考。具体方法如下: 要生成的xml文件格式如下: <?xml version="1.0" ?...