2011-11-17 2 views
1

파이썬 3과 tkinter를 사용하여 메모리 게임을 만들려고합니다. 나는 파이썬에 익숙하지 않기 때문에 이것은 어렵다. 내 문제는 클래스 "메모리"에서 "셀"클래스의 "show_word"메서드를 호출하려고하지만 정확히 어떻게 수행해야할지 모르겠다.파이썬에서 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 
+0

정확히 어떤 조건에서 'show_word'를 지정 하시겠습니까? 또한 귀하의 질문과 관련이없는 코드 부분을 잘라내십시오. (그리고 나중에 한 번에 많은 코드를 작성하지 말고 작은 조각을 먼저 작성한 다음 단계적으로 작성하십시오.) –

+0

아마존의 경우, 나는 단지 수정을 위해'show_word' 버전을 게시했습니다. – senderle

답변

3

당신은 미묘한 범위 지정 문제로 실행했습니다. 변수를 포함하는 범위에서 변수를 참조하는 함수를 만들면 함수 정의시 변수 값이 고정되지 않고 함수 실행시 일 때 고정됩니다. 이렇게 즉, :

command = lambda: print(index) 

당신은 함수가를 호출 할 때 index의 값이 무엇이든 인쇄 파이썬을 말하는 것입니다. 시간 사용자가 그 함수를 호출 할 원인, 그 버튼 중 하나를 밀어으로 index의 값이 35

기능 정의의 시간에 값을 해결하려면, 당신은 같은 기본값을 사용해야합니다 그래서 :

command = lambda x=index: print(x) 

난 당신이 해당 show_word 수정을 알아낼 수 있는지 해요,하지만 단지의 경우 : 당신이 directl 도움이 될 수 있습니다 전에

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

값을 수정하는 다른 방법이 있지만 확실히 우아하지 않습니다. 어쨌든, 여기에'show_cell' 메소드를 사용하고 싶으므로 아마 그걸 보여 주어야합니다. –

0

내 의견에 대한 답변이 필요합니다 y를 사용하는 것이 아니라 좀 더 우아하게 코드를 작성하는 몇 가지 힌트가 있습니다.

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('\n') 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) 

     # ... 
+0

어. 결국 당신이 의미하는 바를 알아 냈고, 센덜 레의 대답은 당신이 필요로하는 것과 정확히 같습니다. 그래도 나는 교육 받았으면 좋겠다. –

관련 문제