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

(编辑:jimmy 日期: 2024/10/3 浏览:2)

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


一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。