English 中文(简体)
甲型六氯环己烷
原标题:Memory Game in Python with Tkinter

我试图利用第3和tkinter语进行记忆游戏。 我是新到晚上的,这样是困难的。 我的问题是,我试图将“法庭”这一类“法庭”中的“手法”称为“密码”,但我不知道如何这样做。

记忆游戏:

    def create_widgets(self):
        """ Create widgets to display the Memory game """
        # buttons to show the words
        column = 0
        row = 1
        the_pairs = self.readShuffle()
        for index in range(36):
            Button(self,
                   text = "hidden",
                   width = "7",
                   height = "2",
                   relief = GROOVE,
                   command = WHAT SHOULD I WRITE HERE???
                   ).grid(row = row, column = column, padx = 1, pady = 1)

            column += 1
            if column == 6:
                column = 0
                row += 1
问题回答

你会陷入一个微妙的透视问题。 当你创设职能时,是指包含范围的各种变数,这些变量的价值在职能定义时确定,但在职能时确定。 换言之,当你这样做时:

command = lambda: print(index) 

页: 1 当用户推导其中的一个州时,这一功能即被称作“,<代码>/index的价值为35。

为了确定职能时的价值finition,你必须使用缺省值,如:

command = lambda x=index: print(x)

我确信,你可以列出相应的<代码> how_word 固定,但就以下情况而言:

command = lambda x=index: Cell.show_word(the_pairs[x])

在我能直接帮助你之前,我需要回答我的意见,但在时间上,这只是起草守则的一些方面:

from tkinter import *
# `tkinter` is meant to be used that way, but `random` isn t really - the names
# can be confusing without an explicit module reference. So instead:
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 """
        self.hidden = not self.hidden
        # no need to take this logic apart into cases
        self.button.set(str(self))

    def __str__(self):
        """ Displays or hides the word """
        # A simpler form of conditional; also, don t compare things
        # explicitly to True or False
        return "---" if self.hidden else 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

    def readShuffle(self):
        """ Creates and organizes (shuffles) the pairs in a list """
        # The modern idiom for handling files and ensuring they are closed
        with open("memo.txt","r") as words_file:
            # The file can be iterated over directly, and is treated as
            # a list of lines. Since we just want all the rstrip()ped
            # lines, we can do the file processing all at once with a list 
            # comprehension.
            # Let s also grab 18 random words while we re at it. We don t
            # really want to *shuffle* the words, but instead *sample* them -
            # we don t care about the words that we didn t select.
            words = random.sample(
                [line.rstrip( 
 ) for line in words_file], 18
            )

        # Instead of making 18 pairs of cells, we can make 18 cells and then
        # pair them up. The set of 18 cells can also be made easily with a 
        # list comprehension. Notice how we get to iterate directly now, 
        # instead of messing around with indices into lists.
        the_pairs = [Cell(word, True) for word in words] * 2
        shuffle(the_pairs)
        return the_pairs

    def create_widgets(self):
        """ Creates 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
        the_pairs = self.readShuffle()
        self.buttons = []
        # Again, we can iterate in a more Pythonic way.
        for i, pair in enumerate(the_pairs):
            # Instead of having extra counters to work out the row and column,
            # we can simply do math on the index value.
            column, row = i % 6, i // 6
            temp = StringVar()
            temp.set(str(pair))
            # Instead of adding the button to a list and then reaching into the
            # list to configure it, get everything set up first.
            button = Button(self,
                   textvariable = temp,
                   width = "7",
                   height = "2",
                   relief = GROOVE,
                   command = lambda: print(index)
                   ))
            button.grid(row = row, column = column, padx = 1, pady = 1)
            buttons.append(button)
            pair.button = temp

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

        # ...




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签