2011-11-26 37 views
0

我没有得到任何错误,但代码没有做我想做的事情,所以我必须在代码中犯了一个错误。我想要做的是,如果单词匹配,那么这些单词必须是一对,并且两个选择的单元格应该保持“self.hidden = False”,因此单元格应该仍然显示两个单元格后面的单词。否则,如果单词不匹配,那么单元格应该是“self.hidden = True”,两个单元格应显示“---”。错误没有任何错误 - 包括Tkinter

这里是重要的部分:

from tkinter import * 
import random 

class Cell: 
    def __init__(self, word, hidden): 
     self.word = word 
     self.hidden = hidden 

    def show_word(self): 
     """ Shows the word behind the cell """ 
     if self.hidden == True: 
      self.hidden = False 
     else: 
      self.hidden = True 

     self.button["text"] = str(self) 

     if mem.choice1 == None: 
      mem.choice1 = [self.word, self.hidden] 
     else: 
      mem.choice2 = [self.word, self.hidden] 
      self.check(mem.choice1, mem.choice2) 

    def check(self, choice1, choice2): 
     """ Checks if the chosen words are a pair """ 
     tries = 0 
     if choice1 == choice2: 
      pass 
     else: 
      self.show_word 

     tries += 1 

    def __str__(self): 
     """ Displays or hides the word """ 
     if self.hidden == True: 
      return "---" 
     else: 
      return self.word 

class Memory(Frame): 
    """ GUI application that creates a Memory game """ 
    def __init__(self, master): 
     super(Memory, self).__init__(master) 
     self.grid() 
     self.create_widgets() 
     self.tries = 0 
     self.choice1 = None 
     self.choice2 = None 

    def readShuffle(self): 
     """ Creates and organizes (shuffles) the pairs in a list """ 
     # reads the file and creates a list of the words 
     words_file = open("memo.txt","r") 
     row = words_file.readline() 
     words = list() 
     while row != "": 
      row = row.rstrip('\n') 
      words.append(row) 
      row = words_file.readline() 
     words_file.close() 

     # shuffles the words in the list 
     random.shuffle(words) 

     # creates 18 pairs of words in a new list 
     the_pairs = list() 
     for i in range(18): 
      the_pairs.append(Cell(words[i],True)) 
      the_pairs.append(Cell(words[i],True)) 

     # shuffles the words in the new list 
     random.shuffle(the_pairs) 

     return the_pairs 

    def create_widgets(self): 
     """ Create widgets to display the Memory game """ 
     # instruction text 
     Label(self, 
       text = "- The Memory Game -", 
       font = ("Helvetica", 12, "bold"), 
      ).grid(row = 0, column = 0, columnspan = 7) 

     # buttons to show the words 
     column = 0 
     row = 1 
     the_pairs = self.readShuffle() 
     for index in range(36): 
      temp = Button(self, 
        text = the_pairs[index], 
        width = "7", 
        height = "2", 
        relief = GROOVE, 
        command = lambda x = index: Cell.show_word(the_pairs[x]) 
        ) 
      temp.grid(row = row, column = column, padx = 1, pady = 1) 
      column += 1 
      the_pairs[index].button = temp 
      if column == 6: 
       column = 0 
       row += 1 

     # total tries 
     self.label = Label(self) 
     Label(self, 
       text = "Total tries: 0", 
       font = ("Helvetica", 11, "italic") 
      ).grid(row = 7, columnspan = 7, pady = 5) 

     # a quit button 
     Button(self, 
       text = "Quit", 
       font = ("Helvetica", 10, "bold"), 
       width = "25", 
       height = "1", 
       command = self.quit 
       ).grid(row = 8, column = 0, columnspan = 7, pady = 5) 

## def update_tries(self): 
##  """ Increase tries count and display new total. """ 
##  self.tries += 1 
##  self.label["text"] = "Total Tries: " + str(self.tries) 

    def quit(self): 
     """ Ends the memory game """ 
     global root 
     root.destroy() 

# main 
root = Tk() 
root.title("Memory") 
root.geometry("365x355") 
mem = Memory(root) 
root.mainloop() 
+0

我是新来的python,所以我不知道你的意思是什么“初始化”。我没有在这里做过? def __init __(self,word,hidden): self.word = word self.hidden = hidden – Amazon

+0

