[Tkinter-discuss] When to use a Canvas vs. a Frame from a container perspective?

Michael O'Donnell michael.odonnell at uam.es
Sun Dec 19 19:56:33 CET 2010


As an example of how to use a Text widget as a container,
below is a simple spreadsheet made using Entry widgets organised
into a Text widget. The user can edit cells, and later save the values of
the cells as a tab delimited file by pressing the "Save" button.

from Tkinter import *

class ScrolledText(Frame):

    def __init__(self, master, **keywords):

        # Set some defaults
        if not keywords.has_key("width"): keywords["width"]=24
        if not keywords.has_key("bg"): keywords["bg"]="white"
        if not keywords.has_key("relief"): keywords["relief"]="sunken"

        Frame.__init__(self, master)
        self.config(bg=keywords["bg"])

        # Scrollbars
        scrollbar = Scrollbar(self, orient=VERTICAL)

        # Create the Text wgt
        self.text=Text(self, yscrollcommand=scrollbar.set, **keywords)
        scrollbar.config(command=self.text.yview)

        scrollbar.pack(side=RIGHT, fill=Y)
        self.text.pack(side=LEFT, fill=BOTH, expand=True)
        self.scroll=scrollbar

def saveSpreadsheet(w):
    out=open("speadsheet.txt", "w")
    for row in w.rows:
        out.write("\t".join([col.get() for col in row])+"\n")
    out.close()

tk = Tk()
stw = ScrolledText(tk, width=100, height=60, wrap="none")
stw.pack(side=BOTTOM, expand=TRUE, fill=BOTH)
Button(tk, text="Save Spreadsheet", command=lambda w=stw:
saveSpreadsheet(w)).pack(side=TOP)

stw.rows=[]
for row in range(60):
    cols=[]
    for col in range(20):
        x=Entry(stw.text, width=10)
        x.row=row
        x.col=col
        cols.append(x)
        stw.text.window_create(END, window=x)
    stw.text.insert(END, "\n")
    stw.rows.append(cols)

tk.mainloop()



On Sun, Dec 19, 2010 at 6:35 PM,  <python at bdurham.com> wrote:
> Mick,
>
>> I use both Canvas and Text for scrollable containers.
>> I use the Canvas when I want pixel accurate placement.
>>
>> I use a Text widget for more lazy placement (one can place items after each other on a row, and start a new row with a "\n"). One can make spreadsheets by placing rows of entry widgets of equal width. However, with hundreds of widgets in a text widget, I find performance suffers.
>
> I love the idea of creating scrollable containers using Text widgets.
> I'll give this technique a try (with your caution about performance for
> large number of widgets).
>
> Thanks,
> Malcolm
>


More information about the Tkinter-discuss mailing list