我想在单击tkinter.Button时调用对象的方法。
我已经将我的代码简化为下面的代码。当我直接调用函数(newone) (如“newone(‘3’)”)时,一切看起来都很好,但是当单击按钮(调用相同的函数)时,就会得到一个错误。
我看过类似的'typerror: x不是可调用的‘,但我没有发现任何类似于我的代码,我不知道这里出了什么问题。对lot.addone(name)的实际调用似乎有效,因为只有当我想在addone()内实例化一个新对象时才会得到错误。类thing()是否不再可见(因为通过tkinter.button调用它?)我怎样才能让它再次可见?任何帮助都将不胜感激。
import tkinter
window = tkinter.Tk()
def newone(name='four'):
global lot
lot.addone(name)
class thing:
def __init__(self):
self.name = 'nothing'
class list_of_things:
def __init__(self):
self.things = dict()
def addone(self, name):
self.things[name] = thing() ## the error location
self.things[name].name = name
lot = list_of_things()
lot.addone('one') ## something dummy
lot.addone('two')
newone('three') ## this works
print(lot.things['one'].name)
print(lot.things['three'].name) ## prints out correctly
row_index = 0
for (key, thing) in lot.things.items():
tkinter.Label(window, text = thing.name).grid(row = row_index)
row_index = row_index + 1
tkinter.Button(window, text = 'New task', command = newone).grid(row = row_index) ## this fails
window.mainloop()
我得到的错误如下:
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\tools\Miniconda3\envs\3dot6kivy\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "test.py", line 8, in newone
lot.addone(name)
File "test.py", line 19, in addone
self.things[name] = thing() ## the error location
TypeError: 'thing' object is not callable
发布于 2019-07-07 18:28:29
类名thing
被名为thing
的变量屏蔽。我将类重命名为Thing
,它起作用了。
还对下列守则作了其他调整:
import tkinter as tk
class Thing:
def __init__(self):
print("adding a 'Thing' object")
self.name = 'nothing'
class ListOfThings:
def __init__(self):
self.things = dict()
def addone(self, name):
self.things[name] = Thing()
self.things[name].name = name
def newone(name='four'):
lot.addone(name) # lot doesn't need to be global if you are not assigning to it
if __name__ == '__main__':
window = tk.Tk()
lot = ListOfThings()
lot.addone('one')
lot.addone('two')
newone('three')
print(lot.things['one'].name)
print(lot.things['three'].name)
row_index = 0
for (key, thing) in lot.things.items():
tk.Label(window, text=thing.name).grid(row=row_index)
row_index = row_index + 1
tk.Button(window, text='New task', command=newone).grid(row=row_index)
window.mainloop()
https://stackoverflow.com/questions/56924472
复制相似问题