윈도우 프로그램 기본 위젯

강의노트 Button

강의노트 • 조회수 940 • 댓글 0 • 작성 1년 전 • 수정 1주 전  
  • 윈도우 프로그램

버튼

버튼이란 클릭 가능한 위젯이다. 사용자가 버튼을 클릭했을 때, 특정 동작(함수)을 실행하도록 연결할 수 있다.

GUI 프로그램에서 버튼은 사용자 입력을 처리하는 가장 중요한 위젯 중 하나이다.

기본 문법

버튼 = tk.Button(부모위젯, 옵션...)
버튼.pack()

주요 옵션으로는

옵션 설명
text 버튼에 표시할 글자
command 버튼을 클릭했을 때 실행할 함수
width, height 버튼의 크기
bg / fg 배경색 / 글자색
font 버튼 글자의 글꼴과 크기

기본 예제

버튼을 만들고 사용하는 방법을 예제들을 이용하여 알아본다.

  1. 버튼을 누르면 hello() 함수가 실행되고, 터미널에 "버튼이 눌렸습니다!"가 출력된다.
import tkinter as tk

def hello():
    print("버튼이 눌렸습니다!")

root = tk.Tk()
root.title("Button 기본 예제")

btn = tk.Button(root, text="클릭하세요", command=hello)
btn.pack(pady=20)

root.mainloop()
  1. 버튼을 아래 그림과 같이 생성한다.
from tkinter import *
def fun_quit(): #1
    win.destroy()
win = Tk() #2  
win.geometry('200x200') #3
but = Button(win, text='파이썬 종료', fg = 'red', command=fun_quit) #4
but.pack() #5
win.mainloop()
  1. 버튼에서 사용하는 명령을 함수로 만든다.

  2. 창을 만든다.

  3. 생성한 창의 크기는 '200x200'으로 한다.

  4. 버튼을 생성하고 텍스트는 '파이썬 종료'라고 쓰고 글자는 빨간색으로 명령어는 win.destroy(), 즉 생성된 창을 지운다.

  5. 생성한 버튼을 창에 붙인다.

  6. 여러 개의 버튼

btn1 = tk.Button(root, text="확인", command=lambda: print("확인 버튼"))
btn2 = tk.Button(root, text="취소", command=lambda: print("취소 버튼"))
btn1.pack()
btn2.pack()
  1. 버튼에 색상 / 크기 지정
btn3 = tk.Button(root, text="빨간 버튼", bg="red", fg="white", width=20, height=2)
btn3.pack()
  1. 버튼 비활성화
btn4 = tk.Button(root, text="비활성화", state="disabled")
btn4.pack()
  1. 이미지를 읽어서 버튼에 넣는다. 그리고 버튼을 누르면 아래와 같은 새로운 메세지 창이 뜬다.

from tkinter import *
from tkinter import messagebox
from PIL import ImageTk, Image

def fun():
    messagebox.showinfo('이미지 테스트','ㅎㅎㅎ')
win = Tk()
photo = Image.open('./../data/images/tiger.bmp')   #1
im = ImageTk.PhotoImage(photo)   #2
but = Button(win, image = im, command= fun)  #3
but.pack()
win.mainloop()
  1. 이미지를 읽어 온다.

  2. 이미지를 포토 이미지로 만든다.

  3. 이미지를 버튼에 넣고(image=im) 명령은 fun함수(메세지 박스를 보여준다)

  4. 두 개의 그림(클로버 1과 클로버 2)를 버튼을 누를때마다 바뀌는 프로그램을 만든다.

import tkinter as tk
count = 1
win = tk.Tk() 
win.geometry("400x300")  # Size of the window
bg = 'blue'         # change the day colour 
win.configure(background=bg) # default background of window
im1 = tk.PhotoImage(file = "./../data/images/clova_1.png")
im2 = tk.PhotoImage(file = "./../data/images/clova_2.png") 
def f_change():
    global count
    if(count % 2 == 0 ):
        b1.config(image=im1)
    else:
        b1.config(image=im2)
    count = count + 1
    
b1=tk.Button(win,image=im1,relief='flat',bg=bg,command=lambda:f_change())
b1.grid(row=1,column=1,padx=20,pady=10)
win.mainloop()  # Keep the window open
열 1 열 2
  1. 하나의 버튼에 여려개의 그림을 그리는 방법
import tkinter as tk
import random 
count = 0
img = []
win = tk.Tk() 
win.title('Card Select')
win.geometry("400x300")  
bg = 'blue'         
win.configure(background=bg) 
for i in range(1,14):
    s = f"./../data/images/clova_{i}.png"
    im = tk.PhotoImage(file = s)
    img.append(im)
    
def f_change():
    im = random.choice(img)
    b1.config(image=im)
    
b1=tk.Button(win,image=img[0],relief='flat',bg=bg,command=lambda:f_change())
b1.grid(row=1,column=1,padx=20,pady=10)
win.mainloop()  
열 1 열 2 열 3

버튼의 command 함수에 변수를 추가해서 넘기려면 lambda함수를 사용해야 한다.

연습문제

  1. 버튼을 하나 만들고 클릭할 때마다 "버튼을 눌렀습니다!"라는 메시지를 라벨(Label)에 출력한다.

정답 :

import tkinter as tk

def on_click():
    print("버튼이 눌렸습니다")

root = tk.Tk()
root.title("과제 1")

button = tk.Button(root, text="클릭하세요", command=on_click)
button.pack(pady=20)

root.mainloop()
  1. 버튼을 두 개 만들고, 하나는 배경색을 파란색, 다른 하나는 초록색으로 바꿀 수 있게 한다.

정답:

import tkinter as tk

def change_blue():
    root.config(bg="blue")
    label.config(text="파란색이 눌렸다")

def change_green():
    root.config(bg="green")
    label.config(text="초록색이 눌렸다")

root = tk.Tk()
root.title("과제 2")

label = tk.Label(root, text="여기에 메시지가 나타납니다.")
label.pack(pady=10)

btn1 = tk.Button(root, text="파랑", command=change_blue)
btn2 = tk.Button(root, text="초록", command=change_green)
btn1.pack(pady=10)
btn2.pack(pady=10)

root.mainloop()
  1. 버튼을 누를 때마다 카운트가 증가해서 "현재 카운트: n"이 표시되도록 만든다.

정답 :

import tkinter as tk

def change_count():
    num = count.get() 
    count.set(count.get() + 1)

root = tk.Tk()
root.title("과제 3")

count = tk.IntVar()
label = tk.Label(root, textvariable=count)
label.pack(pady=10)

button = tk.Button(root, text="카운트", command=change_count)
button.pack(pady=20)

root.mainloop()
  1. 버튼을 눌렀을 때 랜덤으로 "축하합니다!", "잘했어요!", "다시 해보세요!" 중 하나가 출력되도록 만든다.

정답 :

import tkinter as tk
import random

s = ["축하합니다.", "잘했어요!", "다시 해보세요!"]

def say_hello():
   text = random.choice(s)
   label.config(text=text)

root = tk.Tk()
root.title("과제 4")

label = tk.Label(root, text="여기에 메시지가 표시됩니다.")
label.pack(pady=10)

button = tk.Button(root, text="Hello", command=say_hello)
button.pack(pady=5)

root.mainloop()
이전 글
다음 글
댓글
댓글로 소통하세요.