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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM