用python画一个椭圆,并保存坐标到txt文件,要有界面
时间: 2024-03-26 10:34:07 浏览: 158
好的,我可以帮你实现这个功能。首先,我们需要用到 Python 的 GUI 库 tkinter 来实现界面,然后使用 matplotlib 库来画椭圆,并将其坐标保存到 txt 文件中。
以下是完整的代码,你可以将其保存为一个 py 文件,然后运行即可:
```python
import tkinter as tk
from tkinter import messagebox
import matplotlib.pyplot as plt
def draw_ellipse(a, b):
# 构造椭圆的参数方程
t = plt.linspace(0, 2 * plt.pi, 100)
x = a * plt.cos(t)
y = b * plt.sin(t)
# 绘制椭圆
plt.plot(x, y)
plt.axis('equal')
plt.show()
def save_ellipse(a, b):
# 构造椭圆的参数方程
t = plt.linspace(0, 2 * plt.pi, 100)
x = a * plt.cos(t)
y = b * plt.sin(t)
# 保存椭圆坐标到 txt 文件中
with open('ellipse.txt', 'w') as f:
for i in range(len(x)):
f.write(str(round(x[i], 2)) + ',' + str(round(y[i], 2)) + '\n')
messagebox.showinfo(title='提示', message='坐标已保存到 ellipse.txt 文件中!')
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.a_label = tk.Label(self, text="长轴 a:")
self.a_label.pack()
self.a_entry = tk.Entry(self)
self.a_entry.pack()
self.b_label = tk.Label(self, text="短轴 b:")
self.b_label.pack()
self.b_entry = tk.Entry(self)
self.b_entry.pack()
self.draw_button = tk.Button(self, text="绘制椭圆", command=self.draw_ellipse)
self.draw_button.pack()
self.save_button = tk.Button(self, text="保存坐标", command=self.save_ellipse)
self.save_button.pack()
self.quit_button = tk.Button(self, text="退出", command=self.master.destroy)
self.quit_button.pack()
def draw_ellipse(self):
try:
a = float(self.a_entry.get())
b = float(self.b_entry.get())
draw_ellipse(a, b)
except ValueError:
messagebox.showerror(title='错误', message='请输入正确的数字!')
def save_ellipse(self):
try:
a = float(self.a_entry.get())
b = float(self.b_entry.get())
save_ellipse(a, b)
except ValueError:
messagebox.showerror(title='错误', message='请输入正确的数字!')
root = tk.Tk()
app = Application(master=root)
app.mainloop()
```
运行上面的代码后,会弹出一个窗口,输入椭圆的长轴和短轴,然后可以点击“绘制椭圆”按钮来绘制椭圆,点击“保存坐标”按钮来保存椭圆的坐标到 txt 文件中。如果输入的不是数字,会弹出错误提示框。
希望这个代码对你有所帮助!
阅读全文
相关推荐
















