Tkinter报错:'Label' object is not callable 问题求助
问题分析与解决:Tkinter中"Label object is not callable"错误
问题描述
开发基于Tkinter和API的F1桌面应用时,将搜索按钮绑定到search函数(该函数调用full_name API函数),触发错误:
in search full_name() TypeError: 'Label' object is not callable
奇怪的是:
full_name函数内未创建Label实例- 直接将按钮绑定到
full_name函数可正常运行,绑定到调用它的search函数则报错
错误原因
变量名冲突:你先定义了名为full_name的函数,之后又在创建UI元素时定义了同名的Label控件:
def full_name(): # 函数逻辑... # 后续代码中覆盖了函数名 full_name = Label(left_frame, text = "Full Name :")
当Python执行到这段Label定义代码时,full_name这个名称指向的对象从函数变成了Label实例。所以当search函数尝试调用full_name()时,实际是在尝试调用一个Label对象,自然会抛出"Label object is not callable"的错误。
而直接绑定按钮到full_name函数时,按钮的command在Label定义前就已经绑定了函数对象,所以能正常运行。
解决方案
只需避免函数名和控件变量名重复,有两种常见修改方式:
方式1:修改函数名
将full_name函数重命名为不冲突的名称,比如get_driver_full_name:
def get_driver_full_name(): user_input = entry_box.get() lower_user_input = user_input.lower().split(" ")[1] response = requests.get("http://ergast.com/api/f1/drivers/{}.json".format(lower_user_input)) print(response.status_code) response_object = json.loads(response.content) name = response_object["MRData"]["DriverTable"]["Drivers"][0]["givenName"] + " " + response_object["MRData"]["DriverTable"]["Drivers"][0]["familyName"] print(name) def search(): get_driver_full_name()
方式2:修改Label变量名
将Label控件的变量名改为full_name_label,保留函数名不变:
# 替换原Label定义代码 full_name_label = Label(left_frame, text = "Full Name :") full_name_label.grid(row = 1, column = 0, sticky = W)
两种方式任选其一即可解决变量名冲突问题,让search函数能正常调用API函数。
内容的提问来源于stack exchange,提问作者Safwan Khan
相关产品推荐
相关产品推荐

