gpt4 book ai didi

python - Mainloop 似乎只在 tkinter 中运行一次

转载 作者:行者123 更新时间:2023-12-01 06:44:06 27 4
gpt4 key购买 nike

好吧,我正在编写一个程序,以对应该在循环中显示字母的文本进行动画处理:

Th

不过

汤姆

托马

托马斯

托马斯

托马斯苏

托马斯成功...

依此类推,直到重置,然后再次循环。问题是, 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 来查看它是否循环,并且它只打印到控制台一次。我该如何解决这个问题?

最佳答案

您的函数仅执行一次 - 即使在 mainloop() 开始运行之前也是如此。 mainloop甚至不知道有函数setting()

使用window.after(100, setting)你可以要求mainloop在100ms(0.1s)后再次运行它

#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()

关于python - Mainloop 似乎只在 tkinter 中运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59325964/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com