[Tutor] TKinter question

Alan Gauld alan.gauld at freenet.co.uk
Tue Mar 21 20:06:08 CET 2006


> My code writes to a text file 'table.txt', and 'table.txt' is displayed in
> the GUI. The user can generate new data at the click of a button
> which re-writes 'table.txt', but I can only add the new table to the GUI
> window rather than 'update' the existing one.

class MoC:
    def __init__(self, master):
        frame = Frame(master, width=600, height=800, bd=1)
        frame.pack()

you are not storing the widgets so they will be lost when you leave 
__init__.

use self.frame, self.text etc so you can access them in other methods.

        #Text box frame
        text=Text(iframe5, height=10, width =70)
        fd = open('table.txt')  #table.txt must be in the same folder
        lines = fd.read()
        fd.close()
        text.insert(END, lines)

This putes the lines at the end of the text box.
You want to use '1.0' as the position instead of END.
Check the documentation on the Text widget in the Tkinter
reference manual.

    #Command definitions
    def quit(self):
        root.destroy()

    def DisplayUpdate(self): #The command definition used to update the 
display.
        #Could I insert a line here to remove the existing frame/text box 
first?
        iframe5 = Frame(root, bd=2, relief=SUNKEN)
        text = Text(iframe5, height=10, width =70)

This creates a new text widget rather than using the one created in init.
If you use self.text in init you can reference thatv same widget here.

        fd = open('table.txt')
        lines = fd.read()
        fd.close()

Since you do this in two places it might be worth making it a
loadFile() method or similar?

        text.insert(END, lines)

If you use '1.0' it should overwrite the old contents. However if
the second is shorter you will get remnants so you might want
to clear the contents too, look at the delete method and use
a start of '1.0' and an end of END...

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list