Below is my code, it runs but I\'m not sure how to get the \"Run text\" button to prompt me to open text file in new window, currently a new window appears with a \"Quit\" b
If you want that "Run text"
open's a file dialog change called method:
self.button1 = tk.Button(self.frame, text = 'Run Text', width = 25, command = self.openFile)
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()
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