Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

tkinter를 사용하여 두 번의 마우스 클릭 사이에 선 그리기

<시간/>

마우스 버튼으로 창을 클릭하면 좌표를 저장하고 주어진 두 점 사이에 선을 생성하는 GUI 응용 프로그램을 만드는 경우를 생각해 보십시오. Tkinter는 사용자가 키나 버튼을 기능과 바인딩할 수 있는 이벤트를 제공합니다.

두 점 사이에 선을 그리려면 다음과 같은 일반적인 단계를 따르십시오.

  • 캔버스 위젯을 만들고 압축하여 창에 표시합니다.

  • draw_line() 함수 정의 사용자가 클릭 이벤트를 할 때 이벤트로 작동합니다.

  • 캔버스의 클릭 수를 계산하는 전역 변수를 만듭니다.

  • 개수가 2가 되면 첫 번째 좌표와 두 번째 좌표 사이에 선을 그립니다.

  • 함수를 완전히 제어하려면 마우스 버튼을 콜백 함수와 결합하십시오.

예시

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Define a function to draw the line between two points
def draw_line(event):
   global click_num
   global x1,y1
   if click_num==0:
      x1=event.x
      y1=event.y
      click_num=1
   else:
      x2=event.x
      y2=event.y
   # Draw the line in the given co-ordinates
   canvas.create_line(x1,y1,x2,y2, fill="green", width=10)

# Create a canvas widget
canvas=Canvas(win, width=700, height=350, background="white")
canvas.grid(row=0, column=0)
canvas.bind('<Button-1>', draw_line)
click_num=0

win.mainloop()

출력

위의 코드를 실행하여 창을 표시합니다. 캔버스 위젯을 아무 곳이나 두 번 클릭하면 캔버스에 선이 그려집니다.

tkinter를 사용하여 두 번의 마우스 클릭 사이에 선 그리기