非连续线用户绘制tkinter python

2024-10-01 22:37:40 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个程序的代码,用户可以点击一个点,然后画出一个点,随后的点击会画出更多的线,所有的线都附着在前一行上。我该如何编辑这个程序,让用户按下按钮并有like(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()

非常感谢您抽出时间!我真的很感激!在


Tags: 用户import程序eventtkintercoordsstartend
2条回答

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

对于清除部分,您需要将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()
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()

这和你在评论中要求的差不多,但是有不同的键。在

相关问题 更多 >

    热门问题