首页 > 解决方案 > 'Entry' 对象没有属性 'set'

问题描述

我希望能够输入数量并返回总价,但我不确定如何编码DoubleVar或为什么错误返回为“条目对象没有属性集”

from tkinter import *

def price():
    num1 = txtFirst.get()
    first = float(num1) * 22.75
    num2 = txtSecond.get()
    second = float(num2) * 100
    num3 = txtThird.get()
    third = float(num3) * 20.50
    num4 = txtFourth.get()
    fourth = float(num4) * 90
    num5 = txtFifth.get()
    fifth = float(num5) * 25.50
    num6 = txtSixth.get()
    sixth = float(num6) * 125.50
    sum = first + second + third + fourth + fifth + sixth
    cost.set("Sum: " + str(sum))


window = Tk()
window.title("Chicken Feed")
window.geometry("500x500")
Label(window, text="Feed\nType:").grid(row=0, column=0)
Label(window, text="Amount:").grid(row=0,column=1)
Label(window, text="Feed\nCost:").grid(row=0, column=2)
Label(window, text="10kg Pellets:").grid(row=1,column=0)
Label(window, text="50kg Pellets:").grid(row=2,column=0)
Label(window, text="10kg Mash:").grid(row=3,column=0)
Label(window, text="50kg Mash:").grid(row=4,column=0)
Label(window, text="10kg Enhanced:").grid(row=5,column=0)
Label(window, text="50kg Pellets:").grid(row=6,column=0)


cost = DoubleVar()
cost = Entry(window, state='readonly', width=20, textvariable=cost)
cost.grid(row=1, column=2, columnspan=3, padx=20, pady=6)


txtFirst = DoubleVar()
entFirst = Entry(window, width=5, textvariable=txtFirst)
entFirst.grid(row=1, column=1)

txtSecond = DoubleVar()
entSecond = Entry(window, width=5, textvariable=txtSecond)
entSecond.grid(row=2, column=1)

txtThird = DoubleVar()
entThird = Entry(window, width=5, textvariable=txtThird)
entThird.grid(row=3, column=1)

txtFourth = DoubleVar()
entFourth = Entry(window, width=5, textvariable=txtFourth)
entFourth.grid(row=4, column=1)

txtFifth = DoubleVar()
entFifth = Entry(window, width=5, textvariable=txtFifth)
entFifth.grid(row=5, column=1)

txtSixth = DoubleVar()
entSixth = Entry(window, width=5, textvariable=txtSixth)
entSixth.grid(row=6, column=1)

btnAdd = Button(window, text="Calculate", width=3, command=price)
btnAdd.grid(row=2, column=2, padx=20)

window.mainloop()

我不断收到此错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Luke\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "D:/Documents/stage2.py", line 17, in price
    cost.set("Sum: " + str(sum))
AttributeError: 'Entry' object has no attribute 'set'

标签: pythontkinter

解决方案


您使用相同的名称DoubleVarEntry

cost = DoubleVar()
cost = Entry(window, state='readonly', width=20, textvariable=cost)

后来你期望DoubleVar

cost.set("Sum: " + str(sum))

但你有Entry哪些没有.set()

使用不同的名称

cost_var = DoubleVar()
cost = Entry(window, state='readonly', width=20, textvariable=cost_var)

接着

cost_var.set("Sum: " + str(sum))

推荐阅读