文本框输入a,b,c的值,输出一元二次方程的解。
时间: 2024-06-13 19:08:44 浏览: 70
以下是Python实现一元二次方程求解的代码,其中使用了tkinter库实现了一个简单的窗口界面,用户可以在文本框中输入方程的各项系数,点击按钮后在文本区中显示方程的两个根(如果有的话):
```python
import tkinter as tk
import math
class QuadraticEquation:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def getDiscriminant(self):
return self.b * self.b - 4 * self.a * self.c
def getRoot1(self):
if self.getDiscriminant() < 0:
return None
else:
return (-self.b + math.sqrt(self.getDiscriminant())) / (2 * self.a)
def getRoot2(self):
if self.getDiscriminant() < 0:
return None
else:
return (-self.b - math.sqrt(self.getDiscriminant())) / (2 * self.a)
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)
self.a_label["text"] = "a:"
self.a_label.pack(side="left")
self.a_entry = tk.Entry(self)
self.a_entry.pack(side="left")
self.b_label = tk.Label(self)
self.b_label["text"] = "b:"
self.b_label.pack(side="left")
self.b_entry = tk.Entry(self)
self.b_entry.pack(side="left")
self.c_label = tk.Label(self)
self.c_label["text"] = "c:"
self.c_label.pack(side="left")
self.c_entry = tk.Entry(self)
self.c_entry.pack(side="left")
self.calculate_button = tk.Button(self)
self.calculate_button["text"] = "Calculate"
self.calculate_button["command"] = self.calculate
self.calculate_button.pack(side="left")
self.quit_button = tk.Button(self, text="Quit", command=self.master.destroy)
self.quit_button.pack(side="left")
self.result_text = tk.Text(self)
self.result_text.pack()
def calculate(self):
a = float(self.a_entry.get())
b = float(self.b_entry.get())
c = float(self.c_entry.get())
equation = QuadraticEquation(a, b, c)
root1 = equation.getRoot1()
root2 = equation.getRoot2()
if root1 is None and root2 is None:
self.result_text.delete("1.0", tk.END)
self.result_text.insert(tk.END, "No real roots")
elif root1 is None:
self.result_text.delete("1.0", tk.END)
self.result_text.insert(tk.END, "The equation has one root: " + str(root2))
elif root2 is None:
self.result_text.delete("1.0", tk.END)
self.result_text.insert(tk.END, "The equation has one root: " + str(root1))
else:
self.result_text.delete("1.0", tk.END)
self.result_text.insert(tk.END, "The roots are " + str(root1) + " and " + str(root2))
root = tk.Tk()
app = Application(master=root)
app.mainloop()
```
阅读全文