将函数的 return 分配给具有 window.after 的变量

Assign the return of a function to a variable with window.after

我在编程 100 天的第 89 天工作:Python。我需要构建一个 Tkinter 应用程序,它会持续监控文本输入,如果它检测到 10 秒内没有输入任何内容,就会删除代码。我尝试使用此代码这样做:

def get_wordcount(self):
    start_num_char = len(self.entry_box.get(1.0, "end-1c"))
    new_num_char = self.after(5000, self.get_wordcount)
    if new_num_char <= start_num_char:
        return True
    else:
        return False

我也试过:

    def get_wordcount(self):
    start_num_char = len(self.entry_box.get(1.0, "end-1c"))
    new_num_char = self.after(5000, len(self.entry_box.get(1.0, "end-1c")))
    if new_num_char <= start_num_char:
        return True
    else:
        return False

问题是 new_num_char 等于“after#0”、“after#1”、“after#2”等,而不是等于新字符数。如何每五秒抓取一次新字数?如果我这样做:

def get_wordcount(self):
start_num_char = len(self.entry_box.get(1.0, "end-1c"))
self.after(5000)
new_num_char = len(self.entry_box.get(1.0, "end-1c")
if new_num_char <= start_num_char:
    return True
else:
    return False

这只会冻结整个 window 并且在五秒结束之前我无法在输入框中输入内容。我真的很感激这方面的帮助;几天来我一直在努力弄清楚。完整代码如下:

from tkinter import *
from tkinter.scrolledtext import ScrolledText

class App(Tk):
    def __init__(self):
        super().__init__()
        self.title("Focus Writer")
        self.background_color = "#EAF6F6"
        self.config(padx=20, pady=20, bg=self.background_color)
        self.font = "Arial"
        self.start = False
        self.time_left = 10
        self.title_label = Label(text="Focus Writer",
                                 bg=self.background_color,
                                 font=(self.font, 26))
        self.title_label.grid(row=0, column=0, columnspan=2)
        self.explain = Label(text="Welcome to the Focus Writer app. You need to continuously input content in order to "
                                  "keep the app from erasing your data. If the app detects that you haven't written "
                                  "anything for more than 10 seconds, it will wipe everything, and you will need to "
                                  "start over. \n\nPress the start button when you are ready to begin.\n",
                             bg=self.background_color,
                             font=(self.font, 18),
                             wraplength=850,
                             justify="left",)
        self.explain.grid(row=1, column=0, columnspan=2)
        self.start_img = PhotoImage(file="play-buttton.png")
        self.start_button = Button(image=self.start_img,
                                   height=50,
                                   command=self.check_writing)
        self.start_button.grid(row=2, column=0)
        self.time_left_label = Label(text=self.time_left,
                                     bg=self.background_color,
                                     font=(self.font, 36))
        self.time_left_label.grid(row=2, column=1)
        self.entry_box = ScrolledText(width=80,
                                      height=20,
                                      wrap=WORD,
                                      font=(self.font, 14))
        self.entry_box.grid(row=3, column=0, columnspan=2)

    def countdown(self):
        if self.time_left > 0:
            self.time_left -= 1
            self.time_left_label.configure(text=self.time_left)
            self.after(1000, self.countdown)
        else:
            if self.get_wordcount():
                self.entry_box.delete(1.0, "end-1c")
            else:
                self.time_left = 0
                return False

    def get_wordcount(self):
        start_num_char = len(self.entry_box.get(1.0, "end-1c"))
        new_num_char = self.after(5000, len(self.entry_box.get(1.0, "end-1c")))
        if new_num_char <= start_num_char:
             return True
        else:
             return False

    def check_writing(self):
        self.start = True
        self.start_button["state"] = DISABLED
        self.entry_box.focus()
        self.get_wordcount()


app = App()
app.mainloop()

首先我会分成两个函数

首先设置 self.start_num_char 和 运行 self.get_wordcount() 一段时间后

第二个(self.get_wordcount)得到new_num_char,与self.start_num_char比较 - 但它不使用return - 它直接重置计时器 - self.time_left = 10 - 当条目中的文本更长(或更短)时。最后它在 self.start_num_char 中保持 new_num_char 并在短时间

后再次保持 运行s
    def start_wordcount(self):
        self.start_num_char = len(self.entry_box.get(1.0, "end-1c"))
        self.after(50, self.get_wordcount)
        
    def get_wordcount(self):
        new_num_char = len(self.entry_box.get(1.0, "end-1c"))
        
        if new_num_char != self.start_num_char:  # longer or shorter
            self.time_left = 10 
            self.time_left_label.configure(text=self.time_left)
            self.start_num_char = new_num_char
            
        self.after(50, self.get_wordcount)

同时计数器显示新时间并在 self.time_left0

时清除 entry
    def countdown(self):
        if self.time_left > 0:
            self.time_left -= 1
            self.time_left_label.configure(text=self.time_left)
            self.after(1000, self.countdown)
        else:
            self.entry_box.delete(1.0, "end-1c")
            self.start_num_char = 0

只有当您不打字时才计算 10 秒。

但它有一个小问题 - 因为 counterget_wordcount 运行 分开所以有时 counter 将时间更改为 9get_wordcount正在重置变量,它可以显示 9 但它不应该。也许它应该使用实时并且它应该在按下最后一个键时保持时间并使用这个值来计算计数器。


from tkinter import *
from tkinter.scrolledtext import ScrolledText

class App(Tk):
    def __init__(self):
        super().__init__()
        self.title("Focus Writer")
        self.background_color = "#EAF6F6"
        self.config(padx=20, pady=20, bg=self.background_color)
        self.font = "Arial"
        self.start = False
        self.time_left = 10
        
        self.title_label = Label(text="Focus Writer",
                                 bg=self.background_color,
                                 font=(self.font, 26))
        self.title_label.grid(row=0, column=0, columnspan=2)
        
        self.explain = Label(text="Welcome to the Focus Writer app. You need to continuously input content in order to "
                                  "keep the app from erasing your data. If the app detects that you haven't written "
                                  "anything for more than 10 seconds, it will wipe everything, and you will need to "
                                  "start over. \n\nPress the start button when you are ready to begin.\n",
                             bg=self.background_color,
                             font=(self.font, 18),
                             wraplength=850,
                             justify="left",)
        self.explain.grid(row=1, column=0, columnspan=2)
        
        self.start_button = Button(text='Start',
                                   command=self.check_writing)
        self.start_button.grid(row=2, column=0)
        
        self.time_left_label = Label(text=self.time_left,
                                     bg=self.background_color,
                                     font=(self.font, 36))
        self.time_left_label.grid(row=2, column=1)
        
        self.entry_box = ScrolledText(width=80,
                                      height=20,
                                      wrap=WORD,
                                      font=(self.font, 14))
        self.entry_box.grid(row=3, column=0, columnspan=2)
    
    def countdown(self):
        if self.time_left > 0:
            self.time_left -= 1
            self.time_left_label.configure(text=self.time_left)
            self.after(1000, self.countdown)
        else:
            self.entry_box.delete(1.0, "end-1c")
            self.start_num_char = 0

    def start_wordcount(self):
        self.start_num_char = len(self.entry_box.get(1.0, "end-1c"))
        self.after(50, self.get_wordcount)
        
    def get_wordcount(self):
        new_num_char = len(self.entry_box.get(1.0, "end-1c"))
        
        if new_num_char != self.start_num_char:  # longer or shorter
            self.time_left = 10 
            self.time_left_label.configure(text=self.time_left)
            self.start_num_char = new_num_char
            
        self.after(50, self.get_wordcount)

    def check_writing(self):
        self.start = True
        self.start_button["state"] = DISABLED
        self.entry_box.focus()
        
        self.start_wordcount()
        self.countdown()


app = App()
app.mainloop()

编辑:

您可以尝试使用 self.entry_box.bind('<<Modified>>', function) 在文本更改时执行 function(event)。但在我的 Linux 上,它 运行 仅在第一次更改时出现。


编辑:

我添加了 time.time() 以检查更改之间的时间,现在它可以更好地显示计数器。

    def countdown(self):
        if self.time_left > 0:
            current_time = time.time()
            if current_time >= self.change_time + 1:
                self.time_left -= 1
                self.time_left_label.configure(text=self.time_left)
            self.after(1000, self.countdown)
        else:
            self.entry_box.delete(1.0, "end-1c")
            self.start_num_char = 0

    def start_wordcount(self):
        self.num_char = len(self.entry_box.get(1.0, "end-1c"))
        self.change_time = time.time()
        self.after(50, self.get_wordcount)
        
    def get_wordcount(self):
        new_num_char = len(self.entry_box.get(1.0, "end-1c"))
        
        if new_num_char != self.num_char:  # longer or shorter
            self.time_left = 10 
            self.change_time = time.time()
            self.time_left_label.configure(text=self.time_left)
            self.num_char = new_num_char
            
        self.after(50, self.get_wordcount)

我会用另一种方式解决这个问题。创建一个函数会取消之前任何清除该函数的尝试,然后安排此函数在 10 秒内调用。然后,创建一个在每次按键释放时调用此按钮的绑定。整个机制只需要六行代码。

这是一个例子:

import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.after_id = None

        text = tk.Text(self)
        text.pack(fill="both", expand=True)

        text.bind("<Any-KeyRelease>", self.schedule_clear_text)

    def schedule_clear_text(self, event):
        if self.after_id is not None:
            self.after_cancel(self.after_id)
        self.after_id = self.after(10000, event.widget.delete, "1.0", "end")

root = App()
root.mainloop()