【发布时间】:2021-01-28 10:44:07
【问题描述】:
我有一个按钮,当它被点击时,它会在“滚动文本”框中插入文本。
我想延迟插入文本框中的部分文本。如,插入一行文本,有 3 秒延迟,插入下一行文本,依此类推...
我尝试使用“时间”来完成这项工作。但是,这只会延迟组合值插入的所有文本,然后立即插入所有文本。有没有办法让它按我的意愿工作?是否可以延迟它,以便每次插入一个字母?
这是我尝试过的一个非常简化的版本:
import tkinter as tk
from tkinter import *
from tkinter import scrolledtext
import time
# This is the GUI
trialGUI = Tk()
trialGUI.geometry('710x320')
trialGUI.title("Test GUI")
#This is the text that should be inserted when the button is pressed
def insertText():
trialBox.insert(tk.INSERT, 'This line should be inserted first.\n')
time.sleep(1)
trialBox.insert(tk.INSERT, 'This line should be inserted after a 1 second delay.\n')
time.sleep(3)
trialBox.insert(tk.INSERT, 'This line should be inserted after a 3 second delay.\n')
time.sleep(3)
trialBox.insert(tk.INSERT, 'This line should be inserted after a 3 second delay.\n')
#This is the scrolling text box
trialBox = scrolledtext.ScrolledText(trialGUI, wrap = tk.WORD, width = 42, height = 10, font=(14))
trialBox.grid(row = 0, column = 0, columnspan = 4, pady = 3)
#This button runs the code to insert the text
trialButton = Button(trialGUI, text = "Run Code", command = insertText)
trialButton.grid(row = 1)
trialGUI.mainloop()
【问题讨论】:
-
对
after方法进行一些研究,它可以让您安排代码在未来运行。 -
@BryanOakley 我已经按照您的建议查看了该方法,但我不知道如何将其实现到我的代码中。