Tkinter控件Canvas


網上關於tkinter的canvas組件系統的中文教程很少,英文教程未知。要么是專業的參考文檔,沒有豐富的實例,要么在不同的論壇,博客平台零零散散存在一些canvas的例子,這給學習canvas帶來了不便。也許應該從各種canvas的實例着手,結合參考文檔,邊學習邊總結。除此之外從哪里開始也是一個問題,目前對我來說,需求是通過canvas實現自繪按鈕,那么就這樣開始吧。
1.canvas繪制基本圖形的方法
1.1畫線(Line)
方法:
create_line(x0,y0,x1,y1,……,xn,yn,*options)
參數x0到yn指定顯示中一系列的兩點或多點坐標,來描述一條線或一系列線。在數的后面可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。
例子:

from tkinter import *
root=Tk()
cv=Canvas(root,background="white")
cv.pack()

line_point=[(10,10),(12,11),(15,18),
            (20,22),(24,23),(30,39),
            (40,45),(50,60),(60,10),
            (100,101),(110,110),(112,114),
            (116,115),(120,118),(170,200)]
line1=cv.create_line(line_point,fill="orange",dash=(10,6,3),arrow=LAST,smooth=TRUE,width=5)
line2=cv.create_line(line_point,fill="blue",dash=(10,6,3),arrow=LAST,smooth=TRUE,width=5)
line3=cv.create_line(line_point,fill="red",dash=(10,6,3),arrow=LAST,smooth=TRUE,width=5)

cv.coords(line1,20,20,30,10,170,200)
cv.delete(line3)

root.mainloop()

