Nei*_*nro 3 python quickly application-development gtk3
我几乎完成了我的 Ubuntu App Showdown 应用程序,但想让它更加健壮,在应用程序退出时,我遍历打开的文件,检查未保存的文件,如果发现任何文件,我会弹出一个对话框通知用户。
我想要发生的是,如果用户取消对话框,程序将恢复,但是如果用户单击确定,对话框和主窗口都应该关闭。
这是我到目前为止。
self.connect("delete-event", self.CheckSave)
def CheckSave(self, arg1, arg2):
unsaved = False
for doc in self.Documents:
if doc.Saved == False:
unsaved = True
if unsaved:
print("Unsaved document")
Dialog = Gtk.Dialog("Really quit?", 0, Gtk.DialogFlags.MODAL)
Dialog.add_button(Gtk.STOCK_NO, Gtk.ResponseType.CANCEL)
Dialog.add_button(Gtk.STOCK_YES, Gtk.ResponseType.OK)
box = Dialog.get_content_area()
label1 = Gtk.Label("There are unsaved file(s).")
label2 = Gtk.Label("Are you sure you want to quit?")
box.add(label1)
box.add(label2)
box.show_all()
response = Dialog.run()
print(response)
if response == Gtk.ResponseType.OK:
return(False)
else:
return(True)
Dialog.destroy()
Run Code Online (Sandbox Code Playgroud)
当对话框运行时,它从不输出 ResponseType.OK 或 ResponseType.CANCEL 值,我得到随机负数,如 -4 或 -6,对话框也永远不会关闭,主窗口不断发出对话框,需要 CTRL+c 退出它。
这段代码有几个问题。
dialog.destroy() 方法将永远不会被调用,您在此调用之前返回您的函数。
看看Gtk.MessageDialog。它将处理一些您需要使用常规Gtk.Dialog.
阅读PEP-8。这不是规则,而是普遍做法。大写名称用于类,属性和方法应该是驼峰式或 with_underscore。
for 循环效率低下。并且整个方法可以少缩进一个制表符。
这是一些示例代码,pep-8 和 messagedialog 仍然需要完成。
def confirm_close(self, widget, event):
unsaved = False
for doc in self.Documents:
if not doc.Saved:
unsaved = True
break # Break here, no need to check more documents
if not unsaved:
Gtk.main_quit()
#TODO: build the messagedialog
dialog = Gtk.MessageDialog(....)
response = dialog.run()
if response == Gtk.ResponseType.OK:
# Really quit the application
Gtk.main_quit()
# Close the dialog and keep the main window open
dialog.destroy()
return True
Run Code Online (Sandbox Code Playgroud)