如何构建使用GUI的程序?

时间:2013-04-25 13:10:57

标签: python gtk3 pygobject

我刚刚在两周前开始使用Python。现在,我正在尝试使用Glade创建使用PyGObject的GUI。

然而,我对这个程序的总体布局应该是多么困惑。

我应该为主程序和信号使用一个类,还是应该将它们分开?

对此有“最佳方法”吗?

或者就像我以下的卑微方法一样,我根本不应该使用课程吗?

如何在以下示例中的功能之间进行通信?例如,如何将parent函数的Gtk.MessageDialog参数设置为程序的主窗口?

Python代码:

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

CalculatorGUI.glade档案的成分:http://pastebin.com/K2wb7Z4r

该计划的截图:

enter image description here

2 个答案:

答案 0 :(得分:2)

对于刚刚开始使用python编程的人,我强烈建议尝试手工编程GUI,而不是像GLADE,wxGLADE这样的工具......

以这种方式做到这一点将教会您需要了解的有关程序结构的所有信息。特别是像这样的简单程序。

答案 1 :(得分:2)

我会使用类,这样就可以保持方法之间共享应用程序的状态/变量。您的应用程序的具体设计取决于您的需求。这是我个人简单应用的基本模板:

# -*- 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()

您可以在要点https://gist.github.com/carlos-jenkins/5467657

上查看完整模板

如果你学习正确的方法并且立即使用Glade,你会学得更好,这将对你有所帮助并降低代码复杂性,否则会被不必要且难以维护的代码所困扰。