如果你打算让人们为你调试你的代码,那么至少要让它成为一个独立的例子。 “重要位”忽略了许多其他重要的位。你正在做很多没有意义的事情(例如,'Cell.check'中的'try'将会被设置为'0')。你也有冗余的if/else语句。 (例如,你的第一个if/else在'Cell.show_word'等于'self.hidden = not self.hidden',整个'Cell.check'函数根本没有意义。) –

+0

当然,我做了很多因为我是python的新手。我希望如果我在代码中某处出现了错误,那么我可以帮助我。 – Amazon

回答

1

眼前的问题是,你不能在Cell.check线136呼叫self.show_word

def check(self, choice1, choice2): 
    """ Checks if the chosen words are a pair """ 
    tries = 0 
    if choice1 == choice2: 
     pass 
    else: 
     self.show_word 

    tries += 1 

(你也应该只使用!=这里,而不是在你的if条款有pass声明。此外,tries没有做任何事情这里 ...)

然而,即使你确实称它为(即self.show_word()而不是self.show_word),那么你会遇到更大的问题,因为如果这些单词一旦出现,就会形成一个无限循环。

check将调用show_word然后将调用check,等等,等等

你需要做的是复位choice1choice2Cell.checkelse语句中各自的按钮。

但是,要做到这一点,您需要访问有问题的单元对象。事实上,你只能传递文本值,不管它们是否隐藏。

快速解决方法是传递单元对象本身。

不过,首先,让我们来清理你的功能了一下......你有这样的:

def show_word(self): 
    """ Shows the word behind the cell """ 
    if self.hidden == True: 
     self.hidden = False 
    else: 
     self.hidden = True 

    self.button["text"] = str(self) 

    if mem.choice1 == None: 
     mem.choice1 = [self.word, self.hidden] 
    else: 
     mem.choice2 = [self.word, self.hidden] 
     self.check(mem.choice1, mem.choice2) 

def check(self, choice1, choice2): 
    """ Checks if the chosen words are a pair """ 
    tries = 0 
    if choice1 == choice2: 
     pass 
    else: 
     self.show_word 

    tries += 1 

这相当于:

def show_word(self): 
    """ Shows the word behind the cell """ 
    self.hidden = not self.hidden 
    self.button["text"] = str(self) 

    if mem.choice1 is None: 
     mem.choice1 = [self.word, self.hidden] 
    else: 
     mem.choice2 = [self.word, self.hidden] 
     self.check(mem.choice1, mem.choice2) 

def check(self, choice1, choice2): 
    """ Checks if the chosen words are a pair """ 
    if choice1 != choice2: 
     self.show_word() # Infinite recursion!! 

现在,让我们通过周围的Cell实例本身,这样我们可以重新设置它们的显示值。

def show_word(self): 
    """ Shows the word behind the cell """ 
    self.hidden = not self.hidden 
    self.button["text"] = str(self) 

    if mem.choice1 is None: 
     mem.choice1 = self 
    else: 
     mem.choice2 = self 
     self.check(mem.choice1, mem.choice2) 

def check(self, choice1, choice2): 
    """ Checks if the chosen words are a pair """ 
    mem.choice1, mem.choice2 = None, None 
    if choice1.word != choice2.word: 
     for cell in (choice1, choice2): 
      cell.hidden = True 
      cell.button['text'] = str(cell) 

现在,事情将按照您的意图工作。但是,如果第二个选项与第一个选项不匹配,它将不会显示。 (事实上​​,我们可以删除mem.choice2在这个版本完全属性。)

所以,相反,我们只有重新在第三点击这两个值,如果它们不匹配。

def show_word(self): 
    """ Shows the word behind the cell """ 
    self.hidden = not self.hidden 
    self.button["text"] = str(self) 

    if mem.choice1 is None: 
     mem.choice1 = self 
    elif mem.choice2 is None: 
     mem.choice2 = self 
    else: 
     choice1, choice2 = mem.choice1, mem.choice2 
     mem.choice1, mem.choice2 = self, None 
     self.check(choice1, choice2) 

def check(self, choice1, choice2): 
    """ Checks if the chosen words are a pair """ 
    if choice1.word != choice2.word: 
     for cell in (choice1, choice2): 
      cell.hidden = True 
      cell.button['text'] = str(cell) 

