0

你好 :) 在我在 python 3 中创建的打字练习程序中,我有一个 for...循环,它从某个段落字符的全局列表中获取字符并将其与用户正在键入的字符进行比较。出于某种原因,for 循环不会迭代并且不会继续到下一个字符。经过一番研究,我发现您必须使用局部变量才能做到这一点,但这也不起作用。这是我的代码:

import random
from tkinter import *
root=Tk()
a_var = StringVar()
words = []
eachword = []
global eachchar
charlist = []
x=random.randint(0,10)

def typingpractice():
    realcharlist = []
    something = []
    paralist = []
    #x=random.randint(0,10)
    file = open("groupproject.txt")
    line = file.readline()
    paraWords = []
    for line in file:
        newline = line.replace("\n","")
        paralist.append(line.replace("\n", ""))
        paraWords.append(newline.split(" "))
    wordList = []
    for c in paraWords[x]:
        charlist.append(c)
    for b in range(0,len(charlist)):
        wordList.append(charlist[b])
        #print (wordList)
        for p in charlist[b]:
            realcharlist.append(p)
    #print(realcharlist)
    a=Canvas(root, width=500, height=500)
    a.pack()
    a.create_text(250,50, text = "Typing Fun", width = 500, font = "Verdana", fill = "purple")
    a.create_text(250,300, text = paralist[x], width = 500, font = "Times", fill = "purple")  
    a = Entry(root, width = 100)
    a.pack()
    a.focus_set()
    a["textvariable"] = a_var


    def compare(s, realcharlist):         
        for g in realcharlist:
            print ("s:",s)
            print ("g:",g)            
            if s == g:
                print ("y")
                a['fg'] = 'green'
                break
            else:
                print ("n")
                a['fg'] = 'red'
                break

    def callback(*args):
        global s
       # print ("b:",xcount)
        s = a.get()
        s = s[-1:]
        compare(s, realcharlist)

    a_var.trace_variable("w", callback) #CALL WHEN VARIABLE IS WRITTEN


def practicetest():
    print ("nothing here yet")

b = Button(root, text="Start Practice", command=typingpractice)
b.pack()

d = Button(root, text="Test", command=practicetest)
d.pack()

root.mainloop()

文本文件“groupproject.txt”是一个包含 10 个单行段落的外部文本文件,每个段落的每个字符都与用户输入的内容进行比较。

任何有关如何使 for 循环工作的帮助将不胜感激。感谢:D

4

1 回答 1

0

基本上发生的事情是 for 循环中有一个中断,所以它总是会再次从 0 开始迭代自己。

于 2013-06-06T20:05:50.903 回答