Day 27 - Tkinter & *args & **kwargs


Posted by pei_______ on 2022-05-07

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


Tkinter widget demo
Tkinter - Tk Commands


Tkinter - Wedget

from tkinter import *

0. Create a Window

window = Tk()
window.title("Widget Example")
window.minsize(width=500, height=500)
window.config(bg=BACKGROUND_COLOR, padx=50, pady=50)

# Set at the end to keep window always show on
window.mainloop()

1. Labels 標題

label = Label(text="This is old text", font=("Arial", 24, "bold"))
label.config(text="Hello!")
label.pack()

2. Entry 輸入欄位

entry = Entry(width=30)

# put cursor in text box
entry.focus()

# add some text to begin with
entry.insert(END, string="Key your name")
entry.pack()

3. Buttons 按鈕

def action():
    label.config(text=f"Hello! {entry.get()}")

# calls action() when pressed
button = Button(text='Enter', command=action)
button.pack()

# image style
button_image = PhotoImage(file="image.png")
button = Button(image=button_image, highlightthickness=0, command=new_word)

# cancel the command of button
button.config(state="disabled")

4. Text 多列文字欄位

text = Text(height=3, width=30)

# put cursor in text box
text.focus()

# Adds some text to begin with
text.insert(END, "Example of multi-line text entry.")

# Get's current value in textbox at line 1, character 0
print(text.get("1.0", END))
text.pack()

5. Spinbox 點擊式上下選單

def spinbox_used():
    # gets the current value in spinbox.
    print(spinbox.get())

spinbox = Spinbox(from_=0, to=5, width=5, command=spinbox_used)
spinbox.pack()

6. Scale 拖曳式上下選單

# Called with current scale value.
def scale_used(value):
    print(value)

scale = Scale(from_=0, to=10, command=scale_used)
scale.pack()

7. Checkbutton 可複選勾選欄位

def checkbutton_used():
    #Prints 1 if On button checked, otherwise 0.
    print(checked_state.get())

# variable to hold on to checked state, 0 is off, 1 is on.
checked_state = IntVar()
checkbutton = Checkbutton(text="Is On?", variable=checked_state, command=checkbutton_used)
checked_state.get()
checkbutton.pack()

8. Radiobutton 單選式勾選欄位

def radio_used():
    print(radio_state.get())

# Variable to hold on to which radio button value is checked.
radio_state = IntVar()
radiobutton1 = Radiobutton(text="Option1", value=1, variable=radio_state, command=radio_used)
radiobutton2 = Radiobutton(text="Option2", value=2, variable=radio_state, command=radio_used)
radiobutton1.pack()
radiobutton2.pack()

9. Listbox 點擊式多項欄位

def listbox_used(event):
    # Gets current selection from listbox
    print(listbox.get(listbox.curselection()))

listbox = Listbox(height=4)
fruits = ["Apple", "Pear", "Orange", "Banana"]
for item in fruits:
    listbox.insert(fruits.index(item), item)
listbox.bind("<<ListboxSelect>>", listbox_used)
listbox.pack()

10. Image 圖片 & Text 附加文字

canvas = Canvas(bg="white", width=50, height=50, highlightthickness=0)
apple = PhotoImage(file="apple.png")

# set content
apple_img = canvas.create_image(40, 40, image=apple)
apple_text = canvas.create_text(20, 20,text="apple", fill="green", font=("Arial", 40, "italic"))

# change content
banana = PhotoImage(file="banana.png")
banana_img = canvas.create_image(40, 40, image=banana)
canvas.itemconfig(apple_img, image=banana_img)
canvas.itemconfig(apple_text, text="banana", fill="yellow")

canvas.pack()

11. Use after() instead of time.sleep()

flip_timer = window.after(3000, flip_card)
window.after_cancel(flip_timer)

Tkinter - Layout Manager

pack() 大概位置
label.place(side='right')

place() 確定座標
label.place(x=100, y=200)

grid() 相對位置
label.grid(column=1, row=3)
can't not use pack & grid at same time

config() 物件間隔
sceen.config(padx=100, pady=100)
label.config(padx=50, pady=50)


args & kwargs

unlimited numbers of argument with Default Values

args = tuple => position argument

def add(*args):
    for n in args:
        print(n)

add (3,4,5,7)

kwags = dictionary => keyword argument

def calculate(n, **kwags):
    n += kwags["add"]
    n *= kwags["multiply"]
    print(n)

calculate(2,add=3,multiply=6)
class Car:
    def __init__(self,**kw):
        self.make = kw.get("make")
        self.model = kw.get("model")
def all_aboard(a, *args, **kw):
    print(a, args, kw)

all_aboard(4, 7, 3, 0, x=10,y=64)
# 4 (7, 3, 0) {'x':10, 'y':64}

#Python #課堂筆記 #100 Days of Code







Related Posts

CS50 TCP (Transmission Control Protocol)

CS50 TCP (Transmission Control Protocol)

【 JS筆記 】 e.target 與 e.currentTarget 的差別

【 JS筆記 】 e.target 與 e.currentTarget 的差別

七天打造自己的 Google Map 應用入門 - Day04

七天打造自己的 Google Map 應用入門 - Day04


Comments