小白学tkinter(Canvas组件(画布))

来源:互联网 发布:水妖钢笔 知乎 编辑:程序博客网 时间:2024/06/01 15:29

Canvas组件,通常用于显示和编辑图形。
在Canvas上绘制对象,可以用add_xxx()的方法(xxx表示对象类型,
例如直线line、矩形rectangle和文本text等)

from tkinter import *root = Tk()w = Canvas(root,width = 200,height = 100,bg = 'white')w.pack()w.create_line(0,50,200,50,fill = 'yellow') #dash属性 虚线 fill填充颜色w.create_line(100,0,100,100,fill = 'red',dash = (4,4))#outline这是边框颜色 width 边框宽度w.create_rectangle(50,25,150,75,fill = 'blue',outline = 'black',width = 5)root.mainloop()

添加到Canvas上的对象会一直保留。如果希望修改他们需要
使用coods()、itemconfig()、move(方法)

from tkinter import *root = Tk()w = Canvas(root,bg = 'white')w.pack()line1 = w.create_line(0,50,200,50,fill = 'yellow')line2 = w.create_line(100,0,100,100,fill = 'red',dash = (4,4))rect1 = w.create_rectangle(50,25,150,75,fill = 'blue')w.coords(line1,0,25,200,25) #移动组件坐标w.itemconfig(rect1,fill = 'red') #改变组件属性w.delete(line2) #删除组件w.create_text(100,50,text = '我爱PYTHON',fill = 'blue') #添加文本Button(root,text = '删除',command = (lambda x = ALL:w.delete(x))).pack()root.mainloop()

绘制椭圆形或者圆形,使用create_oval()方法,
参数是一个限定矩形(Tkinter会自动在这个矩形内绘制一个椭圆),
如果绘制圆形,限定矩形为正方形

from tkinter import *root = Tk()w = Canvas(root,bg = 'white')w.pack()w.create_rectangle(40,20,160,80,dash = (4,4))#这一行可以不用w.create_oval(40,20,160,80,fill = 'red')#第一组参数就是限定矩形参数w.create_text(100,50,text = '我爱PYTHON')root.mainloop()

可以与事件进行绑定,这以实现画图为例。原理:Tkinter未提供点的工具,
但可以绘制特别小的椭圆来代替,
通过相应‘鼠标左键按住拖动’事件(B1-Motion),
在拖动鼠标的同时获取实时位置(x,y),兵绘制一个超小的椭圆来代替。

from tkinter import *root = Tk()w = Canvas(root,bg = 'white')w.pack()def paint(event):    x1,y1 = (event.x -1),(event.y -1)    x2,y2 = (event.x +1),(event.y +1)    w.create_oval(x1,y1,x2,y2,fill='red') #实时获取的坐标作为参数w.bind('<B1-Motion>',paint)Label(root,text = '按住鼠标左键并移动,绘图吧......').pack(side = BOTTOM)mainloop()