xia的小窩

一起來coding和碼字吧

0%

功能鈕-Button

基本的按鈕功能

使用點擊的方式,讓文字顯示出來

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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()

結果

如果要隱藏的話….

1
2
btn2 = Button(root, text = "隱藏訊息", command = root.destroy)
btn2.pack()

這樣就可以連同視窗一起關掉了

使用lambda的時機

以下是一個範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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()

結果

影像功能鈕

1
2
3
4
5
6
7
8
9
10
11
12
13
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()

結果

添加游標

使用cursor

1
btn = Button(root, image = Ball, command = msgShow, cursor = "heart")

這個部分的圖片就給你們自行去實踐了