【发布时间】:2013-04-26 22:23:01
【问题描述】:
大约 2 周前,我刚刚开始使用 Python。现在,我正在尝试使用 Glade 使用 PyGObject 创建 GUI。
但是,我对程序的总体布局应该如何感到困惑。
我应该为主程序和信号使用一个类还是应该将它们分开?
对此有“最佳方法”吗?
或者像下面我的谦虚方法,我应该根本不使用类吗?
如何在以下示例中的函数之间进行通信?例如,如何将Gtk.MessageDialog函数的parent参数设置为程序的主窗口?
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
程序截图:
【问题讨论】:
-
提示:不要只用
except,用except ImportError更准确。 -
@SantoshKumar 感谢您的提示 :)