-1

我正在用 tkinter 做计算器,但按钮有问题。当我单击时,它显示如下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1885, in __call__
    return self.func(*args)
  File "C:\Users\ADMIN\Desktop\SSCalc\calc.py", line 19, in <lambda>
    btn1 = tk.Button(root,text='1',height=0,width=5,font=fontBtn,command=lambda:pressBtn(1))
  File "C:\Users\ADMIN\Desktop\SSCalc\calc.py", line 12, in pressBtn
    mathValue.set(mathValue)
AttributeError: 'str' object has no attribute 'set'

这是我的代码:

import tkinter as tk
from tkinter import font as tkFont
from tkinter import StringVar, Entry, Button
from tkinter.ttk import *
import math
root = tk.Tk()
root.title("Simple Calculator")
mathValue = ""
def pressBtn(number):
    global mathValue
    mathValue+=str(number)
    mathValue.set(mathValue)
def mainCalc():
    mathValue = StringVar()
    fontBtn = tkFont.Font(family="Helvetica",size=15,weight='bold')
    inputMath = Label(root,textvariable=mathValue,relief='sunken')
    inputMath.config(text="Enter Your Calculation...", width=50)
    inputMath.grid(columnspan=4,ipadx=100,ipady=15) 
    btn1 = tk.Button(root,text='1',height=0,width=5,font=fontBtn,command=lambda:pressBtn(1))
    btn1.grid(row=1,column=0)
    btn2 = tk.Button(root,text='2',height=0,width=5,font=fontBtn,command=lambda:pressBtn(2))
    btn2.grid(row=1,column=1)
mainCalc()
root.mainloop()

谁能为我找到解决此错误的方法?谢谢!

4

1 回答 1

1

您的代码中有两个问题:

  • 这样做mathValue+=str(number)会创建一个local variable被调用mathValue的字符串。
  • global mathValue在该行的顶部将其变为global variable.

因此.get()不适用于string object.

以下代码有效:

import tkinter as tk
from tkinter import font as tkFont
from tkinter import StringVar, Entry, Button
from tkinter.ttk import *
import math
root = tk.Tk()
root.title("Simple Calculator")
mathValue = ""

def pressBtn(number):
    mathValue.set(mathValue.get() + str(number))

def mainCalc():
    global mathValue
    mathValue = StringVar()
    fontBtn = tkFont.Font(family="Helvetica",size=15,weight='bold')
    inputMath = Label(root,textvariable=mathValue,relief='sunken')
    inputMath.config(text="Enter Your Calculation...", width=50)
    inputMath.grid(columnspan=4,ipadx=100,ipady=15) 
    btn1 = tk.Button(root,text='1',height=0,width=5,font=fontBtn,command=lambda:pressBtn(1))
    btn1.grid(row=1,column=0)
    btn2 = tk.Button(root,text='2',height=0,width=5,font=fontBtn,command=lambda:pressBtn(2))
    btn2.grid(row=1,column=1)

mainCalc()
root.mainloop()

我对此代码进行了 2 处更正:

  • 我已将global mathValue线放在mainCalc. StringVar这使得global variable.
  • 我已将 2 行替换pressBtnmathValue.set(mathValue.get() + str(number)). 在这里,mathValue.get()获取先前存储的值mathValue(如果有,否则,''如果不存在值,则返回)并+ str(number)附加新值。最后mathValue.set设置新值。
于 2020-12-09T18:36:26.610 回答