Home > Mobile >  Group widgets in parent container tkinter
Group widgets in parent container tkinter

Time:10-17

Im drawing lines in the canvas, the problem is that the number of lines is not static, so to draw them i use a loop:

 def createBars(self):
        
        size = (200, 50);

        for i in range(6):
            self.canvas.create_line(size[0], i*size[1], size[0], size[1] (i*size[1]), fill = self.COLORS[i], width = 10);

it works, i get my lines one below each other as i wish, the problem now is that i need to move all of them at the same time when clicking of them, since to move each of them i need to access to the method moveto, i dont know how to move all of them as group, cant find any related like draw all them inside a box then i can move the box with them inside.

tried appending each of the lines in an array but when printing i get an integer instead of the line object, but if creating it in the constructor each of them can access to the method, but doing it in array way dont know how

CodePudding user response:

First off, a bit of terminology. The lines you draw are not widgets. They are called canvas items, and are very different than widgets.

The solution is to apply one or more tags to each item, and then pass the tag name to the moveto method, or any other method that takes an item id or a tag.

Here's an example that adds the tags "line" and the line color to each element. The arrow keys will move all of the items together. You can easily modify it to move only a particular color by changing the tag passed to the move method.

class Example(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        self.canvas = tk.Canvas(self)
        self.canvas.pack(fill="both", expand=True)
        self.COLORS=["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
        self.createBars()

        self.canvas.bind("<Left>", self.go_left)
        self.canvas.bind("<Right>", self.go_right)
        self.canvas.focus_set()

    def go_left(self, event):
        self.canvas.move("line", -5, 0)

    def go_right(self, event):
        self.canvas.move("line",  5, 0)

    def createBars(self):

        size = (200, 50);

        for i in range(6):
            self.canvas.create_line(
                size[0], i*size[1], size[0], size[1] (i*size[1]),
                fill = self.COLORS[i], width = 10,
                tags=("line", self.COLORS[i]),
            );

tried appending each of the lines in an array but when printing i get an integer instead of the line object

This is the defined behavior. create_line and the other methods for creating canvas items return an integer identifier for the created object. The lines and other canvas items aren't themselves python objects.

  • Related