如何共享剪贴板数据beetween在GTK程序?(How to share clipboard da

2019-10-30 13:16发布

我想要:

  1. 把一些文字到剪贴板
  2. 结束我的计划
  3. 数据粘贴到其他应用程序

但我的代码是不工作:

#!/usr/bin/env python

import sys
import gtk

if __name__ == '__main__':
    if sys.argv[1] == 'put':
        clipboard = gtk.clipboard_get()
        clipboard.set_text('It\'s working')
        clipboard.store()
    elif sys.argv[1] == 'get':
        clipboard = gtk.clipboard_get()
        text = clipboard.wait_for_text()
        print('Text from clipboard: ', text)

我把文本剪贴板通过执行python2 ./test.py put之后,我想从剪贴板获得分机与python2 ./test.py get

为什么clipboard.wait_for_text()总是返回无?

Answer 1:

你要进入主循环,让剪贴板经理获取文本( PyGTK的剪贴板set_text的影响仅在进程运行时仍然存在 )

#!/usr/bin/env python

import sys
import gtk, gobject


if __name__ == '__main__':
    if sys.argv[1] == 'put':
        clipboard = gtk.clipboard_get()
        clipboard.set_text('It\'s working')
        clipboard.store()
    elif sys.argv[1] == 'get':
        clipboard = gtk.clipboard_get()
        text = clipboard.wait_for_text()
        if text == None:
            print("empty text")
        else:
            print('Text from clipboard: ', text)
gobject.timeout_add(100, gtk.main_quit)
gtk.main()  


Answer 2:

对于GTK3:

#!/usr/bin/env python3

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk

class CopyToClipboard(Gtk.Window):
    def __init__(self, text):
        super(CopyToClipboard, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(text, -1)
        clipboard.store()

CopyToClipboard("your text goes here\n")


文章来源: How to share clipboard data beetween processes in GTK?
标签: python pygtk