ABOUT ME

-

Total
-
  • Python Tkinter 피보나치 수열, 소수 생성기 GUI
    컴퓨터/파이썬 2020. 9. 30. 22:37
    728x90
    반응형

    tkinter

    tkinter은 파이썬 내장 GUI 라이브러리이다.

     

    tkinter — Tcl/Tk 파이썬 인터페이스 — Python 3.8.6 문서

    tkinter — Tcl/Tk 파이썬 인터페이스 소스 코드: Lib/tkinter/__init__.py tkinter 패키지(《Tk 인터페이스》)는 Tk GUI 툴킷에 대한 표준 파이썬 인터페이스입니다. Tk와 tkinter는 대부분의 유닉스 플랫폼과 윈��

    docs.python.org

    결과 GUI

    # 2020-09-30 공부 일지

     

    1. 피보나치 생성 함수

    13을 입력했을 때

    원하는 숫자까지의 피보나치 수를 모두 저장한다. (less or equal)

    ex) n = 13이면, 0, 1, 1, 2, 3, 5, 8, 13을 보여줌

    (시간 복잡도 O(n) | 공간 복잡도 O(1))

    (하지만 tkinter 결과 출력하기 위해 보조 배열을 따로 만듦)

    (event=None은 bind를 했을 때와 버튼을 눌렀을 때 둘 다 작동하게 하기 위함)

    # Time O(n)
    def fib(event=None):
        n = number.get()  # str 타입
        if n == "":  # 입력안하면 오류 보여주고 종료
            messagebox.showerror("숫자를 입력하시오.", "양수 n을 입력하세요.\n시작은 1번째 = 0\n2번째 = 1")
            return
        fibo = [0, 1]
        result = []
    
        while fibo[0] <= int(n):
            nextFibo = fibo[0] + fibo[1]
            result.append(fibo[0])
            fibo[0] = fibo[1]
            fibo[1] = nextFibo
        messagebox.showinfo(f"피보나치 수열 (n <= {int(n)})", ", ".join(map(str, result)))
    

    입력 = None

     

    1-1 소수 생성기

    def primes(event=None):
        n = int(number.get())
        if n == "":
            messagebox.showerror("숫자를 입력하시오.", "양수 n을 입력하세요.")
            return
    
        result = []
    
        for possible in range(2, n + 1):
            isPrime = True
    
            for i in range(2, int(sqrt(possible)) + 1):
                if possible % i == 0:
                    isPrime = False
                    break
    
            if isPrime:
                result.append(possible)
    
        messagebox.showinfo(f"소수 (n <= {n})", ", ".join(map(str, result)))
        return result
    
    
    #2 에라토스테네스의 체
    def eratos(event=None):
        from math import sqrt
        n = int(number.get())
        if n == "":
            messagebox.showerror("숫자를 입력하시오.", "양수 n을 입력하세요.")
            return
    
        result = []
        sieve = [True] * (n + 1)
        for possible in range(2, sqrt(n) + 1):
            if sieve[possible]:
                for i in range(possible * possible, len(sieve), i):
                    sieve[i] = False
                    
        return [i for i in range(2, len(sieve)) if sieve[i] == True]

     

    2. 화면 가운데 띄우는 함수

    원하는 width x height 크기를 화면 정가운데 위치시킨다.

    def center_window(root, width=300, height=200):
        # 화면 높이, 너비 계산
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
    
        # 화면 중앙에 띄우기
        x = (screen_width / 2) - (width / 2)
        y = (screen_height / 2) - (height / 2)
        root.geometry("%dx%d+%d+%d" % (width, height, x, y))
    

     

    3. 메인 함수

    소수를 생성하려면 fib -> primes

    if __name__ == "__main__":
        main = Tk()
    
        # GUI 생성 500x200
        center_window(main, 500, 200)
        main.title("피보나치 수열 생성기")
    
        # 숫자 입력 Entry
        number = Entry(main, bd=3, text=1, justify="center")
        number.pack(side=RIGHT)
        main.bind("&lt;Return>", fib)  # Enter키 눌러도 피보나치 계산
    
        # Entry 옆 글
        text = Label(main, text="n <=")
        text.pack(side=RIGHT)
    
        # 생성 버튼 (수동)
        button = Button(main, text="결과 보기", command=fib)
        button.pack(anchor="s", expand=1, side=BOTTOM, fill=BOTH)
        main.mainloop()
    

     

    728x90

    '컴퓨터 > 파이썬' 카테고리의 다른 글

    Python random 모듈 구현하기  (0) 2020.10.14
    Python Fast inverse square root  (19) 2020.09.28
    Python 중국인의 나머지 정리  (1) 2020.09.25

    댓글