【问题标题】:Delaying parts of text being inserted into Scroll Text Box (scrolledtext)延迟部分文本插入到滚动文本框 (scrolledtext)
【发布时间】: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 我已经按照您的建议查看了该方法,但我不知道如何将其实现到我的代码中。

标签: python tkinter text


【解决方案1】:

这是使用.after() 方法的解决方案:

def insertText():
    global previousDelay
    previousDelay = 0
    delayedInsert('This line should be inserted first.\n',0)
    delayedInsert('This line should be inserted after a 1 second delay.\n',1)
    delayedInsert('This line should be inserted after a 3 second delay.\n',3)
    delayedInsert('This line should be inserted after a 3 second delay.\n',3)

def delayedInsert(text, delay):
    global previousDelay
    trialGUI.after((delay + previousDelay) * 1000, lambda: trialBox.insert(tk.INSERT,text))
    previousDelay += delay

它使用delayedInsert 函数以秒为单位获取文本和延迟,以及全局变量previousDelay 使延迟看起来是异步的(它们仍然同时发生,但延迟被更改以使其看起来像他们不是)。如果延迟没有改变,每个延迟将同时开始,而不是一个接一个。 delayedInsert 函数在插入文本之前等待指定的延迟加上之前的延迟。这与time.sleep() 的效果相同,但它适用于 Tkinter。

【讨论】:

    猜你喜欢
    • 2016-04-19
    • 2013-10-27
    • 2021-08-03
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多