# 功能鈕 Button ###### tags: `活用tkinter – 學習運用GUI` ## 基本的按鈕功能 * 使用點擊的方式,讓文字顯示出來 ```python= from tkinter import * def msgShow(): label["text"] = "我愛蟒蛇" label["bg"] = "lightyellow" label["fg"] = "red" root = Tk() root.title("python-tkinter") root.geometry("300x400") label = Label(root) btn = Button(root, text = "顯示訊息", command = msgShow) # command的用法就是下一步的動作 label.pack() btn.pack() root.mainloop() ``` * 結果 ![](https://i.imgur.com/tykxxb0.png) * 如果要隱藏的話.... ```python= btn2 = Button(root, text = "隱藏訊息", command = root.destroy) btn2.pack() ``` * 這樣就可以連同視窗一起關掉了 ## 使用lambda的時機 * 範例 ```python= from tkinter import * def bColor(bgColor): root.config(bg = bgColor) root = Tk() root.title("python-tkinter") root.geometry("300x400") #label = Label(root) exbtn = Button(root, text = "exit", command = root.destroy) bluebtn = Button(root, text = "Blue", command = lambda : bColor("blue")) greenbtn = Button(root, text = "Green", command = lambda : bColor("green")) #label.pack() exbtn.pack(anchor = S, side = RIGHT, padx = 5, pady = 5) bluebtn.pack(anchor = S, side = RIGHT, padx = 5, pady = 5) greenbtn.pack(anchor = S, side = RIGHT, padx = 5, pady = 5) root.mainloop() ``` * 結果 ![](https://i.imgur.com/bVActVM.png) ## 影像功能鈕 * 範例 ```python= def msgShow(): label.config(text = "純測試用", bg = "red", fg = "green") # 接續 image = Image.open("ball.jpg") Ball = ImageTk.PhotoImage(image) label = Label(root) btn = Button(root, image = Ball, command = msgShow) label.pack() btn.pack() ``` * 結果 ![](https://i.imgur.com/ZRde59c.png) ## 添加游標 * 使用cursor :point_down: ```python= btn = Button(root, image = Ball, command = msgShow, cursor = "heart") ``` * 這個部分的圖片就給你們自行去實踐了 {%hackmd S1DMFioCO %}