Mayfly-nymph
 1 # -*- encoding:utf-8 -*-
 2 
 3 from tkinter import *
 4 
 5 Str = (\'~\',\'|\',\'&\',\'\',\'1\', \'2\', \'3\', \'+\', \'4\', \'5\', \'6\', \'-\', \'7\', \'8\', \'9\', \'*\', \'.\', \'0\', \'/\', \'=\')
 6 
 7 class Calculator:
 8     def __init__(self, master):
 9         self.master = master
10         self.Interface()
11     def ButtonClick(self,var):
12         # 获取文本框中的内容
13         textcontent = self.content.get()
14         # 判断点击消息,将textcontent设置为要计算的式子,并在文本框显示
15         if var.widget[\'text\'] in \'0123456789.+-*/&|~\':
16             textcontent += var.widget[\'text\']
17             self.content.set(textcontent)
18         # 使用eval计算textcontent,并在文本框显示
19         elif var.widget[\'text\'] == \'=\':
20             self.content.set(eval(textcontent))
21         # 清除文本框的内容
22         elif var.widget[\'text\'] == \'\':
23             textcontent = \'\'
24             self.content.set(textcontent)
25 
26     def Interface(self):
27         # 设置文本框显示的字符串
28         self.content = StringVar(self.master, \'\')
29         # 创建Entry组件
30         self.module = Entry(relief=SUNKEN, font=(\'Arial\',25), width=26,textvariable=self.content)
31         self.module.pack(side=TOP, pady=10)
32         # Grad布局
33         fra = Frame(self.master)
34         fra.pack(side=TOP)
35         # 创建Button组件
36         for i in range(len(Str)):
37             botton = Button(fra,text=Str[i], font=(\'Arial\',25),width=6)
38             botton.grid(row=i//4,column=i%4)
39             botton.bind(\'<Button-1>\',self.ButtonClick)
40 
41 if __name__ == \'__main__\':
42     root = Tk()
43     root.title(\'计算器\')
44     Calculator(root)
45     root.mainloop()

分类:

技术点:

相关文章: