练习时长两年半的Programmer 2022-03-20 12:29 采纳率: 81.5%
浏览 27
已结题

关于#python的问题

我现在有一个tkiner弹框,我想每隔1秒显示一个text,
现代码:

import tkinter
from time import sleep

win = tkinter.Tk()
text = tkinter.Text(win)  
text.insert(tkinter.INSERT, "")
text.insert(tkinter.INSERT, "\r\n") 
text.insert(tkinter.INSERT, "")
text.insert(tkinter.INSERT, "\r\n")
text.insert(tkinter.INSERT, "")
text.insert(tkinter.INSERT, "\r\n")
text.insert(tkinter.INSERT, "")
text.insert(tkinter.INSERT, "\r\n")
text.insert(tkinter.INSERT, "")

text.pack()
win.mainloop()


希望可以解决 如果有帮助会采纳

  • 写回答

1条回答 默认 最新

  • 小康2022 Python领域新星创作者 2022-03-20 12:51
    关注

    【有帮助请采纳】
    这个千万不能用sleep函数哦
    在用Tkinter模块编写GUI的时候,它的窗口显示时通过消息事件循环来完成的(这就是为什么每个Tkinter界面程序都有一个mainloop要执行)
    如果你用sleep函数,那么整个事件循环进程(包括窗口显示)都会被暂停一段时间(由sleep决定),这是错误的
    我们应该用Tkinter里的after方法完成(这个方法是Tkinter特定的),参数分别为,暂停时间(单位ms),执行的函数,函数的参数(这个是*args)

    import tkinter
     
    win = tkinter.Tk()
    text = tkinter.Text(win)
    
    text.pack()#先让这个text控件显示出来
    
    def timer(counter=1):#定义一个计时器
        text.insert(tkinter.INSERT, str(counter))
        text.insert(tkinter.INSERT, "\r\n")
        win.after(1000,timer,counter+1)#1000ms后再次执行该函数,且参数为
    
    timer()#执行计时器函数
    
    win.mainloop()
    

    【有帮助请采纳】

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月28日
  • 已采纳回答 3月20日
  • 创建了问题 3月20日