Turtle Graphics Python for Computational Thinking Variable, Calculation, Selection & Loop [GUI 프로그래밍 ] 을 이용한 컴퓨팅사고력 File I/O, Recursion, Sort & Search Class, Object & GUI Programming Function & Data Type
형식 widget.pack( options ) 옵션 (Options) expand fill side 위젯이확장되어사용되지않는공간채우기 위젯이할당된추가공간을채우는지여부결정 ( 기본 = NONE) 값 : NONE, X( 가로채우기 ), Y( 세로채우기 ), BOTH 위젯을배치하고자하는위치 ( 기본 = TOP) 값 : TOP, BOTTOM, LEFT, RIGHT from tkinter import * lbl = Label(window, text= 연락처 ) lbl.pack() txt = Entry(window) txt.pack() btn = Button(window, text= OK ) btn.pack() # 객체 window 생성 # Label 위젯 # Pack() 메서드 # Entry 위젯 # Pack() 메서드 # Button 위젯 # Pack() 메서드 # 이벤트메시지루프
형식 widget.grid( option = value,...) 옵션 (Options) column 격자나누기를하고자하는열의번호 ( 기본 = 0) columnspan ipadx ipady padx pady 격자에서열의여러개의셀을하나의큰셀로병합 격자내부의왼쪽과오른쪽테두리안여백 격자내부의상단과하단테두리안여백 격자외부의왼쪽과오른쪽테두리바깥쪽여백 격자외부의상단과하단테두리바깥쪽여백 row 격자나누기를하고자하는행의번호 ( 기본 = 0) rowspan 격자에서행의여러개의셀을하나의큰셀로병합 ( 기본 = 1) sticky from tkinter import * 셀이위젯보다큰경우셀내부에위젯이배치될위치값 : N, E, S, W, NE, NW, SE, SW # 객체 window 생성 lbl = Label(window, text = 연락처 ) lbl.grid(row=0, column=0) txt = Entry(window) txt.grid(row=0, column=1) btn = Button(window, text= OK, width=15) btn.grid(row=1, column=1) # Label 위젯 # Grid 위젯 # Entry 위젯 # Grid 위젯 # Button 위젯 # Grid 위젯 # 이벤트메시지루프
형식 widget.place( option = value,...) 옵션 (Options) anchor bordermode height width relheight, relwidth relx, rely 위젯의정확한위치지정 ( 기본 = NW) 값 : N, E, S, W, NE, NW, SE, SW 경계선내부및외부참조 ( 기본 = INSIDE) 값 : INSIDE, OUTSIDE 높이 (pixels) 넓이 (pixels) 부모위젯의높이와넓이의일부로서높이와넓이값 : 0.0 1.0 부모위젯의높이와넓이의일부로서수평과수직오프셋값 : 0.0 1.0 x, y 수평및수직오프셋 (pixels) from tkinter import * # 객체 window 생성 btn = Button(window, text= Place() Method ) # Button 위젯 btn.pack() # Pack 메서드 btn.place(bordermode=outside, height=100, width=100) # 이벤트메시지루프
위젯 기능 위젯 기능 Button 단순한버튼 Scale 슬라이스바 Label 문자및이미지표시 Scrollbar 스크롤바 CheckButton 체크박스 RadioButton 옵션버튼 Entry 단순한한라인문자박스 Menu 풀다운및팝업메뉴 ListBox 리스트박스 Menubutton 메뉴버튼 Text Message Toplevel Frame LabelFrame PannedWindow Spinbox Canvas 멀티라인문자박스로서일부 Rich Text 기능제공 Label 과비슷하게문자표시. Label 과달리자동래핑기능 새윈도우를생성할때사용. Tk() 는윈도우를자동으로생성하지만추가로새윈도우혹은다이얼로그를만들경우사용 컨테이너위젯. 다른위젯들을그룹화할때사용 경계선과제목을가지는프레임위젯의변형 자식위젯을크기조절이가능한패널로관리하는컨테이너위젯 특정한범위에서값을선택하는 Entry 위젯의변형 그래프와점들로그림을그릴수있으며, 커스텀위젯을만드는데사용
# 객체 Root 생성 btn1 = Button(window, text= Button 1 ) # Button 위젯 btn2 = Button(window, text= Button 2 ) # Button 위젯 btn1.pack(side=left, padx=10) # Pack() 메서드 btn2.pack(side=left, padx=10) # Pack() 메서드 root.mainloop() # 이벤트메시지루프
형식 btn = Button(window, text= 버튼문자, command= 함수명 ) from tkinter import * from tkinter import messagebox # 버튼클릭이벤트핸들러 def okclick(): name = txt.get() messagebox.showinfo( 이름, name) lbl = Label(window, text= 이름 ) lbl.grid(row=0, column=0) txt = Entry(window) txt.grid(row=0, column=1) # 버튼클릭이벤트와핸들러정의 btn = Button(window, text= OK, command=okclick) btn.grid(row=1, column=1)
형식 Widget.bind(event, handler) from tkinter import * def onclick(event): print( 마우스클릭위치 :, event.x, event.y) frame = Frame(window, width=200, height=100) Shell # 왼쪽마우스바인딩 frame.bind( <Button-1>, onclick) frame.pack() 마우스클릭위치 : 93 159 마우스클릭위치 : 15 109 마우스클릭위치 : 81 156
이벤트명 설명 이벤트명 설명 <Button-1> 마우스왼쪽버튼클릭 <Double-Button-1> 마우스왼쪽버튼더블클릭 <Button-2> 마우스가운데버튼클릭 <Return> Enter 키누름 <Button-3> 마우스오른쪽버튼클릭 <Key> 임의의 Key 누름 <B1-Motion> 마우스왼쪽버튼을클릭한상태에서이동 <ButtonRelease-1> 마우스왼쪽버튼 released <B2-Motion> 마우스가운데버튼을클릭한상태에서이동 <Enter> 마우스포인터가위젯에위치 <B3-Motion> 마우스오른쪽버튼을클릭한상태에서이동 <Leave> 마우스포인터가위젯에서벗어날때 <FocusIn> 키보드초점이위젯으로이동하거나하위위젯으로이동 <FocusOut> 키보드초점이다른위젯으로이동 <Shift-Up> <Shift> 키를누른상태에서위쪽화살표버튼누를때 <Configure> 위젯의위치, 크기및플랫폼을변경할때
속성설명속성설명 char 키보드이벤트에서발생하는 하나의문자 x, y 위젯의좌상단으로부터의상대적마우스위치 (pixels) keysym 키보드이벤트에서발생하는 키의심볼명 x_root, y_root 화면좌상단으로부터의상대적마우스위치 (pixels) num 마우스이벤트의버튼번호 (1- 왼쪽, 2- 가운데, 3- 오른쪽 ) Key 이벤트가발생한위젯 keycode 키코드 width, height 위젯의새로운크기 (pixels) type 이벤트형식
def onclick(event): print( 키보드문자입력 :, event.char) frame = Frame(window, width=200, height=100) Shell # 왼쪽마우스바인딩 frame.bind( <Key>, onclick) frame.focus_set() frame.pack() 키보드문자입력 : s 키보드문자입력 : f 키보드문자입력 : e
btn1 = Button(window, text= Button 1 ) btn2 = Button(window, text= Button 2 ) btn1.pack(side=left, padx=10) btn2.pack(side=left, padx=10) btn1[ fg ] = red btn1[ bg ] = #00ff00 btn2_fg = colorchooser.askcolor()[1] btn2_bg = colorchooser.askcolor()[1] btn2[ fg ] = btn2_fg btn2[ bg ] = btn2_bg # 색상명을직접설정 # 색상명을 16진수로설정 # 색상대화상자호출 # 색상대화상자호출
형식 옵션 (options) (font name, font size, font style) family size weight slant 폰트의이름 포인트정수로표현되는폰트의높이값 일반체, 볼드 (bold) 체 이탤릭체 (italic), 로마체 (roman) underline 일반체 (0), 밑줄체 (1) overstrike 일반 (0), 겹치기 (1) from tkinter import * labelfont = ( times, 20, bold ) widget = Label(window, text= Hello~ Python Font ) widget.config(bg= black, fg= yellow ) widget.config(font=labelfont) widget.config(height=3, width=20) widget.pack(expand=yes, fill=both)
var = StringVar() label = Label(window, textvariable=var, relief=raised) var.set( Hey? How are you doing? ) label.pack()
window.title( 문자열과이미지함께보기 ) # 윈도우제목 # window.geometry( 700x300+10+10 ) # 윈도우해상도와위치 img = PhotoImage(file= python.png ) label1 = Label(window, image=img).pack(side= right ) contents = 컴퓨팅사고력은파이썬언어를사용하여이론과실습을학습함으로서매우빠르고효율적으로사고력을습득할수있다. label2 = Label(window, fg= blue, font= Times 20 bold italic, justi fy=left, padx=10, text=contents).pack(side= left )
nameentry = None addressentry = None name = None address = None # 전역변수 # 전역변수 # 전역변수 # 전역변수 def close_window() : name = nameentry.get() address = addressentry.get() window.destroy() def InputForm(window): Label(window, text= 성명 (Name) : ).grid(row=0, sticky=w) Label(window, text= 주소 (Address) : ).grid(row=1, sticky=w) nameentry = Entry(window) addressentry = Entry(window) nameentry.grid(row=0, column=1) addressentry.grid(row=1, column=1) Button(window, text= 확인 (OK), command=close_window).grid(row=2, column=0) Button(window, text= 취소 (Cancel), command=close_window).grid(row=2, column=1) InputForm(window)
text = Text(window, relief=sunken) text.insert(insert, Text 위젯은여기서시작하고,...\n ) text.insert(end,...\n...\n...\n여기서끝난다. ) text.pack() text.tag_add( what, 1.5, 1.7 ) # 태그명, 1번줄 5번인덱스에서 1번줄 7번인덱스까지선택 text.tag_config( what, background= red, foreground= y ellow )
canvas = Canvas(width=300, height=300, bg= white ) canvas.pack(expand=yes, fill=both) canvas.create_line(10, 10, 200, 50, width=10, fill= blue )
canvas = Canvas(width=300, height=300, bg= white ) canvas.pack(expand=yes, fill=both) canvas.create_oval(10, 10, 200, 200, width=2, fill= pink )
canvas = Canvas(width=300, height=200, bg= white ) canvas.pack(expand=yes, fill=both) canvas.create_arc(10, 50, 240, 210, start=0, extent=150, fill= red )
canvas = Canvas(width=300, height=300, bg= white ) canvas.pack(expand=yes, fill=both) canvas.create_rectangle(50, 50, 300, 200, width=3, fill= yel low )
canvas = Canvas(width=300, height=300, bg= white ) canvas.pack(expand=yes, fill=both) points = [100, 140, 110, 110, 140, 100, 110, 90, 100, 60, 90, 90, 60, 100, 90, 110] canvas.create_polygon(points, outline= #476042, fill= yellow, wid th=3)
canvas = Canvas(width=300, height=300, bg= white ) canvas.pack(expand=yes, fill=both) photo = PhotoImage(file= python.png ) canvas.create_image(0, 0, image=photo, anchor=nw)
canvas = Canvas(width=300, height=200, bg= white ) canvas.pack(expand=yes, fill=both) canvas.create_bitmap( 50, 50, bitmap= questhead ) canvas.create_bitmap(100, 50, bitmap= hourglass ) canvas.create_bitmap(150, 50, bitmap= question ) canvas.create_bitmap(200, 50, bitmap= warning )
canvas = Canvas(width=300, height=300, bg= white ) canvas.pack(expand=yes, fill=both) frame = Frame(canvas, relief=groove, borderwidth=2) Label(frame, text= Embedded Window ).pack() canvas.create_window(150, 50, window=frame, anchor=center)
def oncanvasclick(event): print( Canvas double click, event.x, event.y, event.widget) def onobjectclick(event): print( Text double click, event.x, event.y) canvas = Canvas(window, width=300, height=100, bg= white ) obj = canvas.create_text(150, 50, text= 마우스로여기를더블클릭해보세요. ) # canvas.bind( <Double-1>, oncanvasclick) canvas.tag_bind(obj, <Double-1>, onobjectclick) canvas.pack() Shell Text double click : 166 52
from tkinter import * canvas = Canvas(window, width=400, height=30 0) canvas.pack() x0 = 10 y0 = 50 x1 = 60 y1 = 100 deltax = 2 deltay = 3 canvas.create_oval(x0, y0, x1, y1, fill= red, tag = redball ) while True : canvas.move( redball, deltax, deltay) canvas.after(20) # 대기시간 (ms, milliseconds) canvas.update() # 화면을다시그린다. if x1 >= 400 : deltax = -2 if x0 < 0 : deltax = 2 if y1 > 300 : deltay = -3 if y0 < 0 : deltay = 3 x0 += deltax x1 += deltax y0 += deltay y1 += deltay
def move_left(event) : canvas.move( redball, -deltax, 0) canvas.after(20) canvas = Canvas(window, width = 400, height = 300) canvas.update() canvas.pack() x0 = 100 y0 = 150 x1 = 150 y1 = 200 deltax = 2 deltay = 3 canvas.create_oval(x0, y0, x1, y1, fill= red, tag= redball ) def move_right(event) : canvas.move( redball, deltax, 0) canvas.after(20) canvas.update() canvas.bind( <Left>, move_left) canvas.bind( <Right>, move_right) canvas.focus_set() canvas.pack()
def sel() : selection = 선택항목 : + str(var.get()) label_answer.config(text = selection) # 문제출력 label_question = Label(window, text= 1. 가장배우기쉬운프로그래밍언어는무엇인가요? ) label_question.pack() var = IntVar() # 정수형변수생성 Radiobutton(window, text= Python, variable=var, value=1, command=sel).pack(anchor=w) Radiobutton(window, text= Pascal, variable=var, value=2, command=sel).pack(anchor=w) Radiobutton(window, text= Scratch, variable=var, value=3, command=sel).pack(anchor=w) abel_answer = Label(window, text= ) # 선택된항목에대한값출력 label_answer.pack()
def sel() : if CheckVar1.get() == 1 and CheckVar2.get() == 0 : selection = 선택항목 : 1 label_answer.config(text = selection) elif CheckVar1.get() == 0 and CheckVar2.get() == 1 : selection = 선택항목 : 2 label_answer.config(text = selection) elif CheckVar1.get() == 1 and CheckVar2.get() == 1 : selection = 선택항목 : 1, 2 label_answer.config(text = selection) elif CheckVar1.get() == 0 and CheckVar2.get() == 0 : selection = 선택항목 : 없음. label_answer.config(text = selection)
label_question = Label(window, text= 1. 가장먹고싶은과일은무엇인가요? ) label_question.pack() CheckVar1 = IntVar() CheckVar2 = IntVar() Checkbutton(window, text= Apple, variable=checkvar1, onvalue=1, offvalue=0, height=2, width=20, command=sel).pack() Checkbutton(window, text= Peach, variable=checkvar2, onvalue=1, offvalue=0, height=2, width=20, command=sel).pack() # 선택된항목에대한값출력 label_answer = Label(window, text= 선택항목 : 없음. ) label_answer.pack()
from tkinter import * def donothing() : filewin = Toplevel(window) fileclose = Button(filewin, text= Do no thing button ) fileclose.config(command=window.quit) fileclose.pack() menubar = Menu(window) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label= File, com mand=donothing) filemenu.add_command(label= Open, com mand=donothing) filemenu.add_command(label= Save, com mand=donothing) filemenu.add_command(label= Close, mmand=donothing) filemenu.add_separator() co filemenu.add_command(label= Exit, command=donothing) menubar.add_cascade(label= File, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label= Copy, command=donothing) editmenu.add_command(label= Delete ) menubar.add_cascade(label= Edit, menu=editmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label= Help, command=donothing) helpmenu.add_command(label= About..., command=donothing) menubar.add_cascade(label= Help, menu=helpmenu) window.config(menu=menubar)
mbutton = Menubutton(window, text= 음식메뉴 ) picks = Menu(mbutton) mbutton.config(menu=picks) picks.add_command(label= 짜장면, command=window.quit) picks.add_command(label= 짬뽕밥, command=window.quit) picks.add_command(label= 뽂음밥, command=window.quit) mbutton.pack() mbutton.config(bg= white, bd=4, relief=raised)