获取所选文本(python-gtk)

时间:2012-12-23 23:05:48

标签: python gtk selection textselection selectedtext

我希望使用gtk模块在python中自动获取所选文本。 有一个代码可以从任何地方获取所选文本:

#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk

class GetSelectionExample:
    # Signal handler invoked when user clicks on the
    # "Get String Target" button
    def get_stringtarget(self, widget):
        # And request the "STRING" target for the primary selection
        ret = widget.selection_convert("PRIMARY", "STRING")
        return

    # Signal handler called when the selections owner returns the data
    def selection_received(self, widget, selection_data, data):

        # Make sure we got the data in the expected form
        if str(selection_data.type) == "STRING":
            # Print out the string we received
            print "STRING TARGET: %s" % selection_data.get_text()

        elif str(selection_data.type) == "ATOM":
            # Print out the target list we received
            targets = selection_data.get_targets()
            for target in targets:
                name = str(target)
                if name != None:
                    print "%s" % name
                else:
                    print "(bad target)"
        else:
            print "Selection was not returned as \"STRING\" or \"ATOM\"!"

        return False


    def __init__(self):
        # Create the toplevel window
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title("Get Selection")
        window.set_border_width(10)
        window.connect("destroy", lambda w: gtk.main_quit())

        vbox = gtk.VBox(False, 0)
        window.add(vbox)
        vbox.show()

        # Create a button the user can click to get the string target
        button = gtk.Button("Get String Target")
        eventbox = gtk.EventBox()
        eventbox.add(button)
        button.connect_object("clicked", self.get_stringtarget, eventbox)
        eventbox.connect("selection_received", self.selection_received)
        vbox.pack_start(eventbox)
        eventbox.show()
        button.show()

        window.show()

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    GetSelectionExample()
    main()

但我不想这样做。

我不想点击按钮。我想只看到所选文本,而不是单击按钮后。当我启动程序时;它必须自动显示所选文本(不点击任何按钮!)。

我想要这样:

#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk


class MyApp (object):
    def __init__(self):
        self.window=gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("delete_event", gtk.main_quit )
        self.entry = gtk.Entry()

        try:
            self.s_text=gtk.SelectionData.get_text
            # i expect that : the selected text (from anywhere)
            # but it returns me :
            #<method 'get_text' of 'gtk.SelectionData' objects>
        except:
            self.s_text="it must be selected text"

        self.entry.set_text("Selected Text is : %s"  % self.s_text )

        self.window.add(self.entry)
        self.window.show_all()
    def main(self):
        gtk.main()

app=MyApp()
app.main()

此程序必须自动在输入框中显示所选文本。

只有这一点。但我做不到!

我希望“gtk.SelectionData.get_text”会显示所选文字,但会返回“<method 'get_text' of 'gtk.SelectionData' objects>”。

我也试过self.s_text=gtk.SelectionData.get_text()

但它让我回答:

self.s_text=gtk.SelectionData.get_text()
TypeError: descriptor 'get_text' of 'gtk.SelectionData' object needs an argument

我该怎么做?而且我也是一名初学python程序员;如果你可以写代码;这对我来说非常好:) 非常感谢!!

1 个答案:

答案 0 :(得分:1)

self.s_text=gtk.SelectionData.get_text

方法get_text尚未调用!您正在为方法(函数)对象本身分配self.s_text。在"Selected Text is : %s" % self.s_text中将其转换为字符串 你应该把它改成:

self.s_text=gtk.SelectionData.get_text()

编辑:但是因为你需要一个SelectionData对象传递给这个方法,所以整个想法都是错误的。我将两个代码组合起来作为工作:

#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk


class MyApp (object):
    def __init__(self):
        self.window=gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("delete_event", gtk.main_quit )
        self.entry = gtk.Entry()
        self.window.selection_convert("PRIMARY", "STRING")
        self.window.connect("selection_received", self.selection_received)
        self.window.add(self.entry)
        self.window.show_all()
    # Signal handler called when the selections owner returns the data
    def selection_received(self, widget, selection_data, data):
        print 'selection_data.type=%r'%selection_data.type
        # Make sure we got the data in the expected form
        if str(selection_data.type) == "STRING":
            self.entry.set_text("Selected Text is : %s"  % selection_data.get_text())

        elif str(selection_data.type) == "ATOM":
            # Print out the target list we received
            targets = selection_data.get_targets()
            for target in targets:
                name = str(target)
                if name != None:
                    self.entry.set_text("%s" % name)
                else:
                    self.entry.set_text("(bad target)")
        else:
            self.entry.set_text("Selection was not returned as \"STRING\" or \"ATOM\"!")

        return False
    def main(self):
        gtk.main()

app=MyApp()
app.main()