大约 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
程序截图: