1

好的,我正在编写一个程序来为应该在循环中显示字母的文本设置动画:T

寿

汤姆

托马

托马斯

托马斯

托马斯·苏

托马斯成功...

依此类推,直到它重置然后再次循环。问题是,tkinter 主循环似乎只运行一次然后退出。这是代码:

from tkinter import *
import time

def setting():
    global thoms
    if thoms.get() == "":
        thoms.set("T")
        return
    if thoms.get() == "T":
        thoms.set("Th")
        return
    if thoms.get() == "Th":
        thoms.set("Tho")
        return
    if thoms.get() == "Tho":
        thoms.set("Thom")
        return
    if thoms.get() == "Thom":
        thoms.set("Thoma")
        return
    if thoms.get() == "Thoma":
        thoms.set("Thomas")
        return
    if thoms.get() == "Thomas":
        thoms.set("Thomas s")
        return
    if thoms.get() == "Thomas s":
        thoms.set("Thomas su")
        return
    if thoms.get() == "Thomas su":
        thoms.set("Thomas suc")
        return
    if thoms.get() == "Thomas suc":
        thoms.set("Thomas suck")
        return
    if thoms.get() == "Thomas suck":
        thoms.set("Thomas sucks")
        return
    if thoms.get() == "Thomas sucks":
        thoms.set("")
        return


window = Tk()
thoms = StringVar()
lbl = Label(window, textvariable=thoms)
lbl.grid(row=1, column=1)
setting()
time.sleep(1)
print("Run")
window.mainloop()

它第一次将变量设置为 T 然后停止,所以我输入 print 以查看它是否在循环,并且它只打印到控制台一次。我该如何解决?

4

1 回答 1

1

您的函数只执行一次 - 甚至在mainloop()开始运行之前。mainloop甚至不知道有功能setting()

使用window.after(100, setting)您可以要求 mainloop 在 100 毫秒(0.1 秒)后再次运行它

#from tkinter import * # not preferred
import tkinter as tk

def setting():
    if thoms.get() == "":
        thoms.set("T")
    elif thoms.get() == "T":
        thoms.set("Th")
    elif thoms.get() == "Th":
        thoms.set("Tho")
    elif thoms.get() == "Tho":
        thoms.set("Thom")
    elif thoms.get() == "Thom":
        thoms.set("Thoma")
    elif thoms.get() == "Thoma":
        thoms.set("Thomas")
    elif thoms.get() == "Thomas":
        thoms.set("Thomas s")
    elif thoms.get() == "Thomas s":
        thoms.set("Thomas su")
    elif thoms.get() == "Thomas su":
        thoms.set("Thomas suc")
    elif thoms.get() == "Thomas suc":
        thoms.set("Thomas suck")
    elif thoms.get() == "Thomas suck":
        thoms.set("Thomas sucks")
    elif thoms.get() == "Thomas sucks":
        thoms.set("")
    window.after(100, setting) # ask `mainloop` to run it again after 100ms (0.1s)

window = tk.Tk()

thoms = tk.StringVar()
lbl = tk.Label(window, textvariable=thoms)
lbl.grid(row=1, column=1)

setting() # run first time

window.mainloop()

顺便说一句:你可以写得更短

import tkinter as tk

text = "Thomas sucks"

def setting():

    l = len(thoms.get()) + 1

    if l <= len(text):
        thoms.set(text[:l])
    else:
        thoms.set("")

    window.after(100, setting) # run again after 100ms (0.1s)

window = tk.Tk()

thoms = tk.StringVar()
lbl = tk.Label(window, textvariable=thoms)
lbl.grid(row=1, column=1)

setting()

window.mainloop()
于 2019-12-13T16:14:03.047 回答