Mainloop, кажется, выполняется только один раз в tkinter
Итак, я пишу программу для анимации текста, который должен отображать буквы в цикле: 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, а затем останавливается, поэтому я вставляю печать, чтобы проверить, зацикливается ли она, и она выводит на консоль только один раз. Как это исправить?
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()