Is there a function to terminate after loops in tkinter?

Viewed 22

I'm creating a programme using tkinter and python that tests your words per minute.

I've created a loop that starts when you hit the start game button to keep checking the words typed and to highlight words green if inputted correctly.

After a minute I want the loop to end and for labels to show the total words per minute and errors made. When the labels are shown they're stuck in a loop and keep creating labels over and over again.

I've tried a 'running' boolean to end it, I've tried adding a condition to stop the loop if a variable I've added exceeds 60. I've tried separating it and playing with indentation but nothing seems to be working.

Is there a function or something else that can be used to end the loop? I'm struggling to find a solution.

note: I've set the game to end after 10 seconds, not 60, so that it's easier to test out.


from text import text_list
from tkinter import *

window = Tk()

sample_text = (" ".join(text_list))

text_window = Text(window, height=10, width=99, wrap=WORD)
text_window.insert(INSERT, sample_text)
text_window.configure(state=DISABLED)
text_window.pack()

type_input = Entry(window, width=99)
type_input.pack()


def end_game():
    global running
    running = False
    type_input.configure(state=DISABLED)
    user_type = type_input.get()
    users_input = user_type.split(' ')
    WPM = 0
    errors = 0
    for words in users_input:
        if words in text_list:
            WPM += 1
        else:
            errors += 1
    show_results(WPM, errors)


def show_results(result, mistakes):
    final_wpm = Label(window, text=f"Time's up! Your typing speed is {result} words per minute.")
    final_wpm.pack()
    final_errors = Label(window, text=f'Total errors made: {mistakes}')
    final_errors.pack()


time_spent = 0


def start_game():
    global running
    global time_spent
    running = True
    time_spent += 0.5
    if running:
        user_type = type_input.get()
        users_input = user_type.split(' ')
        for words in users_input:
            if words in text_list:
                countVar = StringVar()
                pos = text_window.search(words, "1.0", stopindex="end", count=countVar)
                end_point = pos + f"+{countVar.get()}c"
                text_window.tag_configure("search", background="green")
                text_window.tag_add("search", pos, end_point)
            else:
                continue
    if time_spent < 10:
        window.after(500, start_game)
    window.after(1000 * 10, end_game)


running = False
start_button = Button(window, text='Start Game', command=start_game)
start_button.pack()

window.mainloop()

0 Answers
Related