[Tutor] Tkinter, widgets not displaying...

Kent Johnson kent37 at tds.net
Fri Feb 10 14:30:16 CET 2006


Hugo González Monteverde wrote:
> Hi All,
> 
> I wrote a small turn delivering graphical app that is supposed to 
> display turns in a queue.

>      def insert(self, turn_string):
>          """Insert a new turn into the queue, move the rest upwards, 
> delete oldest."""

This is overly complicated:

>          current_values = [self.read_panel(i) for i in 
> range(len(self.canvases))]

You are going to throw away the first value, there is no need to read it.
>          next_values = current_values[:]

There is no need to copy current_values since it is a brand new list 
already.

>          next_values[:-1] = current_values[1:]
>          next_values[-1] = turn_string

This works but you could just copy the part of current_values you want 
and append turn_string.

Taking all this together, you can write just
next_values = [self.read_panel(i) for i in range(1, len(self.canvases))]
next_values.append(turn_string)

But there is a deeper issue here. You seem to be writing some kind of 
simulation. You might want to consider separating your model - the data 
and mechanics of the simulation - from the GUI - the visual 
representation. The way you have it now, the data is stored in the GUI 
itself. This leads to tight coupling between the model and the GUI. It 
will be hard to test the model or to put a different front-end on it, 
and hard to have a clean conceptual model of the simulation.

For example, you could have this model class:

class QueueModel(object):
   def __init__(self, length=4):
     self.data = [None * length ]

   def insert(self, item):
     self.data.pop()  # remove the first item
     self.data.append(item)

Then in your GUI, your insert() method would become update(self, model). 
Or maybe instantiate the GUI giving it an instance of the model. Your 
main program would drive them both. Oversimplifying by leaving out the 
threading, it would look like
   model = QueueModel(length=4)
   gui = TurnQueue(model, pw=200, ph=100)
   for i in range(100):
     model.insert(str(i))
     gui.update()
     sleep(0.2)

As the model develops, this separation from the GUI will make it much 
easier to work with.

Kent



More information about the Tutor mailing list