챗GPT를 이용한 첫 Python 프로그램
이제 챗GPT도 준비되었고 Visual Studio Code를 이용한 Python도 준비가 되었다. 이제 무엇을 만들고 싶은가? 솔직히 Python 코딩은 할 줄 아는가? 사실 챗GPT를 이용하면 Python 잘 몰라도 된다. 챗GPT에게 원하는 프로그램을 잘 설명하기만 해도 멋진 프로그램을 만들 수 있다.
마음에 원하는 프로그램이 생각 났는가? 난 SimpleTextEditor를 만들어보겠다. 조건은 아래와 같다.
- 아래와 같이 챗GPT에 요청을 한다.
TextEditor를 만들건데 위에 메뉴가 있고 새파일, 저장하기, 다른이름으로 저장, 검색 메뉴가 있는 python으로 소스를 만들어줘
- 그러면 아래와 같이 답변이 온다. 처음이라 챗GPT의 답변을 스크린켑쳐로 보여줬으나 다음부터는 소스를 그냥 붙이도록 하겠다.
- 소스
import tkinter as tk
from tkinter import filedialog
def new_file():
text.delete(1.0, tk.END)
def save_file():
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
if file_path:
with open(file_path, "w") as file:
text_content = text.get(1.0, tk.END)
file.write(text_content)
def save_as():
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
if file_path:
with open(file_path, "w") as file:
text_content = text.get(1.0, tk.END)
file.write(text_content)
def search():
search_term = search_entry.get()
text_content = text.get(1.0, tk.END)
if search_term in text_content:
start_index = text_content.index(search_term)
end_index = f"{start_index}+{len(search_term)}c"
text.tag_remove("found", 1.0, tk.END)
text.tag_add("found", start_index, end_index)
text.tag_configure("found", background="yellow")
else:
print("Not found")
root = tk.Tk()
root.title("Text Editor")
menu_bar = tk.Menu(root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=new_file)
file_menu.add_command(label="Save", command=save_file)
file_menu.add_command(label="Save As", command=save_as)
menu_bar.add_cascade(label="File", menu=file_menu)
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Search", command=search)
menu_bar.add_cascade(label="Edit", menu=edit_menu)
root.config(menu=menu_bar)
text = tk.Text(root)
text.pack(expand=True, fill="both")
search_frame = tk.Frame(root)
search_frame.pack(side="bottom", fill="x")
search_label = tk.Label(search_frame, text="Search:")
search_label.pack(side="left")
search_entry = tk.Entry(search_frame)
search_entry.pack(side="left", expand=True, fill="x")
search_button = tk.Button(search_frame, text="Find", command=search)
search_button.pack(side="left")
root.mainloop()
- 위의 소스를 Visual Studio Code에 넣고 실행시키면 아래와 같이 보여진다.
간단하게 SimpleTextEditor를 챗GPT를 통해 작성해보았다. 이제 코딩을 모르는 사람도 아이디어만 있으면 코딩이 가능해졌다. 정말 놀라운 것은 Python으로 만든 이 SimpleTextEditor를 java 코드로 바로 변경이 가능한 것이고 개발자가 각 language를 몰라도 말이다. 참으로 무궁무진한 재미난 세계가 열렸다.