【发布时间】:2019-01-07 14:46:49
【问题描述】:
我在 Python Gtk 中有一个应用程序。我的主文件中有我的主应用程序类。然后,我将所有对话框放在不同的文件中。除了标准的 Gtk 响应代码之外,我需要能够将自定义数据从对话框传递/返回到主应用程序类,这里是一些基本示例代码,因为我自己的代码很长:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class DialogWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Dialog Example")
self.set_border_width(6)
button = Gtk.Button("Open dialog")
button.connect("clicked", self.on_button_clicked)
self.add(button)
def on_button_clicked(self, widget):
dialog = DialogExample(self)
response = dialog.run()
if response == Gtk.ResponseType.OK:
print("The OK button was clicked")
elif response == Gtk.ResponseType.CANCEL:
print("The Cancel button was clicked")
dialog.destroy()
win = DialogWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
单独文件中的对话窗口:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class DialogExample(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(self, "My Dialog", parent, 0,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OK, Gtk.ResponseType.OK))
self.set_default_size(150, 100)
label = Gtk.Label("This is a dialog to display additional information")
box = self.get_content_area()
box.add(label)
self.show_all()
作为标准,我们将Gtk.ResponseType 应用于按钮。但是,如果我们想返回一些自定义数据——不仅仅是一个简单的响应代码——作为进一步的代码示例怎么办:
class DialogExample(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(self, "My Dialog", parent, 0)
self.set_default_size(150, 100)
label = Gtk.Label("This is a dialog to display additional information")
button = Gtk.Button("Return something")
button.connect("clicked", self.on_button_clicked)
box = self.get_content_area()
box.add(label)
self.show_all()
def on_button_clicked(self, widget):
if SOME_CONDITION:
return <CUSTOM_RESPONSE>
else:
return <ALT_CUSTOM_RESPONSE>
当我做最后一个例子时,对话框没有返回任何东西,我想做类似的事情:
class DialogWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Dialog Example")
self.set_border_width(6)
button = Gtk.Button("Open dialog")
button.connect("clicked", self.on_button_clicked)
self.add(button)
def on_button_clicked(self, widget):
dialog = DialogExample(self)
response = dialog.run()
if response == <CUSTOM_RESPONSE>:
#do something with <CUSTOM_RESPONSE>
elif response == <ALT_CUSTOM_RESPONSE>:
#do something different with <ALT_CUSTOM_RESPONSE>
dialog.destroy()
win = DialogWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
DialogExample 窗口不会销毁/关闭,也没有返回任何内容,应用程序基本上只是暂停,因为它认为没有更多方法可以运行 - 尽管在返回自定义数据后还有很多工作要做(我需要然后开始向数据库添加记录)。
[更新]
我现在已经尝试了很多不同的方法来解决这个问题,我不可能在这里全部列出。我无休止地寻找某种答案,这似乎不是互联网上任何人都能做到的事情。
【问题讨论】:
标签: python python-3.x gtk gtk3 pygobject