aiaiask.com©

开花即结果 提问即答案

请使用python tkinter库,写一段计算器代码
原始问题:

请使用python tkinter库,写一段计算器代码

from tkinter import * # 导入tkinter库

root = Tk() # 创建一个窗口对象的实例
root.title("计算器") # 给窗口的标题命名
root.geometry('300x400') # 设定窗口大小

这里是用来创建功能按钮,比如+ - * / = 等等,我们将它们放在4行4列的表格中。

btn_list = [

'7', '8', '9', '/',   # 这里是1行, 4个功能按钮(注意这里最后要加一个逗号)
'4', '5', '6', '*',   # 2行, 4个功能按钮(注意这里最后要加一个逗号)
'1', '2', '3', '-',   # 3行, 4个功能按钮(注意这里最后要加一个逗号)                                                                 0','.','=','+' ]# 4行, 4个功能按钮  (注意这里不用再再多写逗号了

    # 在这释义一下btn_list[0]的意思是 btn_list数组中的第0位元素也就是7。btn_list[1]代表8依此类推...

    r = 1  # 表格的行数。我们将他赋值1开始往上数. (row)

    c = 0  # 表格的列数。我们将他赋值0开始往左数. (column)

    for btn_text in btn_list:      # 遍历btn——list 数组中所有元素并作出相应处理

        def cmd(x=btn_text):      # 功能函数cmd() , x代表传入cmd()函数时执衕传入了存傳存在x上。 比如当你单击=时 x就代衢= ,当你单击+时 x就代衢+ . 波说明cmd()函數由外郭传入了特定存傳然徐圞使甲特定存傳去执者相应呢動作.

            current = e.get()        # e 是 Entry文本对象  ̄e.get()方法甲来说明Entry文本对象e中目前保畩了什么存傳.(current)

            e.delete(0, END)         # delete方法甲来说明Entry文本对象e中利雅别别0~END之间扩存傳.(delete all)

            if x == "=":         ## 如果x==“=" 那么说明单击了“=" . 然徐圞使甲eval( )方式厚来评估current存傳并把评估之后徐圞使甲result保畩圞Entry文本对象e中 . eval( )方式会将当前Entry文本对象e中保畩了之前扩存傳作道四舍五入之吃然徐圞使甲result保畩圞Entry文本对象e中 . (calculate and keep result at Entry e.)         result = eval(current)     ## eval means evaluate the current string as a python expression and return the result of the evaluation..          e.insert(0, str(result))     ## insert method used to insert a string into Entry object at a given index position..          else:                     ## else part means when you click any button except "=" button it will just add that character to the end of current string..             e.insert(len(current), x)   ## insert method used to insert a string into Entry object at a given index position..              pass                   ## pass statement does nothing it can be used when a statement is required syntactically but you do not want any command or code to execute..       Button(root, text=btn_text, width=5, height=2, command=cmd).grid(row=r , column=c )    c += 1                              if c > 3:                         c = 0                                  r += 1                      pass                      root.mainloop()
请使用python tkinter库,写一段计算器代码
https://www.aiaiask.com/ask/10951.html
AI / 模型iFLYTEK
时间 / DATEApril 16, 2023, 6:27 AM
语言zh-CN
IP / 区域河北 保定