调用 destroy() 后 GTK window 不消失

GTK window does not disappear after calling destroy()

我正在尝试使用以下代码显示来自 Python 3 脚本的确认 window:

import time
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

dialog = Gtk.MessageDialog(modal=True, buttons=Gtk.ButtonsType.OK_CANCEL)
dialog.props.text = "Why won't this window dissappear?"
response = dialog.run()
dialog.destroy()
dialog.destroy()
dialog.destroy()

if response == Gtk.ResponseType.OK:
    print('OK')
else:
    print('Cancel')

time.sleep(100000)

我希望 window 在单击 "OK" 或 "Cancel" 后消失。但是,window 在程序结束之前一直可见。我该怎么做才能使 window 消失?

注意:我想在一个简单且线性的 shell 脚本中提示用户进行确认。我不打算实现完整的 GTK 应用程序,只是想寻求确认。

您没有给 Gtk 时间(或命令)来更新已销毁的 window。试试这个代码:

import time
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

dialog = Gtk.MessageDialog(modal=True, buttons=Gtk.ButtonsType.OK_CANCEL)
dialog.props.text = "Why won't this window dissappear?"
response = dialog.run()
dialog.destroy()
while Gtk.events_pending():
    Gtk.main_iteration()

if response == Gtk.ResponseType.OK:
    print('OK')
else:
    print('Cancel')

time.sleep(1000000)