Skip to main content
 首页 » 编程设计

python之在 Python 中,允许在显示 Tkinter 对话框后执行后续代码

2025年05月04日7lyhabc

我在 Python 中使用 Tkinter 来显示对话框。对话框显示后,无论用户是否关闭对话框,都应执行后续代码。

我试过用线程在新线程中创建对话框,但似乎不起作用。我想我需要将后续代码封装在我不希望的单独线程中。

def alert(title, message): 
    box = Tk() 
    box.title(title) 
    Message(box, text=message, bg='red', 
      fg='ivory').pack(padx=1, pady=1) #, relief=GROOVE 
    Button(box, text="Close", command=box.destroy).pack(side=BOTTOM) 
    box.geometry('300x150') 
    thread.start_new_thread(box.mainloop()) 
    hello() 
 
def hello(): 
    print 'hello!' 

上面代码的问题是“你好!”只有在用户关闭警告框后才会打印。我如何修改我的代码,使 hello()(或与此相关的任何后续代码)无论对话框的状态如何都被执行?

请您参考如下方法:

试试这个:

def alert(title, message): 
    box = Tk() 
    box.title(title) 
    Message(box, text=message, bg='red', 
      fg='ivory').pack(padx=1, pady=1) #, relief=GROOVE 
    Button(box, text="Close", command=box.destroy).pack(side=BOTTOM) 
    box.geometry('300x150') 
    box.after(10, hello) 
    box.mainloop()