我正在学习tkinter&使用Python 2.7的对象和从给定点(x0,y0)到通过鼠标单击(x1,y1)选择的点绘制线条。
我试图在某些条件下保持线的长度相等(参见代码),然后指向鼠标选择的方向。
代码,
from Tkinter import *
import numpy as np
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.can = Canvas(master, width=800, height=800)
self.can.configure(cursor="crosshair")
self.can.pack()
self.start_point = [400, 400]
self.end_point = [250, 400]
self.line = self.can.create_line(self.start_point, self.end_point)
self.can.bind("<Button-1>", self.line_end)
self.can.bind("<Button-3>", self.del_line)
def line_end(self, event):
r = 150
x0 = self.start_point[0]
y0 = self.start_point[1]
x1 = event.x
y1 = event.y
p = x1
q = y1
if x1 > x0 and y1 < y0:
theta = np.arctan((y1-y0)/(x1-x0))
p = int(x0 + r*np.cos(theta))
q = int(y0 + r*np.sin(theta))
print 'A'
if x1 < x0 and y1 < y0:
theta = np.arctan((y1-y0)/(x0-x1))
p = int(x0 + r*np.cos(theta))
q = int(y0 + r*np.sin(theta))
print 'S'
self.can.delete(self.line)
self.line = self.can.create_line(x0, y0, p, q)
print x0, y0, ' ........ ',x1, y1
def del_line(self, event):
self.can.delete(self.line)
root = Tk()
app = App(root)
root.mainloop()
如果确实存在满足条件的情况,则不会输入。我正确使用Pythons if 结构吗?
答案 0 :(得分:0)
好的解决方案是两次,
1)在新的Python控制台中打开和运行解决了条件块的非条目问题。我不明白为什么,但它有效。
2)将坐标转换为float然后再转换为int&amp;考虑到是stark说下面明显的不稳定行为停止了(愚蠢的弧度!),修改了下面的代码。
from Tkinter import *
import numpy as np
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.can = Canvas(master, width=800, height=800)
self.can.configure(cursor="crosshair")
self.can.pack()
self.start_point = [400, 400]
self.end_point = [250, 400]
self.line = self.can.create_line(self.start_point, self.end_point)
self.can.bind("<Button-1>", self.line_end)
self.can.bind("<Button-3>", self.del_line)
def line_end(self, event):
r = 150
x0 = float(self.start_point[0])
y0 = float(self.start_point[1])
x1 = float(event.x)
y1 = float(event.y)
p = int(x1)
q = int(y1)
if x1 > x0 and y1 < y0:
theta = np.arctan((y1-y0)/(x1-x0))
p = int(x0 + r*np.cos(theta))
q = int(y0 + r*np.sin(theta))
print 'A', p, q, theta
if x1 < x0 and y1 < y0:
theta = np.arctan((y1-y0)/(x0-x1))
p = int(x0 - r*np.cos(theta))
q = int(y0 + r*np.sin(theta))
print 'S', p, q, theta
self.can.delete(self.line)
self.line = self.can.create_line(x0, y0, p, q)
print x0, y0, ' ........ ',x1, y1
def del_line(self, event):
self.can.delete(self.line)
root = Tk()
app = App(root)
root.mainloop()