開發桌面應用時,剪貼板交互是高頻需求。wxPython 作為成熟的 Python GUI 庫,提供了極簡潔的剪貼板 API。本文從核心對象、讀寫流程、完整 GUI 示例三個維度講解。
wx.TextDataObject:承載純文本數據的容器。wx.TheClipboard:全局剪貼板單例,需打開 → 操作 → 關閉三步走。text_obj = wx.TextDataObject()
if wx.TheClipboard.Open():
if wx.TheClipboard.GetData(text_obj):
text = text_obj.GetText()
wx.TheClipboard.Close()
text_obj = wx.TextDataObject()
text_obj.SetText('要寫入的值')
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(text_obj)
wx.TheClipboard.Close()
""" 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))
self.panel = wx.Panel(self)
self.text = wx.TextCtrl(self.panel, pos=(10, 10), size=(370, 220), style=wx.TE_MULTILINE)
self.copy = wx.Button(self.panel, label='Copy', pos=(10, 240))
self.paste = wx.Button(self.panel, label='Paste', pos=(100, 240))
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()
Open() 並檢查返回值:剪貼板可能被其他進程佔用,打開失敗時不應強行操作。Close():否則會鎖定剪貼板導致其他程序無法訪問。wx.BitmapDataObject、wx.HTMLDataObject、wx.FileDataObject 等專用對象。IsOpened() 檢查可避免重複打開報錯。代碼無需修改即可在 Python 3 + wxPython 4 下運行,模塊導入方式統一為 import wx。
掌握剪貼板操作,讓你的桌面工具具備「複製即用、粘貼即得」的原生體驗。