gpt4 book ai didi

python - 如何构建使用 GUI 的程序?

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:42 33 4
gpt4 key购买 nike

大约 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

程序截图:

enter image description here

最佳答案

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

通过艰苦的方式完成这项工作将教会您有关程序结构的所有知识。尤其是像这样的简单程序。

关于python - 如何构建使用 GUI 的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16215677/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com