Python解二次方程
不废话,上源码{:10_279:} 。from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Calculator for solving quadratic equations")
frame = Frame(root, width=root.winfo_screenwidth(), height=10)
frame.grid(row=1, column=0, columnspan=7)
for i in range(1, 4):
exec(f"""def check{i}():
try:
float(e{i}.get())
except ValueError:
return False
else:
return True
def delete{i}():
e{i}.delete(0, END)
e{i} = Entry(root, validate="focus", validatecommand=check{i}, invalidcommand=delete{i})""")
output = Entry(root)
def all_grid():
Label(root, text="The solution to ").grid(row=0, column=0)
e1.grid(row=0, column=1)
Label(root, text="x2+").grid(row=0, column=2)
e2.grid(row=0, column=3)
Label(root, text="x+").grid(row=0, column=4)
e3.grid(row=0, column=5)
Label(root, text="=0 is:").grid(row=0, column=6)
output.grid(row=0, column=7)
Button(frame, text="Start solution equation!", command=solution).grid(row=0, column=4)
def get_input():
return
def format_complex(num):
if isinstance(num, complex):
if num.imag > 0:
return f"{num.real}+{num.imag}i"
elif num.imag < 0:
return f"{num.real}-{-num.imag}i"
else:
return str(num.real)
else:
return str(num)
def solution_equation(a, b, c):
if a != 0:
delta = b ** 2 - 4 * a * c #计算△
if delta < 0:
d = abs(delta) ** (1/2) * 1j
else:
d = delta ** (1/2)
x = (-b + d) / (2 * a)
y = (-b - d) / (2 * a)
output.delete(0, END)
output.insert(0, format_complex(x))
if x != y:
output.insert(END, " ".join(["", "and", format_complex(y)]))
elif b != 0:
x = (0 - c) / b
output.delete(0, END)
output.insert(0, str(x))
else:
if c == 0:
messagebox.showwarning("Calculator for solving quadratic equations", "There are an infinite number of solutions to this equation")
else:
messagebox.showerror("Calculator for solving quadratic equations", "There is no solution to this equation")
def solution():
inputs = get_input()
solution_equation(inputs, inputs, inputs)
def main():
all_grid()
mainloop()
if __name__ == "__main__":
main()
代码存在BUG:
如果用户进入程序之后,直接点开始计算,
将会报错ValueError
请手动将以下内容替换solution函数:
......
def solution():
try:
inputs = get_input()
except ValueError:
pass
else:
solution_equation(inputs)
...... 看看
没必要这么国际化吧… 请问mainloop是在tkinter库里有的吗?(只是询问) 歌者文明清理员 发表于 2023-4-2 20:34
请问mainloop是在tkinter库里有的吗?(只是询问)
啊对对对 KeyError 发表于 2023-4-2 20:35
啊对对对
所以和root.mainloop一样咯? 歌者文明清理员 发表于 2023-4-2 20:35
所以和root.mainloop一样咯?
啊对对对 KeyError 发表于 2023-4-2 20:35
啊对对对
知道了 哦? KeyError 发表于 2023-4-2 20:43
代码存在BUG:
如果用户进入程序之后,直接点开始计算,
将会报错ValueError
ok KeyError 发表于 2023-4-2 20:43
代码存在BUG:
如果用户进入程序之后,直接点开始计算,
将会报错ValueError
可以置顶你这个帖子
如图所示:https://t4.wodetu.cn/2023/04/02/514c592c80c296364053a7c1f7af658a.jpg 鱼币 @一点沙 @liuhongrun2022 @wyhpylc 鱼币鱼币 鱼币 鱼币 看看 {:10_277:} 看看 dd