我try 了下面的脚本,在充满窗口的canvas中:

import tkinter as tk
from PIL import Image, ImageTk
from time import *

root = tk.Tk()
root.geometry("500x500")
canvas = tk.Canvas(root)
canvas.pack()

def fill(event):
    canvas.config(width = root.winfo_width(), height = root.winfo_height())
root.bind("<Configure>", fill)

img = Image.open("CO2.png")
imgtk = ImageTk.PhotoImage(img)
item = canvas.create_image(15, 15, image = imgtk)
while True:
    canvas.moveto(item, canvas.coords(item)[0], canvas.coords(item)[1])
    root.update()
    sleep(0.5)

这应该没有什么作用,因为它只是将一件物品移动到它已经在的地方.但在实践中,这会将图像移向正x和y方向,这意味着从canvas.coords()开始的坐标略有偏离,与canvas.moveto()不符.

以下是使用过的图片:

enter image description here

这是怎么回事?

推荐答案

That behavior is documented 和 you observing the functionality as it is intended.
canvas.coords(item) will return where the item currently is.
canvas.moveto(item, *coord_list) will place the item so that the upper left corner is below 和 next to the coordinates in *coord_list.

coordsmoveto的文档进行比较.

如果未指定坐标,此命令将返回一个列表,该列表 元素是由tag OrId命名的项的坐标.

在画布坐标空间中移动tag OrId给出的项,以便 第一个坐标对(bounding box的左上角) 标签为tag OrID的第一个项目(显示列表中最低的)的 位于(xPos,yPos)位置

这段小代码演示了您的体验:

import tkinter as tk

def test(event):
    cnvs.moveto(rect, *cnvs.coords(rect)[0:-2])

root = tk.Tk()
cnvs = tk.Canvas(root, highlightthickness=0)
cnvs.pack()
rect = cnvs.create_rectangle(0,0,50,50, fill='red')
print(cnvs.coords(rect))
root.bind('<1>', test)
root.mainloop()

而将功能测试更改为以下测试将解决此问题:

def test(event):
    delta = int(float(cnvs.itemcget(rect, 'width'))/2)
    coords = [coordinate-delta for coordinate in cnvs.coords(rect)[0:-2]]
    cnvs.moveto(rect, *coords)

However, you would need to tweak it for different item-types with other coordinate properties as well. The usual way to update coordinates with tk 和 tkinter is to use canvas.coords(item, *new_coords) anyway.

Python相关问答推荐

为什么我的Python代码在if-else声明中的行之前执行if-else声明中的行?

Django mysql图标不适用于小 case

numba jitClass,记录类型为字符串

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

如何标记Spacy中不包含特定符号的单词?

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

如何在给定的条件下使numpy数组的计算速度最快?

avxspan与pandas period_range

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

如何在Python中使用另一个数据框更改列值(列表)

try 检索blob名称列表时出现错误填充错误""

Python全局变量递归得到不同的结果

Python Mercury离线安装

多个矩阵的张量积

PySpark:如何最有效地读取不同列位置的多个CSV文件

如何在Django模板中显示串行化器错误

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)

如何通过函数的强式路径动态导入函数?