简体   繁体   中英

reading lines from a file using tkinter

I've done a typing tutor project and now i would like to make a GUI version of it. So, I am trying to read a file line by line to tkinter and the user has to type each line one by one. That means if he types the first line correctly, the second line shows up and till the end.

this is my code:

import tkinter as tk

root = tk.Tk()
root.resizable(True, True)
frame = tk.Frame(root)
frame.pack()

def callback(sv):
    print(sv.get())
    return sv.get()

sv = tk.StringVar(root)
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv))


with open('sentences.TXT', 'r') as myfile:
     cnt = 1
     for line in myfile:
         # var = tk.StringVar(root)
         label = tk.Label(root, textvariable=sv, relief=tk.RAISED)
         sv.set(line)
         cnt +=1
         label.pack()
         e = tk.Entry(root, textvariable=sv)
         e.pack()


root.mainloop()

my teacher told me not to use for loops! but if there's no for loop, then, how to print line by line? i hope someone can figure it out help me with this, Thanks!

You can manually call next on your file object to get the next sentence:

import tkinter as tk

root = tk.Tk()

f = open('sentence.txt', 'r')

label = tk.Label(root,text="")
label.pack()
tk.Button(root,text="Click for next",
          command=lambda: label.config(text=next(f))).pack()

root.mainloop()

Note that this will raise an StopIteration error when the iterator is exhausted - you can catch it by creating a function and add a try...except block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM