AttributeError: 'str' object has no attribute 'set' (Tkinter)

AttributeError: 'str' object has no attribute 'set' (Tkinter)

我正在使用 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()

谁能帮我解决这个错误?谢谢!

您的代码中有 2 个问题:

  • 执行 mathValue+=str(number) 会创建一个名为 mathValuelocal variable,它是一个字符串。
  • 该行顶部的
  • 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.
  • 并且我已将 pressBtn 中的两行替换为 mathValue.set(mathValue.get() + str(number))。这里,mathValue.get() 获取先前存储在 mathValue 中的值(如果有的话,如果没有值,则返回 '')并且 + str(number) 附加新值。最后 mathValue.set 设置新值。