属性错误:'str'对象没有属性'set' (Tkinter)



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

Exception in Tkinter callback
Traceback (most recent call last):
File "C:UsersADMINAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 1885, in __call__
return self.func(*args)
File "C:UsersADMINDesktopSSCalccalc.py", line 19, in <lambda>
btn1 = tk.Button(root,text='1',height=0,width=5,font=fontBtn,command=lambda:pressBtn(1))
File "C:UsersADMINDesktopSSCalccalc.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()

有人能为我找到解决这个错误的方法吗?谢谢

您的代码中有两个问题:

  • 执行mathValue+=str(number)会创建一个名为mathValuelocal variable,它是一个字符串
  • 该行顶部的CCD_ 4将其转换为CCD_

因此.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中。这使得CCD_ 10变成了CCD_
  • 我已经用mathValue.set(mathValue.get() + str(number))替换了pressBtn中的2行。这里,mathValue.get()获取mathValue中先前存储的值(如果有,否则,如果没有值,则重新运行''(,并且+ str(number)附加新值。最后CCD_ 18设置新值

相关内容

  • 没有找到相关文章