非连续线用户绘制tkinter python

问题描述 投票:1回答:2

所以这里是一个程序的代码,用户可以点击一个点并绘制一个点,然后随后的点击将绘制所有附加到上一行的更多行。我如何编辑这个程序只是让用户按下按钮并且喜欢(xp1,yp1),然后拖动一些位置并在(xp2,yp2)处释放然后在(xp1,yp1)和(xp2)之间画一条线,yp2)。最后,它会让用户创建许多不同的行,然后最终能够通过按“c”清除画布屏幕。就像我知道最后一件事必须将某些功能绑定到“c”但我不知道它是什么。

from Tkinter import Canvas, Tk, mainloop
import Tkinter as tk

# Image dimensions
w,h = 640,480

# Create canvas
root = Tk()
canvas = Canvas(root, width = w, height = h, bg = 'white')
canvas.pack()

# Create poly line
class PolyLine(object):
    def __init__(x, canvas):
        x.canvas = canvas
        x.start_coords = None # first click
        x.end_coords = None # subsequent clicks
    def __call__(x, event):
        coords = event.x, event.y # coordinates of the click
        if not x.start_coords:
            x.start_coords = coords
            return
        x.end_coords = coords # last click
        x.canvas.create_line(x.start_coords[0], # first dot x
                                x.start_coords[1], # first dot y
                                x.end_coords[0], # next location x
                                x.end_coords[1]) # next location y
        x.start_coords = x.end_coords

canvas.bind("<Button-1>", PolyLine(canvas)) # left click is used
mainloop()

非常感谢您的参与!对此,我真的非常感激!

python tkinter draw tkinter-canvas
2个回答
1
投票
import tkinter as tk
from time import sleep

def getpoint1(event):
    global x, y
    x, y = event.x, event.y

def getpoint2(event):
    global x1, y1
    x1, y1 = event.x, event.y

def drawline(event):
    canvas.create_line(x, y, x1, y1)



root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

root.bind('q', getpoint1)
root.bind('w', getpoint2)
root.bind('<Button-1>', drawline)


root.mainloop()

这几乎是您在评论中要求的,但使用不同的键。


1
投票

对于绘图线部分,我使用全局列表变量来存储线点。如果列表为空,那么我将行起始点坐标存储在列表中。否则,我在起点和当前光标位置之间画线,然后重置列表。

对于清除部分,您需要将canvas.delete方法绑定到“c”键按下。

from Tkinter import Canvas, Tk

line = []

def on_click(event):
    global line
    if len(line) == 2:
        # starting point has been defined
        line.extend([event.x, event.y])
        canvas.create_line(*line)
        line = []   # reset variable
    else:
        # define line starting point
        line = [event.x, event.y]

def clear_canvas(event):
    canvas.delete('all')

root = Tk()
canvas = Canvas(root, bg='white')
canvas.pack()

canvas.bind("<Button-1>", on_click) 
root.bind("<Key-c>", clear_canvas)

root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.