Domanda

I'm a little bit lost building a UI with Glade and Python 3. I've made a GtkWindows, which has a GtkBox. The GtkBox has a GtkButton and two GtkPaned objects. Each of the panes have a GtkEntry object. Eventually, I want this to become a login form: the user hits a "Connect" button, and the text values of the two GtkEntry objects get picked up by a handler and sent off to a server. The relevant portion of my code looks like this:

class Handler:
    def on_MainWindow_destroy(self, *args):
        Gtk.main_quit(*args)

    def on_LoginButton_clicked(self, *args):
        print(*args)
        #do other stuff


if __name__ == '__main__':
    builder = Gtk.Builder()
    builder.add_from_file('myui.glade')
    builder.connect_signals(Handler())

    window = builder.get_object("MainWindow")
    window.show_all()

    Gtk.main()

(Slightly off the original topic of my question: what's the right way to name GObjects in Glade? CamelCase? lowercase_underscores?)

I want LoginButton to do something with the text of both fields when it gets clicked. However, Glade only gives you the option of passing a single object to the handler. I can attach the on_LoginButton_clicked method to LoginButton twice and pass the username field to it on the first call and the password field to it on the second call, but that seems very messy. What's the right way to do this?

È stato utile?

Soluzione

You need to have a reference to both objects in a class using GtkBuilder's get_object(). Then, in the callback of the button just get both text with self.myfield1.get_text() or so. Check this template on how to structure a PyGObject application:

How can a program that uses GUI be constructed?

Hope it helps.

EDIT: About the naming scheme, I would use whatever naming scheme is used on the language that would use the Glade file. When programming in PyGObject, I name the objects on the Glade file the same as Python variables so I can do this:

[...]
go = self.builder.get_object
self.window = go('window')
self.my_foobar = go('my_foobar')
[...]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top