首页 > 解决方案 > Tkinter 多个窗口未在按钮单击时打开

问题描述

单击按钮 clk 时,窗口的第一个实例打开,但在销毁第一个窗口后,后续窗口不会打开。只有在主实例 win 关闭后,后续窗口才会打开。

from tkinter import *

def func():
    root = Tk()
    b1 = Button(root,text='Click Me!').pack()
    root.after(2000, lambda: root.destroy())
    root.mainloop()

    root=Tk()
    b1 = Button(root,text='Click Me!',bg='orange').pack()
    root.mainloop()

win = Tk()
clk = Button(win,text='func',command=func).pack()
win.mainloop()

没有语法错误,但我没有得到我想要的输出。

谢谢你

标签: pythonpython-3.xtkinter

解决方案


就我的理解而言,只能有一个 mainloop()。我重写了您的代码以使其正常工作。

from tkinter import *

def func():
    root = Toplevel()
    b1 = Button(root,text='Click Me!').pack()
    root.after(2000, lambda: second(root))

def second(root):
    root.destroy()
    root=Toplevel()
    b1 = Button(root,text='Click Me!',bg='orange').pack()

win = Tk()
clk = Button(win,text='func',command=func).pack()
win.mainloop()

推荐阅读