如何在 Tkinter Python 的點選事件上在 Canvas 上繪製一個點?
考慮一個這樣的情況,建立這樣一個 GUI 應用程式:當我們用滑鼠按鈕單擊視窗時,它會儲存座標並繪製一個點。Tkinter 提供允許使用者將鍵或按鈕與函式繫結的事件。
若要在單擊事件上繪製一個點,我們可以遵循以下一般步驟:
建立一個 Canvas 小部件並將其打包以在視窗中顯示。
定義一個在使用者執行單擊事件時作為事件來工作的函式 **draw_dot()**。
建立一個全域性變數,該變數記數Canvas 中的單擊次數。
如果計數變為二,則在第一個和第二個座標之間繪製一條線。
將滑鼠按鈕與回撥函式繫結,以完全控制函式。
示例
# 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):
x1=event.x
y1=event.y
x2=event.x
y2=event.y
# Draw an oval in the given co-ordinates
canvas.create_oval(x1,y1,x2,y2,fill="black", width=20)
# 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()輸出
執行以上程式碼以顯示一個視窗。當你在畫布內的任何位置單擊時,它將在該點繪製一個點。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP