圖像可以顯示在很多物件上,這裡我挑選一個常用案例是顯示在畫布canvas上,首先定義一個tk.Canvas物件:
self.drawingpadcanvas = tk.Canvas(drawingpadPanel, background = 'white')
定義Canvas物件的拉把
drawingpad_sbarV = Scrollbar(drawingpadPanel, orient=tk.VERTICAL)
drawingpad_sbarH = Scrollbar(drawingpadPanel, orient=tk.HORIZONTAL)
drawingpad_sbarV.config(command=self.drawingpadcanvas.yview)
drawingpad_sbarH.config(command=self.drawingpadcanvas.xview)
self.drawingpadcanvas.config(yscrollcommand=drawingpad_sbarV.set)
self.drawingpadcanvas.config(xscrollcommand=drawingpad_sbarH.set)
drawingpad_sbarV.pack(side=tk.RIGHT, fill=tk.Y)
drawingpad_sbarH.pack(side=tk.BOTTOM, fill=tk.X)
打包Canvas物件的位置
self.drawingpadcanvas.pack(side=tk.TOP, expand=tk.NO)
做一個色彩選擇功能的圖形介面,繼續上篇的Canvas功能,接下來可以增添其他功能,有了畫布就想要有調色盤的功能,當from PIL import ImageColor時﹐,可以開啟調色盤工具,這邊我做了一個簡單的調色盤按鈕,我設定設按鈕的背景顏色
self.Color1Button = tk.Button(ColorPanel,
text = "Color 1",
font=('Courier', 7),
command = self.askcolor1)
self.Color1Button.grid(row = 0, column = 0, sticky = tk.E+tk.W)
askcolor()傳回的是HTML格式的色彩,儲存在self.color1[1]上,只要button物件重新config自己的bg設定值,顏色便會回饋在button上
def askcolor1(self, event = None):
self.color1 = askcolor()
self.Color1Button.configure(bg=self.color1[1])
此外還想設定線條的粗細,所以做了設定線條粗細的工具
linewidth = ( 1, 2, 3, 4, 5)
tk.Label(self.MarkSettingPanel,
text = "Line size",
font=('Courier', 7)).grid(row = 0, column = 4, sticky = tk.E+tk.W)
self.linesizespinbox = tk.Spinbox(self.MarkSettingPanel,
values = linewidth,
width = 3)
self.linesizespinbox.grid(row = 0, column = 5, sticky = tk.E+tk.W)
平常程式內部運用顏色設定是有很大機會是使用tuple格式(R, G, B),所以這邊我再加一個HTML轉換RGB tuple函式
def HTMLColorToRGB(self,colorstring):
colorstring = colorstring.strip()
if colorstring[0] == '#': colorstring = colorstring[1:]
if len(colorstring) != 6:
raise(ValueError, "input #%s is not in #RRGGBB format" % colorstring)
r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:]
r, g, b = [int(n, 16) for n in (r, g, b)]
return (r, g, b)
這樣本篇基本的調色盤作法重點就完成了。
紀錄按下滑鼠左鍵事件,prev為之前發生事件,event為現在發生事件
def mouse_press(self, event):
global prev
prev = event
測試事件發生紀錄資料
print('type: {}'.format(event.type))
print('widget: {}'.format(event.widget))
print('num: {}'.format(event.num))
print('x: {}'.format(event.x))
print('y: {}'.format(event.y))
print('x: {}'.format(event.x_root))
print('y: {}'.format(event.y_root))
滑鼠拖移時繪製線條
def draw(self, event):
global prev
self.drawingpadcanvas.create_line(prev.x, prev.y,
event.x, event.y,
width = (self.linesizespinbox.get()),
fill = self.color1[1])
prev = event