现在,事情会或多或少的表现你想要的。

from tkinter import * 
import random 

class Cell: 
    def __init__(self, word, hidden=True): 
     self.word = word 
     self.hidden = hidden 

    def show_word(self): 
     """ Shows the word behind the cell """ 
     self.hidden = not self.hidden 
     self.button["text"] = str(self) 

     if mem.choice1 is None: 
      mem.choice1 = self 
     elif mem.choice2 is None: 
      mem.choice2 = self 
     else: 
      choice1, choice2 = mem.choice1, mem.choice2 
      mem.choice1, mem.choice2 = self, None 
      self.check(choice1, choice2) 

    def check(self, choice1, choice2): 
     """ Checks if the chosen words are a pair """ 
     if choice1.word != choice2.word: 
      for cell in (choice1, choice2): 
       cell.hidden = True 
       cell.button['text'] = str(cell) 

    def __str__(self): 
     """ Displays or hides the word """ 
     if self.hidden == True: 
      return "---" 
     else: 
      return self.word 

class Memory(Frame): 
    """ GUI application that creates a Memory game """ 
    def __init__(self, master): 
     super(Memory, self).__init__(master) 
     self.grid() 
     self.create_widgets() 
     self.tries = 0 
     self.choice1 = None 
     self.choice2 = None 

    def readShuffle(self): 
     """ Creates and organizes (shuffles) the pairs in a list """ 
     # reads a list of words from the file 
     with open('memo.txt', 'r') as infile: 
      words = [line.strip() for line in infile] 

     # creates 18 pairs of words in a new list 
     the_pairs = list() 
     for i in range(18): 
      the_pairs.extend([Cell(words[i]), Cell(words[i])]) 

     # shuffles the words in the new list 
     random.shuffle(the_pairs) 

     return the_pairs 

    def create_widgets(self): 
     """ Create widgets to display the Memory game """ 
     # instruction text 
     Label(self, 
       text = "- The Memory Game -", 
       font = ("Helvetica", 12, "bold"), 
      ).grid(row = 0, column = 0, columnspan = 7) 

     # buttons to show the words 
     column = 0 
     row = 1 
     the_pairs = self.readShuffle() 
     for index in range(36): 
      temp = Button(self, 
        text = the_pairs[index], 
        width = "7", 
        height = "2", 
        relief = GROOVE, 
        command = the_pairs[index].show_word 
        ) 
      temp.grid(row = row, column = column, padx = 1, pady = 1) 
      column += 1 
      the_pairs[index].button = temp 
      if column == 6: 
       column = 0 
       row += 1 

     # total tries 
     self.label = Label(self) 
     Label(self, 
       text = "Total tries: 0", 
       font = ("Helvetica", 11, "italic") 
      ).grid(row = 7, columnspan = 7, pady = 5) 

     # a quit button 
     Button(self, 
       text = "Quit", 
       font = ("Helvetica", 10, "bold"), 
       width = "25", 
       height = "1", 
       command = self.quit 
       ).grid(row = 8, column = 0, columnspan = 7, pady = 5) 


    def quit(self): 
     """ Ends the memory game """ 
     global root 
     root.destroy() 

# main 
root = Tk() 
root.title("Memory") 
root.geometry("365x355") 
mem = Memory(root) 
root.mainloop() 

但是,仍然有很多清理和重新分解,你可以做。如果Memory类处理检查点击等,会更有意义。此外,请查看新的readShuffle函数。你正在的文件中读取令人惊讶的错综复杂的方式。您应该可以阅读一些python文件用法的基本示例。这是很多比你想象的更简单。

+0

谢谢你的时间。一切都变得更有意义:) – Amazon

+0

有一个错误。当你按下已经选好的单元格时,单元格会隐藏起来,我希望它不会被隐藏。我怀疑“self.hidden = not self.hidden”这一行与它有关。我试过不同的方式来改变'self.hidden = not self.hidden',但我似乎无法让它正常工作。 – Amazon

+0

这不是一个错误。这是当前代码的有意设计。这正是你原来所做的。如果你想让它保持可见状态,你需要设置某种标志(例如'cell.frozen = True'),然后当你改变'cell.hidden'时检查该标志。例如。 'self.hidden = not self.hidden if cell.frozen else True'(尽管在那时使用多行if语句变得更具可读性)。 –