1. 程式人生 > >Python tkinter 學習記錄(一) --label 與 button

Python tkinter 學習記錄(一) --label 與 button

進入 options 報錯 img code 內容 bind 並不會 order

最簡的形式

from tkinter import *

root = Tk()
# 創建一個Tk實例
root.wm_title("標題")
# 修改標題
root.mainloop()
# 進入root的事件循環

運行結果

技術分享圖片

label標簽的使用

from tkinter import *

root = Tk()
root.wm_title("標題")
w1 = Label(root, text="~~~~~~1號標簽~~~~~~")
w2 = Label(root, text="~~~~~~2號標簽~~~~~~")
w3 = Label(root, text="
~~~~~~3號標簽~~~~~~") w4 = Label(root, text="~~~~~~4號標簽~~~~~~") w1.pack() w4.pack() w3.pack() root.mainloop()

結果

技術分享圖片

說明, 組件創建後並不會立刻出現在窗口上,還需要pack一下才會出現

排列順序取決去 pack的順序 而非創建的順序

使用help函數 了解到 label還有很多屬性

>>> from tkinter import *
>>> help(Label.__init__) Help on function
__init__ in module tkinter: __init__(self, master=None, cnf={}, **kw) Construct a label widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground, highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, takefocus, text, textvariable, underline, wraplength WIDGET
-SPECIFIC OPTIONS height, state, width

help(Label)的結果太多所以改成 help(Label.__init__)

Button 按鈕

它可以綁定一個函數/方法/可調用的對象, 在按鈕被點擊時,會調用與之綁定的東西

兩種綁定方法

一,在定義時 標註command 屬性

from tkinter import *


def add_label():
    global root
    w = Label(text="一個新增的標簽")
    w.pack()


root = Tk()
root.wm_title("one window")

b1 = Button(root, text="一個按鈕", command=add_label)
b1.pack()

root.mainloop()

點了按鈕幾次之後

技術分享圖片

需要註意的是

command=add_label     command屬性 將是一個function對象
command=add_label()   command值為None 因為add_label沒定義返回值
command="add_label"    command 是str對象

第二種方法 使用bind方法

from tkinter import *


def add_label(event):
    global root
    w = Label(text="一個新增的標簽"+str(event))
    w.pack()


root = Tk()
root.wm_title("one window")

b1 = Button(root, text="一個按鈕")
b1.bind("<Button-1>", add_label)
b1.pack()

root.mainloop()

結果(點擊了幾次之後的)

技術分享圖片

xx.bind(事件描述,對應函數名)

對應函數定義時,必須加一個參數,,因為事件的詳細信息會作為參數被"塞給"事件對應的函數 ,事件的詳細信息一般大牛們才用的到,新手可以無視事件的內容 ,但是必須在函數定義處加一個參數 以避免TypeError

TypeError: add_label() takes 0 positional arguments but 1 was given

這個函數需要0個參數, 但是調用時 被給了 1 個參數 參數數目不對 python 難以處理 所以報錯

對應函數名處一定要註意 是函數名 不要加引號 也不要加括號 原因上面已解釋

#end

Python tkinter 學習記錄(一) --label 與 button