桌面應用常需讀寫剪貼板。wxPython 提供簡潔 API:wx.TextDataObject 處理文字,wx.TheClipboard 管理剪貼板開啟/關閉與資料傳輸。本文示範基本讀寫與完整 GUI 範例。
import wx
# 寫入文字
text_obj = wx.TextDataObject()
text_obj.SetText('要寫入的值')
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(text_obj)
wx.TheClipboard.Close()
# 讀取文字
text_obj = wx.TextDataObject()
if wx.TheClipboard.Open():
if wx.TheClipboard.GetData(text_obj):
text = text_obj.GetText()
wx.TheClipboard.Close()
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='剪貼板示範', size=(400, 300))
panel = wx.Panel(self)
self.text = wx.TextCtrl(panel, pos=(10, 10), size=(370, 220), style=wx.TE_MULTILINE)
copy_btn = wx.Button(panel, label='Copy', pos=(10, 240))
paste_btn = wx.Button(panel, label='Paste', pos=(100, 240))
self.Bind(wx.EVT_BUTTON, self.OnCopy, copy_btn)
self.Bind(wx.EVT_BUTTON, self.OnPaste, paste_btn)
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() 釋放鎖定。IsOpened() 檢查是否已開啟,避免重複開啟導致錯誤。TextDataObject 僅支援純文字;圖片、檔案等需使用 wx.BitmapDataObject, wx.FileDataObject 等。Open() 失敗:建議重試機制或提示使用者。wxPython 剪貼板 API 簡單易用,適合快速開發桌面文字處理工具。