[Tutor] Tkinter and after() method

Cameron Simpson cs at cskk.id.au
Tue Jan 31 16:27:10 EST 2023


On 31Jan2023 15:46, Phil <phillor9 at gmail.com> wrote:
>Thank you Cameron. The most glaring flaw is that I cannot display 
>multiple dials. I can see why but I'm not sure how to fix the flaw.  
>Even though it runs without error, It's starting to get overly complex.

As you suspect, using a global limits your flexibility.

How about having the dial instance do its own ticker loop? Untested 
example:

class Dial:
    def __init__(self, frame, canvasName, x=60, y=60, size=60):
         self.frame = frame
        self.canvasName = canvasName
         self.x = x  # centre of dial
        self.y = y
        self.size = size # the diameter of the dial
        self.xn = self.x + 1 # the end points of the ticks and pointer
        self.yn = self.y + 1
        self.value = 0 # the pointer's value
         self.loop()

     def loop(self):
         self.value += 10  # change the pointer position by 10%
         if self.value > 100:
             self.value = 0
         move_pointer(self, self.canvasName)
         self.frame.after(1000, self.loop)

Note that last line: `self.loop` is a reference to the `loop()` method 
for this particuar dial. The initialisation of the Dial kicks off the 
first execution of that `loop()`, as you _were_ doing in `Root.__init__` 
but now should do here, thus once per Dial as made.

Then intialise your dial with the addition of the frame and canvasName, 
and do that in Root.__init__. That lets you drop the globals entirely.

The basic pattern here is that all the relevant state is stored with the 
Dial, and thus you can independently have many dials.

Frankly, I've have move_pointer() _also_ be a method of Dial.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list