按钮点击后如何延迟关闭tkinter窗口?

时间:2018-06-03 19:49:38

标签: tkinter delay destroy

我有一个简单的tkinter gui,显示一个单选按钮和ok取消按钮。单击确定按钮后,我想继续运行我的程序,然后在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())

但如何解决?

由于

1 个答案:

答案 0 :(得分:0)

使用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()