Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tkinter typing game not upping score

Here’s my code:

from tkinter import *
import random
from pathlib import Path
from typing import Text

score = 0

def handle(*args):
    global totype
    global typevar
    global score
    print(f'{typevar.get()}, {totype}')
    if typevar.get().strip() == totype:
        score += 1
        print(score)
        
p = Path(__file__).with_name('words.txt')
with p.open('r') as f:
    words = f.readlines()

tab = Tk()
tab.geometry('300x200')

typevar = StringVar()

rand = random.randint(1, len(words))

totype = words[rand]


tab.bind('<Return>', handle)

type = Label(tab, text=totype).pack()
typed = Entry(tab, show = '^', textvariable = typevar).pack()

tab.mainloop()

It works great (apart from it not giving me new words) but it doesn’t recognize when you type in the right word. When you type something in, it’s supposed to up your score and print your current score when you get it right. However, even when you type it correctly it doesn’t print anything out. The two variables are the same, though.

How can I fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are stripping the wrong text, you need to strip on the read text from the file, not on the input from the entry that will never have a \n:

def handle(*args):
    global score # Removed unwanted globals
    
    print(f'{typevar.get()}, {totype}')
    if typevar.get() == totype.strip():
        score += 1
        print(score)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading