我有一个用于cookie点击器的代码块,但是当我尝试将它放在一个类中时它不起作用,给我这个错误
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-
32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
TypeError: click() missing 1 required positional argument: 'self'
我不明白为什么它不起作用 我的代码如下
from tkinter import*
import os
root = Tk()
class Main():
os.chdir('C:\\Users\\Travi\\Downloads')
cookies = 0
grandmas =0
gmaprice = 10
cookiesIcon = Label(root,text = "Cookies you have:"+str(cookies))
cookiesIcon.grid(row = 1,column = 0)
gma = Label(root,text = "Grandmas you have:"+str(grandmas))
gma.grid(row = 0, column = 1)
def click(self):
global cookies,cookiesIcon
cookies+=1
cookiesIcon.config(text = "Cookies you have:"+str(cookies))
def grandma(self):
global cookies,grandmas,cookiesIcon,gma,gmaprice
if cookies>gmaprice:
grandmas+=1
cookies-=gmaprice
gmaprice+=5
cookies.config(text = "Cookies you have:"+str(cookies))
gma.config(text = "Grandmas you have:"+str(grandmas))
photo=PhotoImage(file = "Cookies.gif")
b = Button(root,command =click)
b.config(image=photo)
b.grid()
gmaupgrade=Button(root,command =grandma,text = "Grandmas for sale")
gmaupgrade.grid(column = 1, row = 1)
root.mainloop()
答案 0 :(得分:0)
正如评论中所提到的,你必须首先更好地理解python(以及一般)中的类是如何工作的。
我已经纠正了代码中的一系列错误;那就是:
- 添加一个``函数来初始化类属性
- 删除了无用的global
语句;所有类属性都可以在类中访问
- 更正了一些错误使用的变量(cookies
i / o cookiesIcon
和grandma
i / o gma
)
from tkinter import*
import os
root = Tk()
class Main():
def __init__(self):
# os.chdir('C:\\Users\\Travi\\Downloads')
self.cookies = 0
self.grandmas =0
self.gmaprice = 10
self.cookiesIcon = Label(root,text = "Cookies you have:"+str(self.cookies))
self.cookiesIcon.grid(row=1, column=0)
self.gma = Label(root,text = "Grandmas you have:"+str(self.grandmas))
self.gma.grid(row = 0, column = 1)
# photo=PhotoImage(file = "Cookies.gif")
b = Button(root, command=self.click)
# b.config(image=photo)
b.grid()
self.gmaupgrade=Button(root,command=self.grandma, text = "Grandmas for sale")
self.gmaupgrade.grid(column = 1, row = 1)
root.mainloop()
def click(self):
self.cookies += 1
self.cookiesIcon.config(text = "Cookies you have:"+str(self.cookies))
def grandma(self):
if self.cookies > self.gmaprice:
self.grandmas += 1
self.cookies -= self.gmaprice
self.gmaprice += 5
self.cookiesIcon.config(text="Cookies you have:" + str(self.cookies))
self.gma.config(text="Grandmas you have:" + str(self.grandmas))
Main()
我希望这能让您了解自己需要做什么,以及了解更多信息的愿望。