Python練習1--簡易圖形界面計算器


 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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM