【问题标题】:How to delay closing tkinter window after button click?单击按钮后如何延迟关闭 tkinter 窗口?
【发布时间】:2018-06-03 19:49:37
【问题描述】:

我有一个简单的 tkinter gui,它显示一个单选按钮和确定取消按钮。单击确定按钮后,我想继续运行我的程序,然后 5 秒后关闭窗口。

import tkinter as tk
from tkinter.ttk import *

gui = tk.Tk()

gui.geometry('330x150')
# set up radio buttons
selected = tk.IntVar()  # selected holds radio button currently selected


def ok_clicked():

    gui.after(5000, lambda : gui.destroy())

    #run stuff while waiting for the gui to close
        if selected.get() == 0:
             # run HS
             import Open_HS
         else:
             # run KA
             import Open_KA

def cancel_clicked():
    gui.destroy()

hs_btn = Radiobutton(gui, width=15, text="Radio 1", value=0,variable=selected).place(x=50, y=40)
ok_btn = Button(gui, width=9, text="OK", command=ok_clicked).place(x=180, y=115)
cancel_btn = Button(gui, width=9, text="Cancel", command=cancel_clicked).place(x=250, y=115)

gui.mainloop()

这显然行不通,因为我在打电话

gui.mainloop.

在我设置延迟之前

gui.after(5000, lambda : gui.destroy())

但是如何解决呢?

谢谢

【问题讨论】:

  • 你为什么说“这显然行不通”?这个对我有用。当我点击按钮时,窗口在 5 秒后被销毁。
  • 嗯,我现在也试试。但它不在我的实际代码中,它包含一个导入指令,用于在 .after 命令的正下方导入一个单独的文件。我已经编辑了代码以显示我的意思。抱歉,我认为这不是问题,所以之前忽略了它。
  • 您的代码不会像发布的那样运行,因为您正在导入自定义模块。您需要包含导致问题的Open_HS 的最小可能实现。
  • 好的,谢谢。我现在知道了。我认为问题出在我发布的代码 sn-p 中,但我现在看到它在我的 Open_HS 模块中。我要花点时间来解决它。再次感谢。
  • 感谢您的洞察力。我查看了随后的代码,并将 gui.destroy() 行放在锁定执行的部分(selenium webdriver)之后,现在它工作正常。

标签: tkinter delay destroy


【解决方案1】:

使用gui.after可以实现你所需要的:

import tkinter as tk


def ok_clicked():
    gui.after(5000, gui.destroy)


def cancel_clicked():
    gui.destroy()


if __name__ == '__main__':

    gui = tk.Tk()

    gui.geometry('330x150')
    selected = tk.IntVar()

    tk.Radiobutton(gui, width=15, text="Radio 1", value=0, variable=selected).place(x=50, y=40)
    tk.Button(gui, width=9, text="OK", command=ok_clicked).place(x=180, y=115)
    tk.Button(gui, width=9, text="Cancel", command=cancel_clicked).place(x=250, y=115)

    gui.mainloop()

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    相关资源
    最近更新 更多