Narek Babajanyan
Narek Babajanyan

Reputation: 21

Get value from gtk.Entry in PyGTK

I am working on a PyGTK GUI project, and i would like to know, is there any way to get variable value from gtk.Entry?

        text=gtk.Entry(0)
    text.set_activates_default(True)
    port = text.get_text()

This doesn't work as, the text box is empty by default, and get_text() returns empty string, any ideas?

Upvotes: 2

Views: 8727

Answers (3)

Wes
Wes

Reputation: 964

This doesn't work as, the text box is empty by default, and get_text() returns empty string, any ideas?

Sounds like you're looking for getting the text after some user input. In order to do this, gtk uses signals that allow you to connect a user action to some function that will do something. In your case you want this function to get the text from the input. Because you haven't described the user interaction I'll give the simplest example. If you had a button in your GUI that, when clicked, would grab whatever is typed in the entry at that moment, you'd do this:

button = gtk.Button( 'Click Me')
button.connect( 'clicked', on_button_click )

Then, you define the on_button_click function:

def on_button_click(self, widget, data=None):
    port = text.get_text()
    print 'Port: %s' % port

So with the sample code above, you'd have a button that, when clicked, grabs the text from your gtk.Entry.

Check out this link for a simple example on how to use signals in pygtk

Upvotes: 3

Froyo
Froyo

Reputation: 18477

Since your text field is by default empty, get_text() would return empty string. Add a button callback function or some other function. So whenever that function is called, you would get the string from the Entry using

text.gtk_text()

You might want to use self here. since you'll be accessing entry in some other function and not in main thread, use

self.text=gtk.Entry()
self.text.set_activates_default(True)

def foo(self,widget,event): # some callback function
    port = self.text.get_text()
    print port

Upvotes: 1

Don Question
Don Question

Reputation: 11614

The retrieving method is the correct one, but right after the creation, the user can't yet have typed anyting into the field.

You would have to wait for the user to actually type something into the field, and afterwards calling get_text().

Upvotes: 0

Related Questions