首页 > 解决方案 > 调用 destroy() 后 GTK 窗口不消失

问题描述

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

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)

我希望单击“确定”或“取消”后窗口会消失。但是,在程序结束之前,该窗口仍然可见。我该怎么做才能使窗口消失?

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

标签: pythongtk

解决方案


你没有给 Gtk 时间(或命令)来更新被破坏的窗口。试试这个代码:

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)

推荐阅读