How to use user-clicked button text as input in Tkinter?

Asked

Viewed 163 times

0

I would like to use the text of the button clicked by the user of my game to make a logical test and return another question to the user. The game will work with a sequence of these questions, and the possible answers are always "yes" and "no".

For this, I would like to grab the text of the button clicked between the buttons present in my Frame buttons. I just figured out how to grab the text from a specific button with the command my_button['text'].

The code of the game is too big, so I made a EMCV which I present below. The commented part would be equivalent to the logical test I want to implement, but I haven’t yet.

import tkinter as tk
from tkinter import ttk
import random

def start_game():
    n = random.sample(range(5000),1)[0]
    text_widget4.insert('1.0', '{} é um número é par?'.format(str(n)))
    #essa parte não está funcionando
    # resto = n%%2
    # if (resto==0) & (button_w4['text'] = 'Yes'):
    #     text_widget4.insert('2.0', 'Você está certo')
    # elif (resto==0) & (button_w4['text'] = 'No'):
    #     text_widget4.insert('2.0', 'Você está certo')

class Fourth_window(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title('Meu jogo')
        self.resizable(False, False)

class Button_Frame(ttk.Frame):
    def __init__(self, container):
        super().__init__(container)
        #BUTTON YES
        yes_button = ttk.Button(self, text = 'Yes')
        yes_button.pack(side = 'left', padx =5, pady = 5, fill = 'x')

        #BUTTON NO
        no_button = ttk.Button(self, text = 'No')
        no_button.pack(side = 'left', padx =5, pady = 5, fill = 'x')

class Quit_Frame(ttk.Frame):
    def __init__(self, container, label_1, function_1):
        super().__init__(container)
        self.label_1 = label_1
        self.function_1 = function_1

        next_button = ttk.Button(self, text = label_1, command = function_1)
        next_button.pack(side = 'top', padx =5, pady = 5, fill = 'x')

        quit_button = ttk.Button(self, text = 'Quit', command = root.destroy)
        quit_button.pack(side = 'top', padx =5, pady = 5, fill = 'x')



root = Fourth_window()

text_w4 = ttk.Frame(root)
text_w4.pack(side = 'top', fill = 'both', expand = True)

text_widget4 = tk.Text(text_w4)
text_widget4.pack()

button_w4 = Button_Frame(root)
button_w4.pack(side = 'bottom')


quit_w4 = Quit_Frame(root, 'Start', start_game)
quit_w4.pack(side = 'right')

root.mainloop()

EDIT: In this case, what I want to do is turn an executable that runs on the terminal into a GUI. Link to the executable on github

1 answer

1


One possible solution is to create two new functions: one to generate new questions and the other associated with buttons Sim and Não to validate the responses.

It is also necessary to make the variable numero in a variable global-

import tkinter as tk
from tkinter import ttk
import random

def adiciona_pergunta():
    global numero
    numero = random.sample(range(5000),1)[0]
    text_widget4.insert('1.0', '{} é um número é par?\n'.format(str(numero)))

def valida_resposta(bool):
    global numero
    if (bool and (numero % 2) == 0) or (bool == False and (numero % 2) != 0):
        text_widget4.insert('2.0', 'Você está certo!\n')
    else:
        text_widget4.insert('2.0', 'Você está errado!\n')

class Fourth_window(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title('Meu jogo')
        self.resizable(False, False)

class Button_Frame(ttk.Frame):
    def __init__(self, container):
        super().__init__(container)
        #BUTTON YES
        yes_button = ttk.Button(self, text = 'Yes', command=lambda: valida_resposta(True))
        yes_button.pack(side = 'left', padx =5, pady = 5, fill = 'x')

        #BUTTON NO
        no_button = ttk.Button(self, text = 'No', command=lambda: valida_resposta(False))
        no_button.pack(side = 'left', padx =5, pady = 5, fill = 'x')

class Quit_Frame(ttk.Frame):

    def __init__(self, container, label_1, function_1):
        super().__init__(container)
        self.label_1 = label_1
        self.function_1 = function_1

        next_button = ttk.Button(self, text = label_1, command = function_1)
        next_button.pack(side = 'top', padx =5, pady = 5, fill = 'x')

        quit_button = ttk.Button(self, text = 'Quit', command = root.destroy)
        quit_button.pack(side = 'top', padx =5, pady = 5, fill = 'x')


root = Fourth_window()
numero = 0 #inicializa a variavel global

text_w4 = ttk.Frame(root)
text_w4.pack(side = 'top', fill = 'both', expand = True)

text_widget4 = tk.Text(text_w4)
text_widget4.pack()

button_w4 = Button_Frame(root)
button_w4.pack(side = 'bottom')


quit_w4 = Quit_Frame(root, 'Start', adiciona_pergunta)
quit_w4.pack(side = 'right')

root.mainloop()
  • Interesting. It’s a good way out, but in this case, the show doesn’t ask the question again and, as I said in the question, I would need it to string together a series of questions. I will edit my code to include a link to my real problem

  • I’m not sure I understand your question. If you want the program to ask a new question when the user gets the answer right, just add adiciona_pergunta() within the if of function validar_resposta...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.