How can a program that uses GUI be constructed?

末鹿安然 提交于 2020-01-05 06:41:09

问题


I have just started Python, about 2 weeks ago. Now, I am trying to create GUIs with PyGObject using Glade.

However, I am puzzled on how the general layout of the program should be.

Should I use a class for the main program and the signals or should I separate them?

Is there a "best approach" for this?

Or as in below humble approach of mine, should I not use classes at all?

How do I communicate between functions in the below example? For example, how do I set parent parameter of Gtk.MessageDialog function as the main window of the program?

Python Code:

#!/usr/bin/python

try:
    from gi.repository import Gtk
except:
    print('Cannot Import Gtk')
    sys.exit(1)

# Confirm and exit when Quit button is clicked.
def on_button_quit_clicked(widget):
    confirmation_dialog = Gtk.MessageDialog(parent = None,
                                            flags = Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                            type = Gtk.MessageType.QUESTION,
                                            buttons = Gtk.ButtonsType.YES_NO,
                                            message_format = 
                                            'Are you sure you want to quit?')
    print ('Quit confirmation dialog is running.')
    confirmation_response = confirmation_dialog.run()                                              
    if confirmation_response == Gtk.ResponseType.YES:
        print ('You have clicked on YES, quiting..')
        Gtk.main_quit()
    elif confirmation_response == Gtk.ResponseType.NO:
        print ('You have clicked on NO')
    confirmation_dialog.destroy()
    print ('Quit confirmation dialog is destroyed.')

# Show About dialog when button is clicked.
def on_button_about_clicked(widget):
    print ('About')

# Perform addition when button is clicked.
def on_button_add_clicked(widget):
    print ('Add')

# Main function
def main():
    builder = Gtk.Builder()
    builder.add_from_file('CalculatorGUI.glade')

    signalHandler = {
    'on_main_window_destroy': Gtk.main_quit,
    'on_button_quit_clicked': on_button_quit_clicked,
    'on_button_about_clicked': on_button_about_clicked,
    'on_button_add_clicked': on_button_add_clicked
    }
    builder.connect_signals(signalHandler)

    main_window = builder.get_object('main_window')  
    main_window.show_all()

    Gtk.main()
    print ('Program Finished!')

# If the program is not imported as a module, then run.
if __name__ == '__main__':
    main()

Ingredients of CalculatorGUI.glade file: http://pastebin.com/K2wb7Z4r

A screenshot of the program:


回答1:


For someone who just started to program in python I will strongly recommend to try to program GUIs by hand not with tools like GLADE, wxGLADE...

Doing this the hard way will teach you everything you need to know about the program structure. Especially with simple programs like this.




回答2:


I would use classes, in this way you can keep the state/variables of the application shared between methods. The specific design of your application depends on your needs. This is my personal base template for simple apps:

# -*- coding:utf-8 -*-
#
# Copyright (C) 2013 Carlos Jenkins <cjenkins@softwarelibrecr.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
PyGObject example with Glade and GtkBuilder.

Check dependencies are installed:

    sudo apt-get install python2.7 python-gi gir1.2-gtk-3.0

To execute:

    python main.py

Python reference still unavailable, nevertheless C reference documentation is
available at:

    https://developer.gnome.org/gtk3/

And a good tutorial at:

    https://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html

"""

from gi.repository import Gtk
from os.path import abspath, dirname, join

WHERE_AM_I = abspath(dirname(__file__))

class MyApp(object):

    def __init__(self):
        """
        Build GUI
        """

        # Declare states / variables
        self.counter = 0

        # Build GUI from Glade file
        self.builder = Gtk.Builder()
        self.glade_file = join(WHERE_AM_I, 'gui.glade')
        self.builder.add_from_file(self.glade_file)

        # Get objects
        go = self.builder.get_object
        self.window = go('window')
        self.button = go('button')

        # Connect signals
        self.builder.connect_signals(self)

        # Configure interface
        self.window.connect('delete-event', lambda x,y: Gtk.main_quit())

        # Everything is ready
        self.window.show()

    def _btn_cb(self, widget, data=None):
        """
        Button callback
        """
        self.counter += 1
        print('Button pressed {} times.'.format(self.counter))


if __name__ == '__main__':
    gui = MyApp()
    Gtk.main()

You can check the full template at the gist https://gist.github.com/carlos-jenkins/5467657

And if you're learning better if you learn the right way and use Glade right away, this will help you a lot and reduce code complexity, that would otherwise be plagued with unnecessary and hard to maintain code.



来源:https://stackoverflow.com/questions/16215677/how-can-a-program-that-uses-gui-be-constructed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!