用到的屬性
·fill,設置線的填充顏色
·dash,設置為虛線
·arrow,設置線的箭頭,默認為None,表示無箭頭,還可以設置為FIRST,LAST,BOTH
·smooth,值為布爾值,指出線是否是曲的
·width,設置線寬
其他方法
·coords(item,x0,y0,x1,y1,……,xn,yn
查詢或修改一個項的坐標
·delete(item)
刪除一項
1.2畫矩形(Rectangle)
方法:
create_rectangle(x0,y0,x1,y1,*options)
參數x0,y0,x1,y1指定顯示中長方形對坐標(左上角和右下角),在數的后面可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。
例子:

from tkinter import *
root=Tk()
cv=Canvas(root,background="white")
cv.pack()

rt1=cv.create_rectangle(100,50,300,200,outline="green",fill="red",stipple="gray25")
rt2=cv.create_rectangle(100,50,300,200,outline="green",fill="green",stipple="gray25")

cv.coords(rt2,60,70,260,220)

root.mainloop()

用到的屬性
·outline,邊界顏色,如果為空則不畫邊界
·stipple,指出長方形填充點的樣式,單位為bitmap
其他方法
coords,delete
例2:

from tkinter import *
root=Tk()
cv=Canvas(root,width=850,height=400)
cv.pack()
pw=20
for k in range(2):
    for i in range(20):
        for j in range(20):
            cv.create_rectangle(
            k*450+j*pw, i*pw, k*450+(j+1)*pw, (i+1)*pw)

root.mainloop()

1.3畫多邊形(Polygon)
方法:
create_polygon(x0,y0,x1,y1,*options)
參數x0到yn指定顯示中一系列的三點或多點坐標,來描述一個封閉多邊形。起點和終點可以相同也可以不同;不管相同與否,Tkinter都畫出封閉的多邊形。在數的后面可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。
例1:

from tkinter import *
root=Tk()
cv=Canvas(root)
cv.pack()

poly_points=[(0,80),(140,0),(140,40),(270,40),
             (270,120),(140,120),(140,160)]
cv.create_polygon(poly_points,fill="pink")
root.mainloop()

屬性有outline,smooth,stipple,tags
其他方法:delete,coords.itemconfigure

擴展閱讀Canvas Widgets

以下為節選:

當你看到這里的時候,可能馬上就到聖誕節了,也可能沒有,我們通過Tkinter創建一些星星來提高下一個聖誕節的氛圍。第一顆星星是直接創建的,幾乎不使用任何編程的技巧。

from tkinter import *
canvas_width = 200
canvas_height =200
python_green = "#476042"
master = Tk()
w = Canvas(master, 
           width=canvas_width, 
           height=canvas_height)
w.pack()
points = [100, 140, 110, 110, 140, 100, 110, 90, 100, 60, 90, 90, 60, 100, 90, 110]
w.create_polygon(points, outline=python_green, 
            fill='yellow', width=3)
mainloop()

正如我們提及的,這是一種很笨拙的方法。設想如果我們需要改變星星的尺寸或者厚度,我們就必須手動地改變所有的點坐標,這很容易出錯而且顯得很繁瑣。所以我們提供前一個腳本的新版本,將包含更多的編程技能。我們使用函數來生成星星,使用一個起始點和兩個表示長度的p和t參數創建星星:


我們改進的程序如下:

from tkinter import *

canvas_width = 400
canvas_height =400
python_green = "#476042"

def polygon_star(canvas, x,y,p,t, outline=python_green, fill='yellow', width = 1):
   points = []
   for i in (1,-1):
      points.extend((x,          y + i*p))
      points.extend((x + i*t, y + i*t))
      points.extend((x + i*p, y))
      points.extend((x + i*t, y - i * t))

   print(points)

   canvas.create_polygon(points, outline=outline, 
                         fill=fill, width=width)

master = Tk()

w = Canvas(master, 
           width=canvas_width, 
           height=canvas_height)
w.pack()

p = 50
t = 15

nsteps = 10
step_x = int(canvas_width / nsteps)
step_y = int(canvas_height / nsteps)

for i in range(1, nsteps):
   polygon_star(w,i*step_x,i*step_y,p,t,outline='red',fill='gold', width=3)
   polygon_star(w,i*step_x,canvas_height - i*step_y,p,t,outline='red',fill='gold', width=3)

mainloop()

1.4畫橢圓
方法:
create_oval(x0,y0,x1,y1,*options)
x0,y0,x1,x2給出橢圓的矩形的對角坐標。在坐標之后可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。

例子:

from tkinter import *
root=Tk()

cv=Canvas(root)

cv.create_oval(50,30,300,200,fill="lightblue",outline="",width=3)

cv.pack()
mainloop()

屬性有:outline,stipple(貌似無效),tags
其他方法:delete,coords.itemconfigure
1.5畫弧形(Arc)
方法:create_arc(x0,y0,x1,y1,*options)
x0,y0,x1,y1給出包含定義弧的橢圓的矩形對角坐標。在坐標之后可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。

例子:

from tkinter import *
root=Tk()

cv=Canvas(root)

cv.create_arc(50,30,300,200,fill="lightblue",outline="lightblue",style="arc")
cv.create_arc(50,30,300,200,fill="orange",outline="",start=90,extent=70)
cv.create_arc(50,30,300,200,fill="yellow",outline="",start=160,extent=60)
cv.create_arc(50,30,300,200,fill="blue",outline="",start=220,extent=90,style=CHORD)
cv.pack()
mainloop()

用到的屬性:
·start,指定弧所占角度起始點,角度是按照順時針方向測量的,角度大小可以是正,也可以是負
·extent,指出所包含角度的大小,角度從起始點按逆時針方向開始
·style,指定如何畫弧,默認是PIESLICE,還可以設置為ARC,CHORD
其他屬性:
stipple(未知),outlinestipple(未知),tags等
其他方法:delete,coords
1.6畫位圖(Bitmap)
方法:create_bitmap(x,y,*options)
參數x,y指定顯示中用來定位位圖的點的坐標(使用anchor選項)。在坐標后面可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。

例子:

from tkinter import *
root=Tk()

cv=Canvas(root)

bitmaps = ["error", "gray75", "gray50", "gray25", "gray12",
"hourglass", "info", "questhead", "question", "warning"]
for i in range(len(bitmaps)):
    cv.create_bitmap((i+1)*30,30,bitmap=bitmaps[i])

cv.pack()
mainloop()

屬性:tags,bitmap
其他方法:delete,coords
1.7畫圖像(Image)
create_image(x,y,*options)
參數x,y指定顯示中用來定位圖像的點的坐標(使用anchor選項)。在坐標后面可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。
屬性:tags,image
其他方法:delete,coords
1.8文本(Text)
方法:create_text(x,y,*options)
參數x,y指定顯示文本的點的坐標,在數的后面可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。

例子:

from tkinter import *
root=Tk()

cv=Canvas(root)

cv.create_text(100,50,text="這是第一行文字",font="黑體,16",fill="Blue",)

cv.pack()
mainloop()

屬性:font,justify,tags,text
其他屬性:stipple(未知)
其他方法:delete,coords
1.9畫窗口
方法:create_window(x,y,*options
參數x,y指定顯示窗口的點的坐標,在數的后面可以是任何數量的選項-值對。每對用戶來配置選項。這些相同的選項-值對可以用在itemconfigure調用中修改項的配置。

例子:

from tkinter import *
root=Tk()

cv=Canvas(root)

frm=Frame(cv,relief=GROOVE,borderwidth=2)
Label(frm,text="Embedded Frame/Label").pack()
cv.create_window(100,50,window=frm,anchor=CENTER)

cv.pack()
mainloop()

屬性:tags,window
其他方法:delete,coords

1.10Canvas函數一些屬性,方法
1.10.1屬性
·highlightthickness,缺省值為2,文本框高兩邊寬度
·stipple,用畫刷填充,單位是bitmap,可以直接使用系統bitmap索引,["error", "gray75", "gray50", "gray25", "gray12","hourglass", "info", "questhead", "question", "warning
·tags,為項目添加標簽,tags可以用來索引item,如item=cv.create_rectangle(tags="t1"),delete("t1")和delete(item)等效;可以使用gettags(item)獲得項目的tags,與此相反,使用find_widthtag("t1")獲得對應item。其他關於tags的操作函數還有addtag_above,addtag_below,find_above,find_below等
1.10.2方法
·move(item,x,y),將項目的橫縱坐標移動x,y個單位
示例:

from tkinter import *
def move_rect():
    cv.move(rect,10,10)

root=Tk()
cv=Canvas(root,width=400,height=400,highlightthickness=0,bd=0)
cv.configure(bg="black")

rect=cv.create_rectangle(0,0,20,20,outline="red")

btn=Button(cv,text="Move",background="orange",activebackground="green",command=move_rect)
cv.create_window(300,300,height=50,width=50,window=btn)

cv.pack()
root.mainloop()

·delete(item1,item2,item3,item4)刪除項目,傳入ALL刪除所有項目
·scale(item, xscale, yscale, xoffset, yoffset)
按比例調整item的大小(縮放),項目的坐標按照(coord-offset)*scale+offset被重新計算。換言之,每個項目先移動 -offset,然后乘以比例因子,最后再移回來。值得注意的是,這種方法修改了項目的坐標,如果在一個項目中多次使用該方法,可能會降低精度。
·tag_bind(item, event=None, callback, add=None)
為所有匹配項目添加事件綁定


免責聲明!

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



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