سؤال

I want to get selected text automatically in python, using gtk module. There is a code to get selected text from anywhere:

#!/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()

But i don't want to this exactly.

i dont want to click a button. I want to see the selected text only, not after a button clicking. When i start the program ; it must show me the selected text automatically (without clicking any button!).

I want to this exactly :

#!/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()

This program must show me the selected text in the entry box automatically.

Only this. But i can't do!

i expect " gtk.SelectionData.get_text " will show me the selected text but it returns "<method 'get_text' of 'gtk.SelectionData' objects>" .

And also i tried self.s_text=gtk.SelectionData.get_text()

But it returns me :

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

How can i do this? And also i am a beginner python programmer; if u can write the code ; it will be very good for me :) thanks a lot !!

هل كانت مفيدة؟

المحلول

self.s_text=gtk.SelectionData.get_text

Method get_text is not called yet! You are assigning self.s_text to the method(function) object itself. Which is converted to string in "Selected Text is : %s" % self.s_text
You should changed it to:

self.s_text=gtk.SelectionData.get_text()

EDIT: But since you need a SelectionData object to pass to this method, the whole idea is wrong. I combined you two codes as something working:

#!/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()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top