Python中的类对象编程

2024-10-01 04:46:52 发布

您现在位置:Python中文网/ 问答频道 /正文

import Tkinter
import random

class colourgame():

    colours=['Red','Blue','Green','Pink','Black', 
           'Yellow','Orange','White','Purple','Brown']
    score=0
    timeleft=30

    def __init__(self):
        root = Tkinter.Tk() 
        root.title("COLORGAME") 
        root.geometry("375x200") 
        instructions = Tkinter.Label(root, text = "Type in the colour of the words, and not the word text!", font = ('Helvetica', 12)) 
        instructions.pack()   
        scoreLabel = Tkinter.Label(root, text = "Press enter to start", font = ('Helvetica', 12)) 
        scoreLabel.pack() 
        timeLabel = Tkinter.Label(root, text = "Time left: " +str(self.timeleft), font = ('Helvetica', 12)) 
        timeLabel.pack()  
        label = Tkinter.Label(root, font = ('Helvetica', 60)) 
        label.pack() 
        e = Tkinter.Entry(root) 
        root.bind('<Return>', self.startGame()) 
        e.pack() 
        e.focus_set() 
        root.mainloop()

    def startgame(self,event):

        if self.timeleft==30:
            self.countdown()
        self.nextcolour()            

    def countdown(self):

        if self.timeleft > 0: 
            self.timeleft -= 1
            timeLabel.config(text = "Time left: "+ str(self.timeleft))  #explain
            timeLabel.after(1000, self.countdown)                        

    def nextColour(self): 

        if self.timeleft > 0: 
            e.focus_set()                                
            if e.get().lower() == colours[1].lower(): 
                self.score += 1
            e.delete(0, Tkinter.END) 
            random.shuffle(colours) 
            label.config(fg = str(colours[1]), text = str(colours[0])) #explain
            scoreLabel.config(text = "Score: " + str(self.score)) 


obj=colourgame()
obj.startGame()

出现的错误是:

AttributeError: colourgame instance has no attribute 'startGame'

请有人给我解释一下原因


Tags: textselfiftkinterdefrootlabelpack
1条回答
网友
1楼 · 发布于 2024-10-01 04:46:52

python区分大小写。你的问题在这里:

obj=colourgame() 
obj.startGame() #this should be obj.startgame() because you defined it all lower case not CamelCase

这一行root.bind('<Return>', self.startGame())中的__init__()定义中存在相同的问题,应该是root.bind('<Return>', self.startgame())

相关问题 更多 >