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

Time:03-06

I'm working on day 89 of 100 Days of Code: Python. I need to build a Tkinter app that constantly monitors a text entry and will delete the code if it detects that nothing's been typed for 10 seconds. I've tried to do so using this code:

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

I have also tried:

    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

The problem is that new_num_char equals "after#0", "after#1", "after#2", etc. instead of equaling the new character count. How can I grab the new word count every five seconds? If I do:

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

This just freezes the whole window and I can't type into the entry box until the five seconds are up. I'd really appreciate some help on this; I've been trying to figure it out for a few days now. Full code below:

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()

CodePudding user response:

First I would split in two functions

First which set self.start_num_char and run self.get_wordcount() after some time

Second (self.get_wordcount) which get new_num_char, compare with self.start_num_char - but it doesn't use return - it directly resets timer - self.time_left = 10 - when text in entry is longer (or shorter). And finally it keep new_num_char in self.start_num_char and runs again after short time

    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)

And at the same time counter display new time and clean entry when self.time_left is 0

    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

This count 10 seconds only when you don't type.

But it has small problem - because counter and get_wordcount run separatelly so sometimes counter changes time to 9 when get_wordcount is reseting variable and it can display 9 but it shouldn't. Maybe it should use real time and it should keep time when last key was pressed and use this value to calculate counter.


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()

EDIT:

You may try to use self.entry_box.bind('<<Modified>>', function) to execute function(event) when text was changed. But on my Linux it runs only on first change.


EDIT:

I added time.time() to check time betwin changes and now it better display counter.

    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)

CodePudding user response:

I would solve this another way. Create a function cancels any previous attempt to clear the function and then schedules this function to be called in 10 seconds. Then, create a binding that calls this button on every key release. The entire mechanism takes only a half dozen lines of code.

Here's an example:

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()

  • Related