继承Gtk.MessageDialog时遭遇弃用警告与transient_for类型错误的问题咨询
继承Gtk.MessageDialog时遭遇弃用警告与transient_for类型错误的问题咨询
我在几个项目里用了一个继承自Gtk.MessageDialog的自定义类,出于好奇我用-Wd参数运行测试脚本:
python3 -Wd dialogs_test.py
结果在__init__里使用parent=参数时,收到了两条警告:
.../dialogs_test.py:15: PyGTKDeprecationWarning: Using positional arguments with the GObject constructor has been deprecated. Please specify keyword(s) for "parent" or use a class specific constructor. See: https://wiki.gnome.org/PyGObject/InitializerDeprecations super().__init__(self, /usr/lib/python3/dist-packages/gi/overrides/Gtk.py:577: PyGTKDeprecationWarning: The keyword(s) "parent" have been deprecated in favor of "transient_for" respectively. See: https://wiki.gnome.org/PyGObject/InitializerDeprecations
于是我把__init__里的parent=改成了transient_for=,结果又碰到了类型错误:
See above ... TypeError: could not convert value for property `transient_for' from Dialog to GtkWindow
我明明在__init__里用了关键字参数,为啥第一条警告还会出现?而且我也搞不清该怎么正确使用transient_for,也找不到相关的文档说明。
下面是我简化后的测试脚本:
#!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class Dialog(Gtk.MessageDialog): def __init__(self, message_type, buttons, title, text): # Search for parent parent = next((w for w in Gtk.Window.list_toplevels() if w.get_title()), None) # Initialize the dialog object super().__init__(self, parent=parent, message_type=message_type, buttons=buttons, text=text) # Set title self.set_title(title) def show_dialog(self): """ Show the dialog """ response = self.run() in (Gtk.ResponseType.YES, Gtk.ResponseType.APPLY, Gtk.ResponseType.OK, Gtk.ResponseType.ACCEPT) self.destroy() return response def message_dialog(*args, **kwargs): """ Show message dialog """ #return kwargs return Dialog(Gtk.MessageType.INFO, Gtk.ButtonsType.OK, *args, **kwargs).show_dialog() class MessageDialogWindow(Gtk.Window): def __init__(self): super().__init__(title="MessageDialog Test") self.set_default_size(500, 100) box = Gtk.Box() self.add(box) button = Gtk.Button.new_with_label("Info dialog by class") button.connect("clicked", self.on_info_clicked) button.set_hexpand(True) box.add(button) def on_info_clicked(self, widget): result = message_dialog(title='button title', text='button text') print((f"button result: {result}")) win = MessageDialogWindow() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main()
解决方案
问题的根源在于调用父类构造函数时多传了self参数,同时需要把parent=替换成transient_for=,修改后的父类初始化代码如下:
super().__init__(transient_for=parent, message_type=message_type, buttons=buttons, text=text)
这样既解决了弃用警告,也不会再出现类型错误了。
备注:内容来源于stack exchange,提问作者user8780038
相关产品推荐
相关产品推荐

