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

Cameron Laird Cameron at phaseit.net
Mon Dec 20 17:22:50 CET 2010


On Sun, Dec 19, 2010 at 07:56:33PM +0100, Michael O'Donnell wrote:
			.
			.
			.
> 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()
			.
			.
			.
While many valuable applications have been coded through the
years using exactly this cell-in-Text technique, and the code
above nicely demonstrates the promised scrolling, those 
focused on spreadsheet-like constructs will want to know about
<URL: http://tkinter.unpythonic.net/wiki/TkTable >.


More information about the Tkinter-discuss mailing list