1

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

但是,我对程序的总体布局应该如何感到困惑。

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

对此有“最佳方法”吗?

或者就像我下面的谦虚方法一样,我根本不应该使用类吗?

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

蟒蛇代码:

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

程序截图:

在此处输入图像描述

4

2 回答 2

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,那么您将学习得更好,这将对您有很大帮助并降低代码复杂性,否则会受到不必要且难以维护的代码的困扰。

于 2013-04-26T14:14:48.427 回答
2

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

以艰难的方式做到这一点将教会您有关程序结构的所有知识。尤其是像这样的简单程序。

于 2013-04-25T13:45:48.657 回答