Beginner Tkinter Q.: how to re-pack a frame in place?

Matthew Dixon Cowles matt at mondoinfo.com
Tue Jan 1 16:00:20 EST 2002


On Mon, 31 Dec 2001 12:49:02 -0800, J B Bell <bogus at eschatek.com> wrote:

Dear JB,

>Hello all.

Hello!

>I'm new to Tkinter, but not Python.  I've written a utility
>dice-roller for an RPG and would like to GUIfy it.  My main snag
>right now is that I haven't been able to find docs on how one does a
>re-draw in place.  That is, at the simplest level, let's say I have a
>frame with several text input widgets packed into it--I'd like to be
>able to edit one of the input boxes, then hit a "re-sort" button and
>have the fram they're in re-pack them in some kind of sorted order.
>So if I had widgets saying, e.g., "1", "2", "3", and I changed the
>"2" to a "5" and hit "Re-pack", the widget order would change, with
>underlying variables preserved appropriately.

Tkinter will let you unpack and repack widgets as much as you like.
It's not completely clear from your description why that would be an
advantage over moving the data around, but it's not too hard to do.

I'll append a small example that does things both ways.

Regards,
Matt



#!/usr/local/bin/python

from Tkinter import *
import random

def labelsSortHelper(label1,label2):
  val1=int(label1.cget("text"))
  val2=int(label2.cget("text"))
  return cmp(val1,val2)

class mainWin:

  def __init__(self,root):
    self.root=root
    random.seed()
    self.createWidgets()
    self.fillLabels()
    return None

  def createWidgets(self):
    self.labels1=[]
    f1=Frame(self.root)
    for count in range(3):
     l=Label(f1,width=5)
     l.pack(side=LEFT)
     self.labels1.append(l)
    f1.pack(side=TOP)

    self.labels2=[]
    f2=Frame(self.root)
    for count in range(3):
      l=Label(f2,width=5)
      l.pack(side=LEFT)
      self.labels2.append(l)
    f2.pack(side=TOP)
    
    b=Button(self.root,text="New values",command=self.fillLabels)
    b.pack(side=TOP)
    b=Button(self.root,text="Sort",command=self.sort)
    b.pack(side=TOP)
    
    return None
    
  def fillLabels(self):
    for l in self.labels1+self.labels2:
      l.configure(text=str(random.randrange(6)))
    return None
    
  def sort(self):
    valsList=[]
    for count in range(len(self.labels1)):
      valsList.append(int(self.labels1[count].cget("text")))
    valsList.sort()
    for count in range(len(self.labels1)):
      self.labels1[count].configure(text=str(valsList[count]))      

    tempLabels=[]
    for l in self.labels2:
      tempLabels.append(l)
      l.pack_forget()
    tempLabels.sort(labelsSortHelper)
    for l in tempLabels:
      l.pack(side=LEFT)
    self.labels2=tempLabels
    return None

def main():
  root=Tk()
  mainWin(root)
  root.mainloop()
  return None

if __name__=="__main__":
  main()




More information about the Python-list mailing list