TypeError:“ str”对象不可调用1

时间:2019-01-17 15:43:32

标签: python python-3.x

我想解决问题或用其他方法键入此命令行

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

root = Tk()
ent = ttk.Entry(root, width=40)
ent.pack()

ent1 = ttk.Entry(root, width=40)
ent1.pack()

bu = ttk.Button(root, text="click")
bu.pack()

i = ent.get()

sentence = i
sentence.replace(" ", "")


def buclick():
    if i == i():
        i()
    else:
        messagebox.showinfo("Error", "There is no product with this name")


bu.config(command=buclick)

print("Product" + "      " + "quantity" + "      " + "Price per one" + "      " + "Total")


class Product:
    index = 0
    item = ''
    quantity = 0
    price_per_once = 0
    total = 0

    def __init__(self, item, quantity, price_per_once, total):
        self.item = item
        self.quantity = quantity
        self.price_per_once = price_per_once
        self.total = total

    def return_information(self):
        return self.item + "          " + str(self.quantity) + "               " + str(
            self.price_per_once) + "             " + str(self.sum)

    def print_information(self):
        print(self.return_information())


def ic5501():
    item = "ic 550"
    result = int(ent1.get())
    quantity = result
    price_per_once = 15
    total = (15 * result)
    ic550 = Product(item, quantity, price_per_once, total)
    ic550.return_information()
    ic550.print_information()


def ic5502():
    item = "ic 5502"
    result = int(ent1.get())
    quantity = result
    price_per_once = 20
    total = (20 * result)
    ic550 = Product(item, quantity, price_per_once, total)
    ic550.return_information()
    ic550.print_information()


root.mainloop()


Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Ahmed Rabea Smaha\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:/Users/Ahmed Rabea Smaha/PycharmProjects/untitled/untitled.py", line 22, in buclick
    if i == i():
TypeError: 'str' object is not callable

2 个答案:

答案 0 :(得分:2)

如果我在评论中给出的解释是正确的,则允许用户调用您定义的函数的一种方法是将这些函数放入字典中,并以其名称为键。然后,您可以检查该命令以查看i是否属于它,并在适当时调用该函数。

def buclick():
    i = ent.get()
    if i in user_callable_functions:
        user_callable_functions[i]()
    else:
        messagebox.showinfo("Error", "There is no product with this name")

#put this just above root.mainloop()
user_callable_functions = {
    "ic5501": ic5501,
    "ic5502": ic5502
}

答案 1 :(得分:0)

从您提供给我们的信息来看,似乎在第22行尝试if i == i()的地方,您正在尝试检查变量i是否对应于函数i()的返回值。在我看来,您在任何地方都没有函数i()(无论如何对于函数来说都是一个坏名字)。也许您要检查的是if i == result,其中result是ic5501或ic5502的变量?如果我错了请纠正我。

编辑

在检查注释时,如果您要检查我是否是函数名,我建议作为一个基本开始(取决于这是否是一个大项目),创建一个包含所有函数名和将它们与功能关联。

my_functions = [["function_1", function_1], ["function_2", function_2]]

我将带您回到另一个问题,答案可以帮助您使用上述解决方案。

call list of function using list comprehension