M.Jones M.Jones - 7 months ago 33
Python Question

dequeue object from front of queue

Am trying to dequeue a random shape from the front of the queue in my tkinter program. I have tried the

is_empty()
method but I seem to get an error.

>>> AttributeError: 'Queue' object has no attribute 'pop'.


Any help would be great thanks !

This is the queue class I'm using

class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def size(self):
return len(self.items)
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop(0)
def peek(self):
return self.items[0]


class Recta:

def __init__(self, height=60, width=80 ):
self.height = height
self.width = width
self.create_buttons()
self.canvas = Canvas(root)
self.canvas.pack()
self.queue = Queue()



def remove_triangle(self):
if not self.queue.is_empty():
self.canvas.delete(self.queue.pop())

Answer

You don't need to write you own class. Python provides a Queue data structure in its standard library. You can use deque data structure from collections.

from collections import deque
q = deque()
q.append(5)
print q.pop()

Refer to the documentation for deque here.

In your case, simply create a deque object instead of a Queue object.

from collections import deque
class Recta:
    def __init__(self, height=60, width=80 ):
        self.height = height
        self.width = width
        self.create_buttons()
        self.canvas = Canvas(root)
        self.canvas.pack()
        self.queue = deque()  



def remove_triangle(self):
    if not self.queue.is_empty(): 
         self.canvas.delete(self.queue.pop())
Comments