更新时间:2023-12-03 11:56:58
我对您的代码进行了一些简化,但也对其进行了一些增强.我使用的是askopenfilename
而不是askopenfile
,因此我们可以获取文件名并将其显示在每个包含Text小部件的Toplevel窗口的标题栏中.
I've simplified your code a bit, but I've also enhanced it a little. I use askopenfilename
rather than askopenfile
, so we can get the file name and display it in the titlebar of each Toplevel window containing a Text widget.
import tkFileDialog
import Tkinter as tk
class HomeScreen:
def __init__(self, master):
self.master = master
frame = tk.Frame(master)
frame.pack()
button = tk.Button(frame, text='Show Text', width=25, command=self.open_file)
button.pack()
button = tk.Button(frame, text='Quit', width=25, command=master.destroy)
button.pack()
master.mainloop()
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
window = tk.Toplevel(self.master)
window.title(filename)
text = tk.Text(window, height=10, width=100)
text.pack()
text.insert(1.0, filedata)
def main():
root = tk.Tk()
HomeScreen(root)
if __name__ == '__main__':
main()
要一次显示一个单词一个文本文件,可以将open_file
方法替换为以下版本.您还需要添加show_word
方法.我并不是说这是达到此效果的***方法,但至少可以奏效. :)
To display the text file one word at a time you can replace the open_file
method with the version below. You'll also need to add the show_word
method. I'm not claiming that this is the best way to achieve this effect, but at least it works. :)
def show_word(self, word):
self.text.delete(1.0, tk.END)
self.text.insert(tk.END, word)
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
words = filedata.split()
window = tk.Toplevel(self.master)
window.title(filename)
self.text = text = tk.Text(window, height=10, width=100)
text.pack()
delta = 1000 #in millseconds
delay = 0
for word in words:
window.after(delay, lambda word=word: self.show_word(word))
#print word
delay += delta