我只是tkinter的新手,我不知道该怎么做,我有一段代码在tkinter中逐行读取。有一个输入字段来键入文件中的行,并且当用户按下按钮时,如果
,则应给出“正确”他在文件中键入==行。如果没有,那么它将显示“不正确”。
我只是不知道如何从文件中声明行,实际上我知道如何使用用于文件中的行:
但是我的老师告诉我不要在tkinter中使用循环。
我的代码:
import tkinter as tk
root = tk.Tk()
def callback(sv):
print(sv.get())
for line in f:
if text == line:
print("correct")
else:
print("incorrect")
return sv.get()
f = open('sentences.txt', 'r')
sv = tk.StringVar(root)
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv))
label = tk.Label(root,text="")
label.pack()
e = tk.Entry(root, textvariable=sv)
tk.Button(root, text="Click for next",
command=lambda: label.config(text=next(f))).pack()
e.pack()
text = e.get()
root.mainloop()
这里是根据我对您要求的理解而制定的工作程序。留下评论以便于理解。
from tkinter import *
#before you proceed to create tkinter window, read the file in a list
fileLineList = [line. rstrip('\n') for line in open("sample.txt")]
#check if the content exactly matches any element in the list
def evaluate(text, board):
if text in fileLineList:
board.set("Correct")
else:
board.set("Incorrect")
def clear(content, result):
content.set("")
result.set("")
#build tkinter window
root = Tk()
root.geometry("400x200")
content = StringVar()
result=StringVar()
#the entry widget to take user input
entry = Entry(root, textvariable=content)
entry.pack(fill=X, padx=10, pady=10)
entry.focus_set()
evalBtn = Button(root, text="Evaluate",
command=lambda: evaluate(text=content.get(), board=result))
evalBtn.pack(fill=X, padx=20, pady=10)
#label to show the result
lbl = Label(root, bg="white", textvariable=result)
lbl.pack(fill=X, padx=10, pady=10)
clearBtn = Button(root, text="Clear",
command=lambda: clear(content, result))
clearBtn.pack(fill=X, padx=20, pady=10)
root.mainloop()
您需要在单独的变量中跟踪当前行。试试这个:
import tkinter as tk
root = tk.Tk()
f = open('sentences.txt', 'r')
current_line = ''
def callback(*args):
if sv.get() == current_line:
print("correct")
else:
print("incorrect")
def next_line():
global current_line
current_line = next(f)
label.config(text=current_line)
sv = tk.StringVar(root)
sv.trace("w", callback)
label = tk.Label(root,text="")
label.pack()
e = tk.Entry(root, textvariable=sv)
e.pack()
btn = tk.Button(root, text="Click for next", command=next_line)
btn.pack()
next_line() # autoload the first line of the file; remove this line to start with a blank
root.mainloop()
FWIW,请尽量不要使用lambda。它只会使您感到困惑。