Tkinter(七):Canvas 画布

 

 效果:在canvas画布上添加图片,和各种形状,点击move按钮,可以移动形状

import tkinter as tk

# 定义窗口
window = tk.Tk()
window.title('my window')  # 窗口title
window.geometry('1300x800')  # 窗口尺寸

# 定义canvas,背景颜色为yellow
canvas = tk.Canvas(window, bg='yellow', height=700, width=1200)

'''
放置图片
'''
# 定义图片文件,只能装入gif格式的文件,不能通过更改后缀的方式,需要重新下载,不然会报错
image_file = tk.PhotoImage(file='hui.gif', height=500, width=500)
# 定义图片的位置,anchor是锚定点,可以理解为起始位置
img = canvas.create_image(0, 0, anchor='nw', image=image_file)

'''
自定义形状
'''
# 画直线
x0, y0, x1, y1 = 700, 150, 800, 300
line = canvas.create_line(x0, y0, x1, y1)
# 画圆
oval = canvas.create_oval(x0, y0, x1, y1, fill='red')
# 画扇形,start,extent,扇形从start的角度展开到extent的角度
arc = canvas.create_arc(x0 + 150, y0 + 50, x1 + 250, y1 + 50, fill='grey', start=0, extent=150)
# 长方形
rect = canvas.create_rectangle(x0 + 50, y0 + 170, x1 + 80, y1 + 200, )
canvas.pack()

'''
定义函数让图形移动
'''
def move_it():
    # 移动的形状为rect,点一次横坐标移动0,纵坐标移动10
    canvas.move(rect, 0, 10)

button1 = tk.Button(window, text='move', command=move_it).pack()

window.mainloop()

总结:

1.tkinter只支持放置gif格式的图片,且不能通过改图片后缀,不然会报错

2.move_it定义函数时,要指定canvas,然后canvas.move()

posted @ 2020-09-21 18:06  RonyJay  阅读(1463)  评论(0编辑  收藏  举报