Skip to main content
 首页 » 编程设计

python之尝试使用 Canvas.coords() 修改对象坐标时 python 的 tkinter 中的 "_tkinter.TclError: bad screen distance"

2024年10月24日15JustinYoung

我正在尝试用一些可以移动和旋转的项目制作 Canvas ,为此,我有修改坐标的功能,但是我在移动对象时遇到了问题。我正在尝试使用 coords 函数来更改每个对象的坐标。

当前引发错误的代码是:

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

self 是我创建的 Canvas 对象。 createdpartlist 包含在 Canvas 中创建的部分的 id(所有 4 边多边形)和 partlist 是一个对象列表,这些对象的坐标以 [(x1, y1), (x2, y2), (x3, y3) 的形式返回, (x4, y4)]

但是当我尝试运行它时,我得到了错误;

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

(在本例中 340 是 y4 坐标)

我不完全知道屏幕距离差是什么意思,也无法真正弄清楚出了什么问题,或者我是否错误地使用了坐标函数。

非常感谢任何帮助

编辑:当我创建一个仅包含此文件的新文件时出现此错误。

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) 

在这种情况下错误出现为“245)]”而不是“340)]”

请您参考如下方法:

你能试试这个吗?我稍后会在不使用移动设备时尝试。

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)) 

如果可行,请尝试:

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