Udemy 100 days of code
Day 27
Argument
Argument with default values
Play with tkinter
*arg : Many Positional Arguemnts
Unlimited Argument
def add(*args):
sum = 0
for n in args:
sum += n
return sum
예전에는
def add(n1, n2):
return n1+n2
이렇게 들어가야하는 숫자의 갯수를 정해주었다면 *args 를 사용하면 n1, n2, n3.... 무한대로 적용해서 더 폭 넓게 사용할 수 있다.
print(add(1,2,3,4,5))
의 답은 15
def number(*args):
return args
print(number(1,2,3,4,5))
= (1, 2, 3, 4, 5)
*args 를 사용할때 아무것도 하지 않고 그대로 리턴하면 tuple type으로 나온다.
**kwargs : Many Keyworded Arguments
def calculate(**kwargs):
print(kwargs)
calculate(add=3, multiply=5)
= {'add': 3, 'multiply': 5}
*args 가 tuple로 리턴되었다면 **kwargs는 dictionary로 리턴된다.
def calculate(n, **kwargs):
n += kwargs["add"]
n *= kwargs["multiply"]
print(n)
calculate(2, add=3, multiply=5)
= 25
class Car:
def __init__(self, **kwargs):
self.make = kwargs["make"]
self.model = kwargs["model"]
my_car = Car(make="Hyeondai", model="Genesis")
print(my_car.model)
= Genesis
class Car:
def __init__(self, **kwargs):
self.make = kwargs["make"]
self.model = kwargs["model"]
my_car = Car(make="Hyeondai")
print(my_car.model)
You get an error because you didn't specify model.
But,
If you use .get() instead of []
class Car:
def __init__(self, **kwargs):
self.make = kwargs.get("make")
self.model = kwargs.get("model")
my_car = Car(make="Hyeondai")
print(my_car.model)
= None
You get None instead of an error.
Quiz
def all_aboard(a, *args, **kw):
print(a, args, kw)
all_aboard(4, 7, 3, 0, x=10, y=64)
What is the output of the code above?
A : 4 (7, 3, 0) {'x': 10, 'y': 64}
from tkinter import *
#Creating a new window and configurations
window = Tk()
window.title("Widget Examples")
window.minsize(width=500, height=500)
#Labels
label = Label(text="This is old text")
label.config(text="This is new text")
label.pack()
#Buttons
def action():
print("Do something")
#calls action() when pressed
button = Button(text="Click Me", command=action)
button.pack()
#Entries
entry = Entry(width=30)
#Add some text to begin with
entry.insert(END, string="Some text to begin with.")
#Gets text in entry
print(entry.get())
entry.pack()
#Text
text = Text(height=5, width=30)
#Puts cursor in textbox.
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()
#Spinbox
def spinbox_used():
#gets the current value in spinbox.
print(spinbox.get())
spinbox = Spinbox(from_=0, to=10, width=5, command=spinbox_used)
spinbox.pack()
#Scale
#Called with current scale value.
def scale_used(value):
print(value)
scale = Scale(from_=0, to=100, command=scale_used)
scale.pack()
#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()
#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()
#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()
window.mainloop()
3 ways to display in tkinter
1. pack()
2. place(x= , y=)
3. grid (column= , row= )
pack - 순차적으로 표시해줌
place - 정확한 coorinate을 지정해서 둘 수 있다
grid - 마치 표처럼 그리드를 나눠서 둘 수 있다. 상대적인거라 하나 밖에 없다면 그리드를 행=3 열=3 이렇게 설정해도 왼쪽 상단에 뜸
# Label
my_label = tkinter.Label(text="I am a Label", font=("Arial", 24, "bold"))
my_label.pack()
my_label.grid(column=0, row=0)
## Here are 2 ways to change the text of a lebel
my_label["text"] = "New Text"
my_label.config(text="New Text")
# Button
def button_clicked():
print("I got clicked")
new_text = input.get()
my_label.config(text=new_text)
button = tkinter.Button(text="Click Me", command=button_clicked)
button.grid(column=1, row=1)
# Entry
input = tkinter.Entry(width=15)
input.grid(column=2, row=2)
print(input.get())
How to add padding to the window
window = tkinter.Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
window.config(padx=50, pady=50)
tkinter 갑자기 왜 배우는 건데....
넘나 혼란.. 그 잡채
turtle 같기도 하고
약간 예전에 http css 배울때 같기도 하고..?
'Udemy Python Notes' 카테고리의 다른 글
Day 30 Errors, Exceptions, and Json data (0) | 2022.12.05 |
---|---|
Day 29 - Password Manager (0) | 2022.12.05 |
Day 28 - Pomodoro Timer (0) | 2022.12.01 |
Day 27 - Mile to Kilometers Converter Project (0) | 2022.11.29 |
Day 26 (0) | 2022.11.28 |