gpt4 book ai didi

python - 非连续线用户绘制tkinter python

转载 作者:行者123 更新时间:2023-11-30 22:41:26 25 4
gpt4 key购买 nike

因此,这是一个程序的代码,用户可以单击一个点并绘制一个点,然后后续单击绘制更多的线,所有线都附加到前一行。我将如何编辑这个程序,让用户按下按钮并拥有类似(xp1,yp1)的内容,然后拖动一些位置并在(xp2,yp2)处释放,然后在(xp1,yp1)和(xp2)之间画一条线,yp2)。最后,它会让用户创建许多不同的线条,然后最终能够通过按“c”清除 Canvas 屏幕。就像我知道最后一件事必须将某个函数绑定(bind)到“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()

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

最佳答案

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

对于清除部分,您需要将canvas.delete方法绑定(bind)到“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()

关于python - 非连续线用户绘制tkinter python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42570280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com