Home > Software design >  Tkinter typing game not upping score
Tkinter typing game not upping score

Time:01-03

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?

CodePudding user response:

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)
  • Related