How do I make the hidden words reveal themselves when pressing a button in tkinter?

46 Views Asked by At

I have created a separate class for the words that are in my memory grid and I am trying to make it so they are hidden till the user presses the button that activates the toggle_info method in my buttons class. It does not work.

I tried to create a separate class for the words so that they don't get overwritten In my for function in the game_menu method but the text on the buttons do not change at all when pressed. Here is the code:

import tkinter as tk
import random

class Buttons:
    '''För att spelet ska komma ihåg informationen bakom varje knapp krävs det att informaitonen sparas som attribut o knappar klassen annars glömmer funktionen bort dem.'''
    
    def __init__(self, hidden_word, is_it_hidden=False):
        self.is_it_hidden = is_it_hidden
        self.hidden_word = hidden_word
    
    def get_hidden_word(self):
          # Måste titta närmare på vad som händer när man klickar på en knapp. Fundera på att göra en metod i den andra klassen.
        print(self.is_it_hidden)
        print(self.hidden_word)
        if self.is_it_hidden:
            return self.__str__()
        else:
            return '?'
        '''return self.hidden_word if self.is_it_hidden else '?'''
    
    def toggle_info(self):
        self.is_it_hidden = True
        return self.get_hidden_word()

        
    def __str__(self):
        return f'{self.hidden_word}'


    


class Huvudmeny:
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Memory game")
        self.root.geometry("800x500")
            
        self.label = tk.Label(self.root, text="Hur stor matris vill du spela med? (A*A). Du måste välja ett jämt tal.", font = ("Arial", 18), background="White", foreground="Black")
        self.label.pack(padx=10, pady=10)

        self.entry_var = tk.StringVar()
        self.entry = tk.Entry(self.root, text= 'A= ', textvariable=self.entry_var, font=("Arial", 18))
        self.entry.pack(padx=20, pady=20)

        self.button = tk.Button(self.root, text= "Klar", font=("Arial", 18), command=self.move_forward)
        self.button.pack(padx=12, pady=12)

        self.words = 0
        self.word_list = []
        self.number_of_words = None
        self.hidden_words = None
        self.words_used = []
        self.button_instances = []
        self.root.mainloop()
        


    def game_menu(self):
        for i, self.button_instances in enumerate(self.button_instances):
            self.button = tk.Button(self.root, text=Buttons(self.button_instances).get_hidden_word(), command= lambda: Buttons.toggle_info(self.button_instances))#
            self.button.grid(row=i // self.words, column=i % self.words, padx=10, pady=10)
            '''self.hidden_words = self.button.cget('text')
            self.button.config(text='?')   
            print(self.hidden_words)'''

    def move_forward(self):
        integer_check = int(self.entry_var.get())
        if integer_check % 2 == 0:
            self.words = integer_check
            self.number_of_words = int((integer_check**2)/2)
            for widget in self.root.winfo_children():
                widget.destroy()
            self.memory_init()
            self.game_menu()

        else:
            print('Var vänlig skriv ett jämt heltal.')
            return self.move_forward(self)
    
    

    def memory_init(self) -> list:
        ord = 'memo.txt'
        with open(ord, 'r', encoding='utf-8') as file:
            self.word_list = file.readlines()

        # Gör ord_denna_macth till self.ord_denna_match
        self.words_used = random.sample(self.word_list, self.number_of_words) * 2
        random.shuffle(self.words_used)

        
        for i in range(0, len(self.words_used)):
            self.words_used[i] = self.words_used[i][:-1]
            button_instance = Buttons(self.words_used[i])
            self.button_instances.append(button_instance)
            print(self.button_instances)
        
        return self.words_used  




Huvudmeny()
1

There are 1 best solutions below

0
acw1668 On

Note that calling Buttons.toggle_info() does not update the text of the button automatically. You need to call .config(text=...) on the button to update the text of the button:

class Huvudmeny:
    ...

    def game_menu(self):
        # use local variables instead of instance variables
        for i, button_instance in enumerate(self.button_instances):
            button = tk.Button(self.root, text=button_instance.get_hidden_word())
            # use default values of function arguments to pass
            # the required instances of the button and `Buttons` class
            button.config(command=lambda btn=button, i=button_instance: btn.config(text=i.toggle_info()))

    ...

Note also that the toggle_info() should be modified to actually toggle the instance variable self.is_it_hidden as below:

class Buttons:
    ...

    def toggle_info(self):
        # toggle the instance variable
        self.is_it_hidden = not self.is_it_hidden
        return self.get_hidden_word()
    
    ...

PS: I don't understand why you call self.move_forward(self) in the else block inside move_forward(). Should it be removed?