[python] GUI programming tkInter (클릭 가능 위젯)
A A

목차

    728x90

     

    tkinter의 위젯을 모두 설명할 순 없지만, 정리해보자.

     

    각 위젯은 tkinter의 생성자에 의해 생성된다.

    생성자 호출지 첫번쨰 인수는 항상 마스터 위젯으로 새로이 생성된 객체를 소유한 위젯이다.

    widget_object = WidgetClass(master_object, option, ...)

    마스터 위젯의 대부분의 경우 기본창 또는 Frame, LabelFrame으로 사용된다.

    생성자는 위젯을 구성하는 인수들을 키워드형태로 받는다.

     

    앞서 보앗 듯, 모든 위젯은 클릭 가능한 위젯과, 클릭 불가능한 위젯으로 구성되어있다.


    • Button

    클릭 가능한 위젯으로 가장 많이 사용하는 Button의 경우로 가장 유용한 속성과 메서드를 살펴보자.

    버튼 속성(property) 속성 의미
    command 버튼을 클릭하면 콜백 호출되는 함수
    justify 내부 텍스트가 정렬되는 방식
    LEFT, CENTER, RIGHT
    state DISABELED : 버튼의 비활성화
    NORMAL : 정상적인 버튼 형태
    ACTIVE : 마우스가 버튼 위에 있을 때

     

    버튼 메서드(method) 메서드 역할
    flash() 버튼이 몇 번 깜빡이지만, 상태가 변경되지는 않는다.
    invoke() 위젯에 할당된 콜백을 활성화 하고, 콜백이 반환한 것 과 동일한 값을 반환한다.
    이벤트 관리자가 이 사실을 알고 있어야 하므로, 명시적으로 자신의 콜백을 호출하는 유일한 방법이다.
    import tkinter as tk
    
    def switch():
      if button1.cget('state') == tk.DISABLED:
        button1.config(state=tk.NORMAL)
        button1.flash()
      else:
        button1.flash()
        button1.config(state=tk.DISABLED)
    
    def mouseover(ev):
      button1['bg'] = 'green'
    
    def mouseout(ev):
      button1['bg'] = 'red'
    
    root = tk.Tk()
    root.title('버튼 속성과 메서드 알아보기')
    
    button1 = tk.Button(root, text="Enabled", b="red")
    button1.bind('<Enter>', mouseover)
    button1.bind('<Leave>', mouseout)
    button1.pack()
    
    button2 = tk.Button(root, text="Enabled/Disabled", command=switch)
    button2.pack()
    
    root.mainloop()

    • Checkbutton

    체크버튼의 속성과 메서드도 함께 살펴보자.

    체크버튼 속성(property) 속성 의미
    bd 체크 버튼의 프레임 너비 (default : 2px)
    command 상태가 변경될 때 호출되는 콜백 함수
    jsutify Button과 동일
    state Button과 동일
    variable IntVar 위젯의 상태를 반영하는 관찰 가능한 변수
    기본적으로 체크됨이 1, 체크되지 않음이 0
    offvalue 체크하지 않은 경우 variable 기본값이 아닌 값이 할당됨
    onvalue 체크시 variable 기본값이 아닌 값이 할당됨.
    체크 버튼 메서드(method) 메서드 역할
    deselect() 위젯의 체크를 해제
    flash() Button과 동일
    invoke() Button과 동일
    select() 위젯을 확인함
    toggle() 위젯을 토글한다 , 즉 상태를 반대 상태로 변경한다
    import tkinter as tk
    from tkinter import messageboc
    
    def count():
      global counter
      counter +=1
    
    def show():
      messagebox.showinfo("",f"counter = {str(counter)}, state = {str(switch.get())}")
    
    root = tk.Tk()
    switch = tk.IntVar()
    counter = 0
    button = tk.Button(root, text="Show", command=show)
    button.pack()
    
    checkbutton = tk.Checkbutton(root, text="Counter", variable=switch)
    checkbutton.pack()
    
    root.mainloop()
    import tkinter as tk
    from tkinter import messagebox
    
    def count():
      global counter
      counter +=1
    
    def show():
      messagebox.showinfo("",f"counter = {str(counter)}, state = {str(switch.get())}")
    
    root = tk.Tk()
    switch = tk.IntVar()
    counter = 0
    button = tk.Button(root, text="Show", command=show)
    button.pack()
    
    checkbutton = tk.Checkbutton(root, text="Tick", variable=switch, command=counter)
    checkbutton.pack()
    
    root.mainloop()

    • Radiobutton

    Radiobutton은 여러 위젯을 그룹화 할때 사용한다.

    그룹화 된 여러 위젯중 하나만 선택할 수 있으므로, 여러 사용자의 선택중 하나를 나타내는 데 유용한 도구이다.

    동일한 관찰 가능 변수를 여러 위젯에 할당하면 그룹이 생성된다.

    서로 다른 관찰 가능한 변수를 사용하는 경우 정의상 서로 다른 그룹에 속함을 의미한다.

    라디오 버튼 속성(property) 속성의 의미
    command 해당 그룹이 상태를 변경할 때 호출되는 콜백
    justify Button과 동일
    state Button과 동일
    variable 그룹내 현재 선택을 반영하는 관찰가능항목 변수
    value 그룹내의 고유값으로 식별하기 위함으로 사용.
    정수값 또는 문자열일 수 있고, 변수의 유형과 호환되어야 함

     

    라디오 버튼 메서드(method) 메서드 역할
    deselect() 위젯의 체크를 해제
    flash() Button과 동일
    invoke() Button과 동일
    select() 위젯을 확인한다.
    togggle()메서드는 없다.  
    import tkinter as tk
    from tkinter import messagebox
    
    def show():
      messagebox.showinfo("",f"radio1 : {str(radio1.get())}, radio2 : {str(radio2.get())}")
    
    def command_1():
      radio2_var.set(radio1_var.get())
    
    def command_2():
      radio1_var.set(radio2_var.get())
    
    root = tk.Tk()
    button = tk.Button(root text="Show", command=show)
    button.pack()
    
    radio1_var = tk.IntVar()
    radio1_1 = tk.Radiobutton(root, text="Pizza", variable=radio1_var, value=1, command=command_1)
    radio1_1.select()
    radio1_1.pack()
    radio1_2 = tk.Radiobutton(root, text="Pasta", variable=radio1_var, value=2, command=command_1)
    radio1_2.pack()
    
    radio2_var = tk.IntVar()
    radio2_1 = tk.Radiobutton(root, text="FR", variable=radio2_var, value=2, command=command_2)
    radio2_1.pack()
    radio2_2 = tk.Radiobutton(root, text="UK", variable=radio2_var, value=1, command=command_2)
    radio2_2.select()
    radio2_2.pack()
    
    root.mainloop()

    해당 코드를 실행하면 Pizza와 UK 가 함께 움직이는 것과 같고, Pasta와 FR 같이 움직이는 것을 볼 수 있다.

    radio2_var 의 값이 command_2를 콜백하면서 , radio1_var의 값을 변화하고 있기 때문에 함께 움직이는 것 처럼 확인할 수 있다.

    그룹이 가지는 연결성과, 콜백함수에 대해 이해하기 좋았던 예제였다.


    • Entry
    entry_object = tk_object.Enrty(master_object, option, ...)

    Entry 위젯은 텍스트의 줄을 표시할 뿐 아니라 사용자의 동작에 따라 텍스트를 편집할 수 있다.

    사용자에게 텍스트 정보를 요청해야할 때 사용한다.

    해당 위젯은 삽입, 삭제, 스크롤, 선택, 복사 및 붙여넣기 모든 표준 작업을 구현한다.

     

    위젯의 전체 기능은 매우 복잡하기 때문에 , 기본적인 기능만 보도록하자.

    Entry 속성(property) 속성의 의미
    command 클릭 가능한 위젯이지만, command 속성을 통해 콜백을 바인딩할 수 없다.
    대신 관찰 가능 변수에 추적 함수를 설정하여 발생하는  모든 변경 사항을 관찰하고 제어할 수 있다.
    추적함수는 이후 보도록 하자.
    show 입력 필드에 입력된 실제 문자 대신 표시한다.
    예를 들어 show="*"를 설정할 경우 사용자의 비밀번호를 안전하게 편집할 수 있다.
    state Button과 동일하다
    textvariable StringVar 입력 필드의 현재 상태를 반영하는 관찰 가능 객체
    width 입력 필드의 너비
    Entry 메서드(method) 메서드 역할
    get() 현재 입력 필드의 내용을 문자열로 반환한다.
    set(s) s 는 문자열로 전체 입력 필드의 내용을 설정한다
    delete(first, last=None) 입력 필드의 내용을 일부 삭제한다.
    문자열의 인덱싱을 하는 값은 정수이다.
    'last' 인수가 생략되면 단일 문자가 삭제 된다.
    'last'이 'end'으로 지정된 경우 마지막 필드의 문자 뒤에 있는 위치를 가리킨다.
    insert(index, s) index 의 위치에 s 를 삽입한다
    import tkinter as tk
    
    def digits_only(*args):
      global last_string
      string = text.get()
      if string =='' or string.isdigit():
        last_string = string
      else:
        text.set(last_string)
    
    last_string = ''
    root = tk.Tk()
    text = tk.StringVar()
    
    entry = tk.Entry(root, textvariable=text)
    text.set(last_string)
    text.trace("w", digits_only)
    
    entry.pack()
    entry.focus_set()
    
    root.mainloop()

    trace 추적 콜백 함수와 관찰가능 변수(observable variable)를 통해 숫자만 입력하도록 항제하고 다른 문자는 무시한다.

    입력필드가 달라질때마다 콜백함수를 호출하여, last_string을 통해 상태를 기억하고 유지하거나 업데이트한다.

    위젯 자체가 포커스를 받지 않으므로, focus_set()을 사용하여 포커스를 받도록 한다.

     

     

     

     

     

     

     

     

    Copyright 2024. GRAVITY all rights reserved