如何在python中创建一个GUI以鼠标在直角轴(或网格)上绘制?



我想创建一个GUI,用户可以使用鼠标在网格(或笛卡尔轴)上绘制,并获得绘制的每个条或弧的初始点和最终点的坐标。

我开始学习python,我无法用我对Tkinter的基本知识创建这个程序。如果有人能帮助我,我会很感激的。

这段代码展示了如何使用Tkinter库在Python中创建图形用户界面(GUI)的示例,以便在笛卡尔轴(或网格)上使用鼠标进行绘制。

代码的主要思想是创建一个Tkinter窗口和一个Tkinter画布,并在画布上绘制笛卡尔轴(或网格)。然后,为画布建立一个鼠标事件处理程序,每当按下鼠标左键将鼠标移动到画布上时调用该处理程序。事件处理程序获取当前鼠标位置,并在画布上鼠标位置处绘制一个圆点。

import tkinter as tk
# Create a Tkinter window
window = tk.Tk()
# Create a Tkinter canvas
canvas = tk.Canvas(window, width=600, height=600, bg='white')
# Draw the cartesian axis (or grid) on the canvas
canvas.create_line(0, 300, 600, 300, width=2)  # x-axis
canvas.create_line(300, 0, 300, 600, width=2)  # y-axis
# Bind a mouse event to the canvas to draw with the mouse
def draw(event):
# Get the current mouse position
x, y = event.x, event.y
# Draw a dot on the canvas at the current mouse position
canvas.create_oval(x-3, y-3, x+3, y+3, fill='black')
# Bind the '<B1-Motion>' event to the canvas to call the 'draw()' function
canvas.bind('<B1-Motion>', draw)
# Pack the canvas and start the main loop
canvas.pack()
window.mainloop()

最新更新