我在做一个程序,发现了一个错误。 所以在我的程序中,你可以创建一个简单的功能,改变颜色的按钮。 创建按钮后,它的文本保存在一个.dat文件中,加载后,它用文件中存储的文本创建按钮。在
按钮创建,但当我试图改变颜色时,它会向我发送一个错误:
TypeError: changecolor() missing 1 required positional argument: 'self'
我看到其他帖子说答案是实例化函数,例如:
^{pr2}$但如果我试图这么做,我会得到另一个错误:
__init__() missing 3 required positional arguments: 'MainWindow', 'color', and 'text'
我已经尝试了所有方法来修复这个错误,所以我想实例化类并尝试添加所需的位置参数不是一个选项。在
那么,我该怎么解决这个问题呢? 如果你解决了这个问题,请告诉我怎么做。在
以下是加载包含文本的文件的代码:
class LoadButtons:
def _init_(self):
global console
self.instance=console
def LoadButton(self):
global lnumber, path, name, p
if os.path.isfile("%s\BI\Button%s.dat" %(path, lnumber)):
print("Button%s found!" %(lnumber))
name = pickle.load(open("%s\BI\Button%s.dat" %(path, lnumber), 'rb'))
console = Button(MainWindow, text=name,bg = "#E6E6E6", command=needed_but.changecolor())
console.pack()
LoadButtons()._init_()
lnumber += 1
LoadButtons().LoadButton()
else:
lnumber = 0
下面是让按钮变色的代码:
class needed_but:
def __init__(self,MainWindow,color,text):
console = Button(MainWindow, text=text,bg=color, command=self.changecolor)
console.pack()
self.instance=console
def changecolor(self):
buttonred,buttongreen,buttonblue=get_color()
global clicked,misses_dict,dictionary
#clicked=True
#global buttoncolor
if buttonred == True:
if os.path.exists("%s\SI" %(path)):
self.instance.configure(bg = "#ff0000")
dun = self.instance.cget('text')
print(dun)
if dun in misses_dict:
misses_dict[('%s' %(dun))] += 1
else:
misses_dict[('%s' %(dun))] = 1
dictionary = misses_dict
pickle.dump(dictionary, open("%s\SI\SIA.dat" %(path), 'wb'))
print(misses_dict)
buttonred = False
else:
print("ATTENTION: The SI Folder was not found, Please Create a folder with the name SI\nIf you don't create the folder, then you will not be able to use this program")
elif buttongreen == True:
self.instance.configure(bg = "#00ff00")
elif buttonblue == True:
self.instance.configure(bg = "#2e9afe")
谢谢!在
您将实例方法作为类方法调用。
changecolor
必须通过一个needed_but
实例来调用,该实例是您想要对其进行操作的self
对象。例如:由于您尚未实例化任何此类对象,所以我不完全确定您希望如何处理此调用。在
更新
你现在的问题是:
^{pr2}$与
根据您的初始化方法,必须提供列出的所有三个值才能创建对象。主代码的实例化只提供实例化的隐式
self
。在相关问题 更多 >
编程相关推荐