(Python 3.7)如何使用tkinter打印消息和字符之间有延迟的字符?

2024-09-28 03:14:01 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我不熟悉python和编码

我想用tkinter做一些非常简单的事情,当你按下一个按钮时,它会显示一个文本,就像在旧游戏中一样,一个字母一个字母地显示,每个字符之间有一点延迟

我找不到一种方法来实现字符之间的延迟,我尝试了time.sleep循环,但是文本显示在循环的末尾

我看过之后的功能,但我不知道如何使用它,也不知道它是如何工作的

我应该在之后使用睡眠还是?我应该如何使用它们使其工作

顺便说一句,如果你有任何提示或建议的代码告诉我

    #MainFrame
root.title("Project")
root.geometry('400x400')
root.configure(bg="plum1")
    #Frame
BlackBorder=Frame(root,width=400,height=300,bg='Black')
BlackBorder.place(x=0,y=80)
TxtFrame=Frame(BlackBorder,width=370,height=270,bg='lavender')
TxtFrame.place(x=15,y=15)
    #Display
Cunter=Text(root,width=24,height=1,bg='lavender',font='Fixedsys')
Cunter.place(x=100,y=22)
Cunter.insert(END, str(len(LoList))+" Résultats Différents")


#defTxt
def LoMsg(self):
    self=Text(TxtFrame,wrap='word',borderwidth=0,width=35,height=10,bg='lavender',font='Fixedsys')
    self.place(x=50,y=100)
    LoTxt=str(LovList[randrange(len(LovList))])
    LoNum=0
    while LoNum!=len(LoTxt):
        self.insert(END,LoTxt[LoNum])
        sleep(0.1)
        LoNum+=1

    #Button
buttonMain=Button(root,width=9,height=3,bg='thistle2',text="Try me",font='Fixedsys')
buttonMain.place(x=5,y=5)
#ButtonEvent
buttonMain.bind('<1>', LoMsg)

Tags: selflenplacerootwidthframebgfont
2条回答

欢迎使用Python和编码!在回答你的问题之前,我想先解决几件事:

  1. 如果你能在提问时提供一个minimal, reproducible example是很有帮助的。我真的看不出你的代码中有什么问题,因为发生了太多事情,我无法在我的计算机上运行它,因为缺少了一些部件。例如,LoList是未定义的,并且没有import语句。

  2. PEP8有一大堆关于如何设计代码风格的建议——太多了,一下子读不完。但我想提请大家注意Function and Variable names,它表明变量和函数都使用小写,单词之间用下划线分隔。通常Class Names以大写字母开头。在我看来,很多变量和函数都像类

为了回答你的问题,我认为使用time.sleep()会有效。下面是一个在控制台中运行的简单示例,它可能会帮助您了解如何使用它:

import time
text = "I've been awaiting your arrival..."
for char in text:
    # end='' will prevent each letter from getting its own line on the console
    # flush=True will make sure that the character is printed right away in the console
    print(char, end='', flush=True) 
    time.sleep(0.1)

下面是一个示例,用于强调使用after(ms, callback)方法来获得所需结果(相应地调整after方法中的ms):

import tkinter as Tk

def insert():
    global LoNum
    text.insert(Tk.END, word[LoNum])
    LoNum += 1
    if LoNum != len(word):
        root.after(300, insert)
    else:
        return

root = Tk.Tk()
root.geometry('600x200')

LoNum = 0
word = [x for x in 'abcdefg'] # get the word to a list format
text = Tk.Text(root, wrap='word', borderwidth=0, width=35, height=10, bg='lavender')
text.pack()

Tk.Button(root, text='Try Me', width=9, height=3, bg='thistle2', command=insert).pack()

root.mainloop()

相关问题 更多 >

    热门问题