"_tkinter.TclError: bad screen distance" in python's tkinter when trying to modify object coordinates with Canvas.coords()

user2627127 picture user2627127 · Sep 8, 2015 · Viewed 8k times · Source

I am trying to make a canvas with some items that can move and rotate, to do this, i have functions to modify the coordinates, however i am having trouble with moving the objects. I am trying to use the coords function to change the coordinates of each object.

the current bit of code that is raising the error is:

count = 1
for part in self._createdpartlist:
    self.coords(part, self._partlist[count].coordinates)
    count += 1

self is a Canvas object i created. with createdpartlist containing id's of created parts in canvas (all 4 sided polygons) and partlist being a list of objects that have coordinates that are returned in the form of [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]

however when i try to run it, i get the error;

_tkinter.TclError: bad screen distance "340)]" 

(in this case 340 is the y4 coordinate)

I dont exactly know what it means by bad screen distance, and cant really figure out whats going wrong or if i am using coords function incorrectly.

Any help is greatly appreciated

Edit: i get this error when i make a new file only containing this.

from tkinter import *

coordinates = [(330,230), (350,230), (350,340), (330,340)]
new_coords = [(340,245), (340,260), (400,260), (400,245)]

c = Canvas()

shape = c.create_polygon(coordinates)

c.coords(shape, new_coords)

the error comes up with "245)]" instead of "340)]" in this instance

Answer

KobeJohn picture KobeJohn · Sep 8, 2015

Can you try this? I will try it later when I am not on mobile.

import itertools
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk


# from itertools recipes: https://docs.python.org/2/library/itertools.html
def flatten(list_of_lists):
    """Flatten one level of nesting"""
    return itertools.chain.from_iterable(list_of_lists)


coordinates = [(330,230), (350,230), (350,340), (330,340)]
new_coords = [(340,245), (340,260), (400,260), (400,245)]
c = tk.Canvas()
shape = c.create_polygon(coordinates)
c.coords(shape, *flatten(new_coords))

If that works then try:

for i, part in enumerate(self._createdpartlist):
    self.coords(part, *flatten(self._partlist[i+1].coordinates))