1、编写一个Line Length应用程序 要求如下:在窗体上绘制一条黑色直线并计算他的长度,如图所示。该直线从按下鼠标按钮出的坐标开始,直到释放鼠标按钮的那点结束。应用程序应当在“Length = ”标签中显示直线的长度(即两个端点之间的距离)。
时间: 2024-03-07 19:47:47 浏览: 121
以下是使用Python和Tkinter库编写的Line Length应用程序代码,满足您的需求:
```
import tkinter as tk
import math
class LineLengthApp:
def __init__(self, master):
self.master = master
master.title("Line Length App")
self.start_x = None
self.start_y = None
self.end_x = None
self.end_y = None
self.canvas = tk.Canvas(master, width=400, height=400, bg="white")
self.canvas.pack()
self.canvas.bind("<Button-1>", self.on_click)
self.canvas.bind("<B1-Motion>", self.on_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_release)
self.length_label = tk.Label(master, text="Length = 0")
self.length_label.pack()
def on_click(self, event):
self.start_x = event.x
self.start_y = event.y
def on_drag(self, event):
self.canvas.delete("line")
self.end_x = event.x
self.end_y = event.y
self.canvas.create_line(self.start_x, self.start_y, self.end_x, self.end_y, width=2, tag="line")
def on_release(self, event):
self.canvas.delete("line")
self.end_x = event.x
self.end_y = event.y
length = math.sqrt((self.end_x - self.start_x)**2 + (self.end_y - self.start_y)**2)
self.length_label.config(text="Length = {:.2f}".format(length))
root = tk.Tk()
app = LineLengthApp(root)
root.mainloop()
```
运行该程序后,会在窗口上显示一个白色的画布,您可以在上面按下鼠标左键并拖动,画出一条直线,直到松开鼠标左键。程序会在窗口上方显示一条标签,标识出该直线的长度。
阅读全文