Python Tkinter 三角形面积计算器

 设计 GUI 图形化的面积计算器, 请用户输入三条边长,
判断是否能成为三角形,并求出三角形的面积。

设三角形ABC 边分别为a、b、c,三角形ABC的面积为S,则

S=1/4 sqrt[(a+b+c)(a+b-c)(a+c-b)(b+c-a)]

p=周长的一半。S=根号下p(p-a)(p-b)(p-c)

 

from tkinter import *
from math import sqrt

# 设计 GUI 图形化的面积计算器, 请用户输入三条边长,
# 判断是否能成为三角形,并求出三角形的面积。


class Calculator: # 类 Calculator
    def __init__(self): # 构造函数,实例化对象时自动执行这个函数

        window = Tk() # 新建一个Tkinter的窗体window
        window.title("-----Triangle Area Calculator-----") # 窗体标题

        # Add a tool bar frame
        frame0 = Frame(window) # Frame是一种容器 Create and add a frame to window
        frame0.grid(row = 1, column = 1, sticky = W) # 把frame0放到window的1行1列位置;参见 https://www.cnblogs.com/emanlee/p/15340537.html
        # Add labels and entries to frame1
        frame1 = Frame ( window )
        frame1.grid ( row = 2, column = 1, pady = 10 ) # 把frame1放到window的2行1列位置; https://www.cnblogs.com/emanlee/p/17302221.html
        Label ( frame1, text = "side a:" ).pack ( side = LEFT ) # Label 的文本为 "Number 1:",放置到左边  https://www.cnblogs.com/emanlee/p/15340485.html
        self.v1 = StringVar ( value = '0' ) # https://www.cnblogs.com/emanlee/p/16090048.html
        Entry(frame1, width = 5, textvariable = self.v1, justify = RIGHT).pack(side=LEFT)
        Label ( frame1, text = "side b:" ).pack(side = LEFT )
        self.v2 = StringVar ( value = '0' )
        Entry(frame1,width = 5, textvariable = self.v2, justify = RIGHT).pack(side=LEFT)

        Label ( frame1, text = "side c:" ).pack(side = LEFT )
        self.v3 = StringVar ( value = '0' )
        Entry(frame1,width = 5, textvariable = self.v3, justify = RIGHT).pack(side=LEFT)

        Label ( frame1, text = "Area:" ).pack(side = LEFT )
        self.v4 = StringVar ( value = '0' )
        Entry(frame1,width = 5, textvariable = self.v4, justify = RIGHT ).pack(side=LEFT)

        # Add buttons to frame2
        frame2 = Frame(window) # Create and add a frame to window
        frame2.grid(row = 3, column = 1, pady = 10, sticky = E )

        Button(frame2, text = "Calculate", command = self.subtract ).pack( side = LEFT )
        mainloop()


    def subtract(self):
        number1 = eval ( self.v1.get() )
        number2 = eval ( self.v2.get() )
        number3 = eval ( self.v3.get() )

        if number1+number2<= number3 or number1+number3<= number2 or number3+number2<= number1:
            self.v4.set ("Error")
        else:
            p=(number1+number2+number3)/2
            self.v4.set (  sqrt(p *(p-number1)*(p-number2)*(p-number3))  )

Calculator() # Create GUI 实例化对象

 

 

 

posted @ 2023-04-10 12:27  emanlee  阅读(976)  评论(0编辑  收藏  举报