Tkinter Python GUI Issues

岁酱吖の 提交于 2019-11-29 18:26:20

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

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!