【问题标题】:why do I get a blank tkinter window?为什么我会得到一个空白的 tkinter 窗口?
【发布时间】:2011-09-19 20:53:03
【问题描述】:

所以当我运行此代码并单击按钮时:

from Tkinter import *
import thread
class App:
    def __init__(self, master):
        print master

        def creatnew():

            admin=Tk()
            lab=Label(admin,text='Workes')
            lab.pack()
            admin.minsize(width=250, height=250)
            admin.maxsize(width=250, height=250)
            admin.configure(bg='light green')
            admin.mainloop()
        def other():
            la=Label(master,text='other')
            la.pack()
            bu=Button(master,text='clicks',command=lambda: thread.start_new_thread(creatnew,()))
            bu.pack()
        other()

Admin = Tk()

Admin.minsize(width=650, height=500)
Admin.maxsize(width=650, height=500)
app = App(Admin)
Admin.mainloop()

我得到了第二个 tkinter 窗口,但它是一个白色的空白屏幕,使两个程序都没有响应。 任何想法

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    不要使用线程。这使 Tkinter 主循环感到困惑。为第二个窗口创建一个Toplevel 窗口。

    您的代码修改最少:

    from Tkinter import *
    # import thread # not needed
    
    class App:
        def __init__(self, master):
            print master
    
            def creatnew(): # recommend making this an instance method
    
                admin=Toplevel() # changed Tk to Toplevel
                lab=Label(admin,text='Workes')
                lab.pack()
                admin.minsize(width=250, height=250)
                admin.maxsize(width=250, height=250)
                admin.configure(bg='light green')
                # admin.mainloop() # only call mainloop once for the entire app!
            def other(): # you don't need define this as a function
                la=Label(master,text='other')
                la.pack()
                bu=Button(master,text='clicks',command=creatnew) # removed lambda+thread
                bu.pack()
            other() # won't need this if code is not placed in function
    
    Admin = Tk()
    
    Admin.minsize(width=650, height=500)
    Admin.maxsize(width=650, height=500)
    app = App(Admin)
    Admin.mainloop()
    

    【讨论】:

    • 您应该只调用一次mainloop。您不会将其称为 forveeach 顶层,仅适用于整个应用程序。
    • @Bryan Oakley:正确!我最初注意到这一点,但忘记修复它。我试图尽可能多地保留他的代码。现已修复。