### ex5-1 ### import tkinter root = tkinter.Tk() root.title('在Canvas繪製影像') canvas = tkinter.Canvas(width = 480, height = 300) canvas.pack() img_bg = tkinter.PhotoImage(file = 'images/park.png') canvas.create_image(240, 150, image = img_bg) root.mainloop() ### ex5-2 ### import tkinter x = 0 # 管理捲動位置的變數 def scroll_bg(): # 執行捲動的函式 global x x = x + 1 # 設定捲動的速度 if x == 480: # 讓圖片的 X 座標 在 0 ~ 479 之間移動,超過 480 則重設為 0 x = 0 canvas.delete('BG') # 暫時刪除背景影像 'BG' canvas.create_image(x - 240, 150, image = img_bg, tag = 'BG') # 繪製背景影像 (左側) canvas.create_image(x + 240, 150, image = img_bg, tag = 'BG') # 繪製背景影像 (右側) root.after(50, scroll_bg) # 50 毫秒後再次執行這個函式 root = tkinter.Tk() root.title('捲動畫面') canvas = tkinter.Canvas(width = 480, height = 300) canvas.pack() img_bg = tkinter.PhotoImage(file = 'images/park.png') scroll_bg() # 執行捲動的函式 root.mainloop() ### ex5-3 ### import tkinter x = 0 # 管理捲動位置的變數 ani = 0 # 選擇小狗動畫圖片的變數 def animation(): # 執行捲動與小狗走路的函式 global x, ani x = x + 4 if x == 480: x = 0 canvas.delete('BG') canvas.create_image(x - 240, 150, image = img_bg, tag = 'BG') canvas.create_image(x + 240, 150, image = img_bg, tag = 'BG') ani = (ani + 1) % 4 # 讓 ani 的值在 0 ~ 3 之間變化 canvas.create_image(240, 200, image = img_dog[ani], tag = 'BG') # 繪製小狗圖片 root.after(200, animation) root = tkinter.Tk() root.title('動畫') canvas = tkinter.Canvas(width = 480, height = 300) canvas.pack() img_bg = tkinter.PhotoImage(file = 'images/park.png') img_dog = [ # 在 list 載入小狗圖片 tkinter.PhotoImage(file = 'images/dog0.png'), tkinter.PhotoImage(file = 'images/dog1.png'), tkinter.PhotoImage(file = 'images/dog2.png'), tkinter.PhotoImage(file = 'images/dog3.png') ] animation() # 執行函式 animation() root.mainloop() ### ex5-4 ### import tkinter root = tkinter.Tk() root.title('地圖資料') canvas = tkinter.Canvas(width = 336, height = 240) canvas.pack() img = [ # 在 list 載入地圖圖片 tkinter.PhotoImage(file = 'images/chip0.png'), tkinter.PhotoImage(file = 'images/chip1.png'), tkinter.PhotoImage(file = 'images/chip2.png'), tkinter.PhotoImage(file = 'images/chip3.png') ] map_data = [ # 用二維 list 定義地圖資料 [0, 1, 0, 2, 2, 2, 2], [3, 0, 0, 0, 2, 2, 2], [3, 0, 0, 1, 0, 0, 0], [3, 3, 0, 0, 0, 0, 1], [3, 3, 3, 3, 0, 0, 0] ] for y in range(5): for x in range(7): n = map_data[y][x] # 把二維 list 的值帶入變數 n canvas.create_image(x * 48 + 24, y * 48 + 24, image = img[n]) # 繪製地圖 root.mainloop() ### ex5-5 ### import tkinter def mouse_click(e): # 定義按下滑鼠的函式 px = e.x # 把滑鼠游標的 X 座標帶入 px py = e.y # 把滑鼠游標的 Y 座標帶入 px print('滑鼠游標的座標是({}, {})'.format(px, py)) # 輸出 px 與 py 的值 mx = int(px / 48) # 把 px 換算成 mx (圖塊的 X 位置索引) my = int(py / 48) # 把 py 換算成 my (圖塊的 Y 位置索引) if 0 <= mx and mx <= 6 and 0 <= my and my <= 4: # 如果 mx 與 my 在地圖範圍內 n = map_data[my][mx] # 把圖塊的編號代入 n print('這裡的圖塊是' + CHIP_NAME[n]) # 輸出圖塊的名稱 root = tkinter.Tk() root.title('地圖資料') canvas = tkinter.Canvas(width = 336, height = 240) canvas.pack() canvas.bind('