Tkinter 主循环无法访问

Tkinter Mainloop Unreachable

我制作了 wordle,但我想让它看起来更像官方的 wordle,所以我的最终目标是在每一行制作 5 个 tkinter 条目,并将它们相互链接。当我 运行 这段代码时,底部的 mainloop 是灰色的,没有 window 出现。


root = Tk()
root.geometry('400x400')

def testlen():
    global textinentry1
    textinentry1= entry1.get()
    if len(textinentry1)  >1 :
        entry1.delete(0,END)
        entry1.insert(0,textinentry1[0])
        entry2.delete(0, END)
        entry2.insert(0,textinentry1[1] )

     

entry1 = Entry(root,width=5,  font = ('Georgia 18'), justify=CENTER)
entry1.grid(row=0, column=0)
entry2 = Entry(root, width=5,  font = ('Georgia 18'), justify=CENTER)
entry2.grid(row=0, column=1)
entry3 = Entry(root, width = 5,font = ('Georgia 18'), justify=CENTER)
entry3.grid(row=0, column=2)

while True:
    testlen()

        
root.mainloop()

我做错了什么?

mainloop 在 while 循环结束后执行 这是永远不会结束的,因为你在这里没有看到 window。

如果你想运行这段代码,那么你可以使用root.after()方法来创建一个循环。

from tkinter import *
root = Tk()
root.geometry('400x400')

def testlen():
    global textinentry1
    textinentry1= entry1.get()
    if len(textinentry1)  >1 :
        entry2.delete(0, END)
        entry2.insert(0,textinentry1[1] )

     

entry1 = Entry(root,width=22,  font = ('Georgia 18'), justify=CENTER)
entry1.grid(row=0, column=0)
entry2 = Entry(root, width=22,  font = ('Georgia 18'), justify=CENTER)
entry1button = Button(root, text="Enter", command = lambda :testlen())
entry1button.grid(row=1, column=0)
entry2.grid(row=2, column=0)
entry3 = Entry(root, width = 22,font = ('Georgia 18'), justify=CENTER)
entry3.grid(row=4, column=0)
def loop():
    testlen()
    root.after(1,loop) # 1 is 1 millisecond. Here root.after method call the loop function after 1 millisecond without crashing your code.
loop()

root.mainloop()