Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 没有任何错误的错误-包括Tkinter_Python_Python 3.x_Tkinter - Fatal编程技术网

Python 没有任何错误的错误-包括Tkinter

Python 没有任何错误的错误-包括Tkinter,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我没有得到任何错误,但代码没有做我想要的,所以代码中一定有我犯了错误的地方。我想做的是,如果单词匹配,那么单词必须是一对,并且所选的两个单元格应保持“self.hidden=False”,因此单元格仍应显示两个单元格后面的单词。否则,如果单词不匹配,则单元格应为“self.hidden=True”,两个单元格应显示“--” 以下是重要部分: from tkinter import * import random class Cell: def __init__(self, word,

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

以下是重要部分:

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()

直接的问题是您没有调用
self。请在
单元格的第136行显示单词。检查

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
语句。此外,
trys
在此处没有任何操作…)

但是,即使您确实调用它(即
self.show\u word()
而不是
self.show\u word
),您也会遇到更大的问题,因为一旦调用,如果单词不相同,您将建立一个无限循环

check
将调用
show_word
,然后调用
check

您需要做的是重置
choice1
choice2
以及
单元格中的
else
语句中的相应按钮。选中

但是,要做到这一点,您需要访问相关的单元格对象。实际上,您只传入它们的文本值,不管它们是否隐藏

快速修复方法是绕过单元对象本身

不过,首先,让我们稍微清理一下函数。。。你有这个:

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!!
现在,让我们绕过
单元格
实例本身,以便重置它们显示的值

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()

然而,仍然有很多清理和重新分解的工作可以做。让
内存
类句柄检查单击等功能更有意义。另外,请看一看新的
readShuffle
函数。你在以令人惊讶的复杂方式阅读文件。您可能应该阅读一些python中文件使用的基本示例。这比你想象的要简单得多

我是python新手,所以我不知道“初始化”到底是什么意思。我不是在这里做的吗?def uuu init uuuu(self,word,hidden):self.word=word self.hidden=hidden如果您要让别人为您调试代码,那么至少让它成为一个独立的示例。“重要部分”省略了许多其他重要部分。您正在做很多没有意义的事情(例如,在
单元格中尝试
。check
将始终是
0
)您还有很多多余的if/else语句。(例如,你在
单元格.show_word
中的第一个if/else相当于
self.hidden=not self.hidden
,整个
单元格.check
函数毫无意义。)当然,我犯了很多错误,因为我是python新手。如果我在代码中的某个地方想错了,我希望ppl能帮助我。请求帮助是可以的,但是当你的代码引用了很多你发布的代码片段中没有定义的东西时,很难遵循你的思路。调试一个没有足够信息运行的代码段本身就比较困难。我现在编辑了我的文章,这样你就可以运行代码了。问题是ppl以前告诉过我,我不应该发布程序的全部代码,只应该发布重要的部分。谢谢你的时间。现在一切都变得更有意义了:)有一个bug。当你按下一个已经选择的单元格时,该单元格将隐藏,我希望它不会隐藏。我怀疑行
self.hidden=不是self.hidden
与此有关。我尝试了不同的方法来改变self.hidden=不是self.hidden,但我似乎无法让它正常工作。这不是一个bug。这是当前代码的精心设计。这正是你最初让它做的。如果希望它保持可见,则需要设置某种标志(例如,
cell.freezed=True
),然后在更改
cell.hidden
时检查该标志。例如,
self.hidden=not self.hidden if not cell.freezed else True
(尽管此时使用多行if语句更容易阅读。)我是python新手,所以我无法100%理解您。我试图将
self.hidden=not self.hidden
更改为
如果self.hidden:self.hidden=False,否则:self.hidden=False
。但这只是偶尔起作用,细胞的行为非常奇怪。