Canvas 通过 create_xxx 方法绘制图形项之后,这些图形项井不是完全静态的图形,每个图形项都是一个独立的对象,程序完全可以动态地修改、删除这些图形项。对这些图形项的引用有两种方式:
1.通过返回值id,如: id1 = create_xxx(...);
2.通过标签 tag,如: cv.create_xxx(..., tags =('rect1'))。
# “物体”移动的例子:
coord = 20,20,30,30
rID=tCanvas.create_rectangle(coord,outline='black',fill='red')
tCanvas.move(rID,50,30)
物体沿着函数图像的轨迹移动
例:先用Graph()画出轨迹,然后用 grMove() 在轨迹上移动一个小方块:
import tkinter as tk
import pyautogui as ag
from math import *
from numpy import arange as np
def Window_Open(W, H):
X, Y = ag.size()
winSize = str(W)+"x"+str(H)
winPos = winSize + "+20" # + str((X - W) // 2)
winPos += "+" + str((Y - H) // 2)
win.geometry(winPos)
win.resizable(False, False)
title = u'桌面分辨率:' + str(X) + "x" + str(Y)
title += ' ' * 5 + u'窗体大小:' + winSize
win.title(title)
win.update()
def Graph(funcx,funcy,x0,y0,tmin,tmax,w,h,c='blue',step=0.001):
'xmin,xmax 自变量的取值范围; c 图像颜色'
'x0,y0 原点坐标 w,h 横纵轴半长 step 步进'
coord = x0-w,y0,x0+w,y0
tCanvas.create_line(coord,fill='black')
coord = x0,y0-h,x0,y0+h
tCanvas.create_line(coord,fill='black')
w1,w2=100,100
for t in np(tmin,tmax+step,step):
x = funcx(t)
y = funcy(t)
coord = x0+w1*x,y0-w2*y,x0+w1*x,y0-w2*y
if abs(x*w1)<w and abs(y*w2)<h:
tCanvas.create_rectangle(coord,outline=c)
tCanvas.update()
def grMove(funcx,funcy,x0,y0,tmin,tmax,w,h,c='blue',step=0.01):
w1,w2=100,100
x,y = funcx(tmin), funcy(tmin)
tx,ty=x,y
coord = x0+w1*x-5,y0-w2*y-5,x0+w1*x+5,y0-w2*y+5
r=tCanvas.create_rectangle(coord,outline=c,fill=c)
for t in np(tmin,tmax+step,step):
x = funcx(t)
y = funcy(t)
if abs(x*w1)<w and abs(y*w2)<h:
tCanvas.move(r,(x-tx)*w1,(ty-y)*w2)
tx,ty=x,y
tCanvas.update()
if __name__ == '__main__':
win = tk.Tk()
Window_Open(480,480)
tCanvas = tk.Canvas(win, width=win.winfo_width(), height=480, bg='white')
tCanvas.pack(side="top")
x0,y0=240,240
a,b = 1,1.5
fx = lambda t : a*cos(t)
fy = lambda t : b*sin(t)
Graph(fx,fy,x0,y0,-pi,pi,220,200)
Graph(fy,fx,x0,y0,-pi,pi,220,200,c='green')
grMove(fx,fy,x0,y0,-pi,pi,220,200,c='red')
grMove(fy,fx,x0,y0,-pi,pi,220,200,c='red')
win.mainloop()
效果图:
附:Graph()函数出自上一篇 《Python tkinter库之Canvas 根据函数解析式或参数方程画出图像》