Rushy Panchal
Rushy Panchal

Reputation: 17552

Tkinter Canvas - Draw text on top

I have this class to create a Statusbar:

class Statusbar(Canvas):
    '''Creates a statusbar widget'''
    def __init__(self, master = None, **options):
        if not master: master = Tk()
        self.master, self.options = master, options
        self.barFill, self.addText, self.value = self.options.get('barFill', 'red'), self.options.get('addText', True), 0
        for option in ('barFill', 'addText'):
            if option in self.options: del self.options[option]
        Canvas.__init__(self, master, **self.options)
        self.offset = self.winfo_reqwidth() / 100
        self.height = self.winfo_reqwidth()
        if self.addText: self.text = self.create_text(self.winfo_reqwidth()/2, self.winfo_reqheight()/2, text = '0%')
        self.bar = self.create_rectangle(0, 0, self.value, self.height, fill = self.barFill)

    def setValue(self, value):
        '''Sets the value of the status bar as a percent'''
        self.value = value * self.offset
        self.coords(self.bar, 0, 0, self.value, self.height)
        if self.addText: self.itemconfigure(self.text, text = str(self.value/self.offset) + '%')

    def change(self, value):
        '''Changes the value as a percent'''
        self.value += (value * self.offset)
        self.coords(self.bar, 0, 0, self.value, self.height)
        if self.addText: self.itemconfigure(self.text, text = str(self.value/self.offset) + '%')

My issue is that the text is always drawn under rectangle. So when the rectangle reaches the text, you can't see the text anymore. How can I fix this? Thanks in advance.

Upvotes: 1

Views: 3121

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386332

The fact that one object sits atop another is called the stacking order. By default, objects created later have a higher stacking order than those that were created earlier. So, one solution is to draw the rectangle and then draw the text.

You can also move things up or down the stacking order using the lift and lower commands of a canvas. You must give it an id or tag of what you want to lift or lower, and optionally an id or tag of the object you want the first object(s) to be above or below.

So, for example, you could raise the text above the rectangle like this:

self.lift(self.text, self.bar)

If you want to get really fancy, you can create the notion of layers. I gave an example in another answer, here: https://stackoverflow.com/a/9576938/7432

Upvotes: 3

Joe Michail
Joe Michail

Reputation: 449

In my programming class, we said put whatever text you don't want to be blocked drawn last. So put the text at the bottom of what function you are using to draw with

Upvotes: 1

Related Questions