from tkinter import * from tkinter.messagebox import * # 系统弹窗消息 class Calculator: def __init__(self): # 构造函数,初始化GUI界面 # 先创建一个窗体 --self.frame self.frame = Tk() # 添加一个按钮 self.Button_call = Button(self.frame, text="计算", command=self.get_result) self.Button_call.place(x=500, y=50) # 为窗体增加标题 self.frame.title("计算圆的周长和面积") # 指定窗体大小 根据像素 self.frame.geometry("800x650+450+300") # 不允许改变窗体大小 self.frame.resizable(0, 0) # 为窗体指定背景 self.frame["bg"] = "lightgray" # 添加一个Label 标签 self.Label_input = Label(self.frame, text="请输入圆的半径:", background="lightgray", foreground="blue", font=("微软雅黑", 12, "bold")) self.Label_input.place(x=50, y=50) # 添加输入的文本框 self.var_radius = StringVar() self.Entry_input = Entry(self.frame, textvariable=self.var_radius, font=("微软雅黑", 12, "bold"), width=30) self.Entry_input.place(x=180, y=50) # 添加圆的周长Label self.Label_perimeter = Label(self.frame, text="圆的周长:", background="lightgray", foreground="blue", font=("微软雅黑", 12, "bold")) self.Label_perimeter.place(x=100, y=110) self.var_perimeter = StringVar() self.Label_perimeter_result = Label(self.frame, textvariable=self.var_perimeter, text="圆的周长的结果", background="lightgray", foreground="blue", font=("微软雅黑", 12, "bold")) self.Label_perimeter_result.place(x=200, y=110) # 添加圆的面积 Label self.Label_area = Label(self.frame, text="圆的面积:", background="lightgray", foreground="blue", font=("微软雅黑", 12, "bold")) self.Label_area.place(x=100, y=150) self.var_area = StringVar() self.Label_area_result = Label(self.frame, textvariable=self.var_area, text="圆的面积的结果", background="lightgray", foreground="blue", font=("微软雅黑", 12, "bold")) self.Label_area_result.place(x=200, y=150) def check_input(self, radius: str): """ 判断一个字符是否为数字 :param radius: 要判断的字符串 :return:是数字,返回ture ; """ if radius.replace(".", "").isdigit(): return True # 计算元的周长和面积 # circle_perimeter = 2 * PI * radius # circle_area = PI * radius * radius else: return False def get_perimeter(self, radius: float): """ 获取圆的周长 :param radius: :return: """ PI = 3.1415926 circle_perimeter = 2 * PI * radius return circle_perimeter def get_area(self, radius: float): """ 获取圆的面积 :param radius: :return: """ PI = 3.1415926 circle_area = PI * radius * radius return circle_area # 获取计算的结果 def get_result(self): print("点击了计算按钮") # showinfo("系统消息", "") # 获得文本框输入的半径 radius = self.var_radius.get() # 验证半径 if self.check_input(radius): # showinfo("系统消息", "半径 符合要求") circle_perimeter = self.get_perimeter(float(radius)) circle_area = self.get_area(float(radius)) # 赋值 self.var_perimeter.set("%.2f" % circle_perimeter) self.var_area.set("%.2f" % circle_area) else: showinfo("系统消息", "半径 不符合要求") # 显示窗口 def show_a(self): self.frame.mainloop() if __name__ == "__main__": # 根据类实例化一个对象 this_gui = Calculator() # 展示窗体 this_gui.show_a() 输出结果:
学习心得:
1.先创建窗体 self.frame = Tk()
2. 创建一个Label标签(提示语)Label()
3.接着创建 Label 标签后面的文本提示框 Stringvar() / Entry()
4. 创建一个按钮Button() ,并将按钮绑定到一个处理函数
5.输出: 最后需要显示窗口 self.frame.mainloop()