首页 > 解决方案 > 睡眠 while 循环而不中断它,用于在 tkinter 中写入新条目

问题描述

在这个 UI 中有 2 个按钮和 1 个输入框。名为“开始循环”和“打印”的按钮。

当我在输入框中写入文本时,按下相关按钮时我应该能够看到它被打印出来。我想要做的是,把那个按钮按下一个while循环。但有趣的部分是尝试每 10 秒打印一个新条目。

当您输入一个条目并按下“开始循环”按钮时,它就会运行。同时用户界面窗口将冻结。无法编写新条目或按“打印”按钮。即使我使用 time.sleep 功能它仍然冻结。它打印旧条目,但我想在每次迭代时写一个新条目。查看代码:

import time
from tkinter import *

class tkin(Frame):
    def __init__(self,parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.UI()

    def UI(self):
        self.down = StringVar()
        self.down_entry = Entry(self, textvariable=self.down)
        self.down_entry.grid(row=2, column=0)


        self.start_loop_buuton = Button(text="Start Loop", command=self.loop_func)
        self.start_loop_buuton.place(x=10,y=40)
        self.print_func_button = Button(text="Print ", command=self.pprint)
        self.print_func_button.place(x=120,y=40)
        self.pack()

    def loop_func(self):
        start = time.time()
        while True:
            print("standart print out")
            end = time.time()
            if (end- start) >10:
                time.sleep(10)
                self.print_func_button.invoke()           ## press print_func_button
                start = time.time()
                

    def pprint(self):
        print("WHICH PRINT LINE I WANT TO PRINT IN LIKE EVERY 10 SECONDS")
        print(self.down.get())

def main():
    root = Tk()
    tkin(root)
    root.geometry("195x100+300+300")
    root.mainloop()

main()

任何建议都会很好。提前致谢。

标签: pythontkinterwhile-loop

解决方案


这就是我重新定义您的方法的方式:

def loop_func(self):
        self.print_func_button.invoke()  # press print_func_button
        self.after(3000, self.loop_func)

时间以毫秒为单位,所以这将是 3 秒


推荐阅读