GUI(Graphical User Interface)는 프로그램을 더 쉽게 사용할 수 있도록 만들어준다. 이때 User가 더 쉽게 사용할 수 있도록, 화면, 텍스트 박스, 버튼 등을 생성할 수 있게 해주는 파이썬 라이브러리가 Tkinter이다.
1) from tkinter import * : 라이브러리 임포트
2) windoe.geometry("00x00") : 윈도우의 크기를 정의
3) window.mainloop() : 프로그램 계속 작동 코드 하단
#124
사용자의 이름을 입력하는 윈도우를 생성한다.
버튼을 클릭하면 'Hello' 메시지와 함께 이름이 표시되고 메시지의 폰트 색상과 배경색을 변경하라.
from tkinter import *
def click():
name = textbox1.get()
maessage = str("hello" + name)
textbox2['bg'] = 'yellow'
textbox2['fg'] = 'blue'
textbox2['text'] = Message
window = Tk() #윈도우 영역 생성, 타이틀 추가 윈도우 크기
window.geometry("500x200")
label = Label(text = '이름 입력:') #메세지 표시하는 텍스트 화면 추가 #
label.place(x=30, y=20) #윈도우에 표시될 객체의 위치 지정
textbox1 = Entry(text ='')
textbox1.place(x = 150, y = 20, width = 200, height = 25)
textbox1["justify"] = 'center'
textbox1.focus()
button1 = Button(text = 'Press me', command = click)
button1.place(x= 30, y = 50, width = 100, height = 25)
textbox2 = Message(text = '', width = 200)
textbox2.place(x = 150, y = 50, width = 200, height = 25)
textbox2['bg'] = 'white'
textbox2['fg'] = 'black'
window.mainloop()
#125
여섯 면의 주사위 대신 보드게임에서 사용할 수 있는 프로그램을 작성하자.
사용자가 버튼을 클릭하면 1에서 6(포함) 사이의 임의의 정수를 표시하라.
ver1.
from tkinter import *
import random
#주사위굴리기함수
def roll_dice():
number = random.randint(1, 6)
label.config(text=str(number))
#윈도우생성
window = Tk()
window.title("주사위 굴리기")
window.geometry("50x100")
#버튼생성
button1 = Button(text = 'Roll', command = click)
button1.place(x=30, y=30, width=50, heigh=25)
#위젯배치
answer = Message(text='')
answer.place(x=40, y=70, width=30, height=25)
#윈도우실행
window.mainloop()
ver2.
import tkinter as tk
import random
# 윈도우 생성
window = tk.Tk()
window.title("주사위 시뮬레이션")
# 레이블 생성
label = tk.Label(window, text="", font=("Helvetica", 48))
# 주사위 굴리기 함수
def roll_dice():
number = random.randint(1, 6)
label.config(text=str(number))
# 버튼 생성
button = tk.Button(window, text="주사위 굴리기", command=roll_dice)
# 위젯 배치
label.pack(pady=20)
button.pack()
# 윈도우 실행
window.mainloop()
#126
사용자가 숫자를 입력하도록 요청하는 프로그램을 생성한다.
사용자가 버튼을 클릭하면 입력한 숫자를 합계에 더하게 되며, 그 합이 화면에 출력된다.
이 과정을 사용자가 원하는 만큼 반복할 수 있으며, 합계에 계속 추가된다.
또한, 합계를 0으로 돌리고 표시했던 합계를 원래 상태로 비워 다시 시작할 준비를 하는 버튼도 있어야 한다.
from tkinter import *
def add_on():
num = enter_txt.get()
num = int(num)
answer = output_txt['text']
answer = int(answer)
total = num + answer
output_txt['text'] = total
def reset():
output_txt['text'] = 0
enter_txt.delete(0, END)
enter_txt.focus()
window = Tk()
window.title('Adding Togeter')
window.geometry("450x100")
enter_lbl = Label(text = "enter a number: ")
enter_lbl.place(x=50, y=20, width=100, height=25)
enter_txt = Entry(text = 0)
enter_txt.place(x=150, y=20, width=100, height=25)
enter_txt['justify'] = 'center'
enter_txt.focus()
add_btn = Button(text = 'Add', command = add_on)
add_btn.place(x=300, y=2, width=50, height=25)
output_lbl = Message(text=0)
output_lbl.place(x=150, y=50, width=100, height=25)
output_txt = Message(text=0)
output_txt.place(x=150, y=50, width=100, height=25)
output_txt['bg'] = 'white'
output_txt['relief'] = "sunken"
clear_btn = Button(text = 'clear', comman=reset)
clear_btn.place(x=300, y=50, width=50, height=25)
window.mainloop()
#127
텍스트 박스에 사용자 이름을 입력하도록 요청하는 윈도우를 생성한다.
입력한 이름을 목록 하단에 추가하는 버튼도 만든다. 또한, 목록의 내용을 지우는 버튼도 생성한다.
from tkinter import *
def add_name():
name = name_box.get()
name_list.insert(END, name)
name_box.delete(0, END)
name_box.focus()
def clear_list():
name_list.delete(0, END)
name_box.focus()
window = Tk()
window.title("Names List")
window.geometry("400x200")
label1 = Label(text = "enter a name: ")
label1.place(x=20, y=20, width=100, height=25)
name_box = Entry(text = 0)
name_box.place(x=120, y=20, width=100, height=25)
name_box.focus()
button1 = Button(text = 'Add to list', command = add_name)
button1.place(x=250, y=20, width=100, height=25)
name_list = Listbox()
name_list.place(x=120, y=50, width=100, heigh=100)
button2 = Button(text= 'Clear list', command= clear_list)
button2.place(x=250, y=50, width=100, height=25)
window.mainloop()
#128
1킬로미터는 0.6214마일이고 1마일은 1.6093킬로미터다.
이것을 이용하여 마일과 킬로미터를 변환하는 프로그램을 만들어라.
from tkinter import *
def convert1():
mile = textbox1.get()
mile = float(mile)
message = mile * 1.6093
textbox2.insert(END, message)
textbox2.insert(END, 'km')
def conver2():
km = textbox1.get()
km = float(km)
message = km * 0.6214
textbox2.delete(0, END)
textbox2.insert(END, message)
textbox2.insert(END, 'miles')
window = Tk()
window.title("Distance")
window.geometry("260x200")
label1 = Label(text = "Enter the valuse you want to convert: ")
label1.place(x=15, y=20)
textbox1 = Entry(text= '')
textbox1.place(x=30, y=50, width=200, heigh=25)
textbox1['justify'] = 'center'
textbox1.focus()
convert1 = Button(text = "convert miles to km", command = convert1)
convert1.place(x=30, y=80, width=200, heigh=25)
convert2 = Button(text = "convert miles to km", command = convert1)
convert2.place(x=30, y=110, width=200, heigh=25)
textbox2 = Entry(text = '')
textbox2.place(x=30, y=140, width=200, height=25)
textbox2['justify'] = 'center'
window.mainloop()
#129
텍스트 박스에 숫자를 입력하도록 요청하는 윈도우를 생성한다.
variable.isdigit() 코드를 사용하여 정수를 입력했는지 확인하는 버튼을 만든다.
만약 정수라면 목록에 추가하고, 그렇지 않다면 엔트리 박스의 내용을 지운다. 목록의 내용을 지우는 버튼도 추가한다.
from tkinter import *
def add_number():
num = num_box.get()
if num.isdigit():
num_list.insert(END, num)
num_box.delete(0, END)
num_box.focus()
else:
num_box.delete(0, END)
num_box.focus()
def clear_list():
num_list.delete(0, END)
num_box.focus()
window = Tk()
window.title('Number list')
window.geometry("400x200")
label1 = Label(text = "enter a number")
label1.place(x=20, y=20, width=100, height=25)
num_box = Entry(text = '')
num_box.place(x=120, y=20, width=100, height=25)
num_box.focus()
button1 = Button(text = 'add to list', command = add_number)
button1.place(x=250, y=20, width=100, height=25)
num_list = Listbox()
num_list.place(x=120, y=50, width=100, height=100)
button2 = Button(text = 'clear list', command = clear_list)
button2.place(x=250, y=50, width=100, height=25)
window.mainloop()
#130
129번 프로그램을 변경하여 목록의 내용을 csv 파일로 저장하는 세 번째 버튼을 추가하자.
tmp_list = num_list.get(0,END) 코드는 목록의 내용을 tmp_list 라는 이름의 변수에 튜플로 저장하기 위해 사용할 수 있다.
from tkinter import *
import csv
def add_number():
num = num_box.get()
if num.isdigit():
num_list.insert(END, num)
num_box.delete(0, END)
num_box.focus()
else:
num_box.delete(0, END)
num_box.focus()
def clear_list():
num_list.delete(0, END)
num_box.focus()
def save_list():
file = open("number.csv", 'w')
tem_list = num_list.get(0, END)
for x in tem_list:
newrecord = x + '\n'
file.write(str(newrecord))
file.close()
window = Tk()
window.title('Number list')
window.geometry("400x200")
label1 = Label(text = "enter a number")
label1.place(x=20, y=20, width=100, height=25)
num_box = Entry(text = '')
num_box.place(x=120, y=20, width=100, height=25)
num_box.focus()
button1 = Button(text = 'add to list', command = add_number)
button1.place(x=250, y=20, width=100, height=25)
num_list = Listbox()
num_list.place(x=120, y=50, width=100, height=100)
button2 = Button(text = 'clear list', command = clear_list)
button2.place(x=250, y=50, width=100, height=25)
button3 = Button(text = 'Save list', command = save_list)
button3.place(x=250, y=80, width=100, height=25)
window.mainloop()
#131
새로운 csv 파일을 생성하는 프로그램을 만든다.
이름과 나이를 입력하도록 요청하고 입력된 데이터를 방금 만든 파일에 추가하도록 한다.
from tkinter import *
import csv
def create_new():
file = open('ages.csv', 'w')
file.close()
def save_list():
file = open('ages.csv', 'a')
name = name_box.get()
age = age_box.get()
newrecord = name + "," + age + '\n'
file.write(str(newrecord))
file.close()
name_box.delete(0, END)
age_box.delete(0, END)
name_box.focus()
window = Tk()
window.title('People list')
window.geometry("400x100")
label1 = Label(text = "enter a name: ")
label1.place(x=20, y=20, width=100, height=25)
name_box = Entry(text = '')
name_box.place(x=120, y=20, width=100, height=25)
name_box['justify'] = 'left'
name_box.focus()
label2 = Label(text = "enter their age: ")
label2.place(x=20, y=20, width=100, height=25)
age_box = Entry(text='')
age_box.place(x=120, y=50, width=100, height=25)
age_box['justify'] = 'left'
button1 = Button(text = 'create new file', command = create_new)
button1.place(x=250, y=20, width=100, height=25)
button2 = Button(text = 'add to file', command = save_list)
button2.place(x=250, y=50, width=100, height=25)
window.mainloop()
#132
131번에서 만든 csv 파일을 사용하여 csv 파일의 내용을 가져와서 목록에 표시되도록
사람들의 이름과 나이를 목록에 추가하는 프로그램을 만들자.
from tkinter import *
import csv
def save_list():
file = open('ages.csv', 'a')
name = name_box.get()
age = age_box.get()
newrecord = name + ","+ age + '\n'
file.write(str(newrecord))
file.close()
name_box.delete(0, END)
age_box.delete(0, END)
name_box.focus()
def read_list():
name_list.delete(0, END)
file = list(csv.reader(open("ages.csv")))
tmp = []
for row in file:
tmp.append(row)
for data in tmp:
name_list.insert(END, data)
window = Tk()
window.title("People list")
window.geometry("400x200")
label1 = Label(text = "enter a name: ")
label1.place(x=20, y=20, width=100, height=25)
name_box = Entry(text = '')
name_box.place(x=120, y=20, width=100, height=25)
name_box['justify'] = 'left'
name_box.focus()
label2 = Label(text = "enter their age: ")
label2.place(x=20, y=20, width=100, height=25)
age_box = Entry(text='')
age_box.place(x=120, y=50, width=100, height=25)
age_box['justify'] = 'left'
button1 = Button(text = 'add to file', command = save_list)
button1.place(x=250, y=20, width=100, height=25)
button2 = Button(text = 'read list', command = read_list)
button2.place(x=250, y=50, width=100, height=25)
label3 = Label(text = "saved names: ")
label3.place(x=250, y=80, width=100, height=25)
name_list = Listbox()
name_list.place(x=120, y=80, width=230, height=100)
window.mainloop()
'Python challenge' 카테고리의 다른 글
[146] 시프트코드 (1) | 2023.10.05 |
---|---|
[139~145] SQLite (1) | 2023.10.03 |
Do you think that is possible? (0) | 2023.09.24 |
[118~123] 함수 (0) | 2023.09.24 |
[111~117] csv 파일 읽기와 쓰기 (0) | 2023.09.24 |