使用Tkinter开发计算器遇按钮报错:'str'对象无'set'属性
修复Tkinter计算器中的AttributeError问题
咱们先来拆解一下你遇到的错误:
AttributeError: 'str' object has no attribute 'set'
这个错误的核心原因是变量作用域和类型不匹配:
- 你在全局作用域把
mathValue初始化成了空字符串"" - 在
mainCalc()函数里,你又创建了一个局部的StringVar()变量,名字也是mathValue——但这个局部变量只在mainCalc()内部有效,全局的mathValue还是原来的字符串 - 当点击按钮触发
pressBtn()时,它访问的是全局的字符串类型mathValue,而字符串没有set()方法,自然就报错了
修复步骤
只需要调整三个关键地方:
- 把全局的
mathValue初始化为StringVar()类型 - 删掉
mainCalc()里的局部mathValue = StringVar()定义 - 在
pressBtn()里,先用get()获取当前输入框的内容,拼接新数字后再用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") # 全局变量初始化为StringVar类型 mathValue = StringVar() # 设置初始提示文本 mathValue.set("Enter Your Calculation...") def pressBtn(number): global mathValue # 获取当前值,如果是初始提示文本就清空后拼接 current_value = mathValue.get() if current_value == "Enter Your Calculation...": current_value = "" current_value += str(number) mathValue.set(current_value) def mainCalc(): fontBtn = tkFont.Font(family="Helvetica",size=15,weight='bold') # 直接使用全局的mathValue inputMath = Label(root,textvariable=mathValue,relief='sunken') inputMath.config(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()
另外我还加了个小优化:当输入框显示初始提示文本时,点击数字会自动清空提示,直接输入数字,体验更友好。
内容的提问来源于stack exchange,提问作者FurryCoder
相关产品推荐
相关产品推荐

