[Python] 24. GUI(Graphic User Interface) - tkinter

2023. 11. 8. 02:39·Programming Language/Python

GUI(Graphic User Interface) - tkinter


  • Tcl/Tk 툴킷을 사용하는데 필요한 인터페이스 모듈 (Std library)
import tkinter as tk

root = tk.Tk() # 실행했을 때 나타나는 창 root
label = tk.Label(root, text='Hello World') # root 창에 포함되는 컴포넌트로 label 생성
label.pack() # label 객체를 창에 표시

root.mainloop() # root 창을 event loop에 들어가게 하여 root 창이 종료되지 않고 일을 계속 수행
  • 블로그 프로그램을 만든다고 할 때 사용되는 tkinter component

    • ListBox : 블로그의 목록

    • Label : '제목'이라는 라벨 표시

    • Entry : 제목을 보여주고 입력

    • Text : 내용을 보여주고 입력

    • Button : 블로그 생성, 수정, 삭제

  • ListBox : 블로그의 목록처럼 정해진 순서가 있는 여러개의 데이터를 표시하는 컴포넌트

    from tkinter as tk
    
    root = tk.Tk()
    listbox = tk.Listbox(root)
    listbox.pack()
    
    for i in ['one', 'two', 'three', 'four']:
        listbox.insert(END, i) # 리스트 박스의 마지막 위치에 새로운 데이터 insert
    
    def event_for_listbox(event):
        print("Hello Event")
    
    listbox.bind('<<ListboxSelect>>', event_for_listbox) 
    # click eventbox --> event happen
    
    root.mainloop()
    • ListBox 메서드

      • insert(index, "항목")

        • index 위치에 항목 추가
      • delete(start_index, end_index)

        • start_index 부터 end_index 까지의 항목 삭제
      • size()

        • 항목 개수 반환
      • activate(index)

        • index 위치에 항목 선택
      • curselection()

        • 선택된 항목을 튜플로 반환
      • index(index)

        • index 에 대응하는 위치 획득
      • see(index)

        • index 가 보이도록 리스트 박스의 위치 조정
  • Entry

    • 텍스트를 입력하거나 보여주고자 사용하는 컴포넌트

    • 주로 한 줄로 구성된 문자열을 처리할 때 사용

    • 여러 줄의 문자열을 처리하려면 Text 컴포넌트를 사용한다.

    from tkinter import *
    
    root = Tk()
    entry = Entry(root)
    entry.pack()
    
    entry.insert(0, "Hello python")
    
    root.mainloop()
    • Entry Method

      • insert(index, "문자열")

        • index 위치에 문자열 추가
      • delete(start_index, end_index)

        • start_index부터 end_index까지의 문자열 삭제
      • get()

        • 기입창의 텍스트를 문자열로 반환
      • index(index)

        • index 에 대응하는 위치 획득
      • icursor(index)

        • ndex 앞에 키보드 커서 설정
      • select_adjust(index)

        • index 위치까지의 문자열을 블록처리
      • select_range(start_index, end_index)

        • start_index 부터 end_index 까지 블록처리
  • Text

    • 텍스트를 입력하거나 보여주고자 사용하는 컴포넌트

    • 여러줄을 처리할 때 사용

    from tkinter import *
    
    root = Tk()
    text = Text(root)
    text.pack()
    
    data = '''Life is too short
    You need python'''
    
    text.insert(1.0, data)
    
    root.mainloop()
    • insert 메서드의 첫 번째 매개변수를 보면 1.0이다

    • 소수점 기준 왼쪽은 행, 오른쪽은 열을 뜻한다.

    • 첫번째 행은 1부터 시작한다. (0부터 시작 X)

    • 텍스트에 입력한 내용을 삭제하려만 아래와 같이 하면 됨

      text.delete(1.0, END)
  • Button

    • 버튼을 클릭했을 때 특정 함수를 실행하고자 사용하는 컴포넌트

      from tkinter import *
      
      root = Tk()
      b1 = Button(root, text='테스트')
      b1.pack()
      
      def btn_click(event):
          print("버튼이 클릭되었습니다")
      
      b1.bind('<Button-1>', btn_click)
      
      root.mainloop()
    • 버튼을 클릭했을 때 btn_click() 함수가 실행되도록 이벤트 연결

      button_send = tk.Button(root, text='Send your message', command=handle_button_send)
    • command에 함수명을 입력해 event를 발생시킬 수 있다.

참조) https://wikidocs.net (파이썬 계단밟기)

'Programming Language > Python' 카테고리의 다른 글

[Python] 23. 정규 표현식(regular expression)  (0) 2023.11.07
[Python] 22. 표준 라이브러리(Standard Library)(2)  (0) 2023.11.07
[Python] 21. 표준 라이브러리(Standard Library)(1)  (0) 2023.11.07
[Python] 20. 내장 함수(Built-in-function)  (0) 2023.11.07
[Python] 19. 예외처리(Exception Handling)  (0) 2023.11.07
'Programming Language/Python' 카테고리의 다른 글
  • [Python] 23. 정규 표현식(regular expression)
  • [Python] 22. 표준 라이브러리(Standard Library)(2)
  • [Python] 21. 표준 라이브러리(Standard Library)(1)
  • [Python] 20. 내장 함수(Built-in-function)
lumana
lumana
배움을 나누는 공간 https://github.com/bebeis
  • lumana
    Brute force Study
    lumana
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Spring
        • MVC
        • DB
        • 핵심 원리
        • JPA
      • WEB
        • HTML
        • CSS
        • HTTP
        • Application
      • Computer Science
        • Network
        • Database
        • OS
        • 시스템 프로그래밍
        • 컴퓨터구조
      • Algorithm
        • Divide&Conquer
        • Sort
        • Greedy
        • DP
        • Backtracking
        • NP-Complete
        • Graph
      • Data Structure
        • 자료구조
        • C++ STL
        • Java Collection
      • 소프트웨어 공학
        • 시험 공부 정리
        • Theorem
      • Programming Language
        • Python
        • Java
        • C
        • C++
        • Rust
        • Theory
      • Unix_Linux
        • Common
      • React
      • PS
        • BOJ
        • Tip
        • 프로그래머스
        • CodeForce
      • Book Review
        • Clean Code
      • Math
        • Linear Algebra
      • AI
        • DL
        • ML
        • DA
        • Concepts
      • 우아한테크코스
        • 프리코스
      • Project Review
      • LegacyPosts
      • Android
      • Apple
        • Mac
        • IPhone
        • IPad
      • 모니터
      • Diary
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
lumana
[Python] 24. GUI(Graphic User Interface) - tkinter
상단으로

티스토리툴바