我在填充窗口的
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()
不对应。
这是使用的图像:
这里发生了什么?
该行为已记录下来,您可以按预期观察功能。
canvas.coords(item)
将返回该项目当前所在的位置。canvas.moveto(item, *coord_list)
将放置项目,使右上角位于 *coord_list
中坐标的下方和旁边。
coords
与 moveto
的文档进行比较。
如果没有指定坐标,该命令返回一个列表,其 elements 是由 tagOrId 命名的项目的坐标。
和
在画布坐标空间中移动 tagOrId 给定的项目,以便 第一个坐标对(边界框的左上角) 带有标签 tagOrId 的第一个项目(显示列表中最低的)是 位于位置 (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):
coords = [coordinate-1 for coordinate in cnvs.coords(rect)[0:-2]]
cnvs.moveto(rect, *coords)