tkinter.Buttonをクリックしたときにオブジェクトのメソッドを呼び出したいのですが。
コードを以下のコードに減らしました。関数(newone)を直接呼び出すと( "newone( 'three')"のように)、すべて問題ないように見えますが、ボタンをクリックすると(同じ関数を呼び出す)、エラーが発生します。
'typerror:x is ont callable'に関する同様の投稿を見ましたが、コードに類似したものは見つかりませんでした。ここで何が問題になっているのかわかりません。addone()内で新しいオブジェクトをインスタンス化する場合にのみエラーが発生するため、lot.addone(name)への実際の呼び出しは機能しているようです。クラス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
クラス名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()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加