Smich
Smich

Reputation: 435

How can I take button input from tkinter in python?

I have this game where you need to choose the text and not the color it is in:

import tkinter, os, random

colors = ['Green', 'Red', 'Blue','Yellow', 'Pink', 'Orange', 'Purple', 'Grey', 'Brown', 'Black']

window = tkinter.Tk()
os.chdir(os.path.dirname(os.path.abspath(__file__)))

def color(color):
    colors.remove(color)
    text = random.choice(colors)
    label = tkinter.Label(window, text=color, fg = text, highlightthickness = 20)
    label.config(font=("Calibri", 44))
    buttonT = tkinter.Button(window, text=text)
    buttonF = tkinter.Button(window, text=color)
    colors.append(color)
    label.pack()
    buttonT.pack()
    buttonF.pack()

os.chdir(os.path.dirname(os.path.abspath(__file__)))

window.title('Color Game')
window.geometry('250x250')
instructions = tkinter.Label(window, text = 'Select word, not color!')
instructions.pack()
window.iconbitmap('icon.ico')
color(random.choice(colors))

window.mainloop()

It produces this window: enter image description here

How can I check which button the user clicks in order to determine whether his answer is correct? Can you please specify how I should implement your answer in my code? How does it work?

Thanks in advance.

Upvotes: 0

Views: 6812

Answers (2)

Prakhar Verma
Prakhar Verma

Reputation: 467

You can use lambda functions for this.

def populateMethod(self, method):
    print "method:", method

for method in ["Red","Green","Blue"]:
    button = Button(window, text=method, 
        command=lambda m=method: self.populateMethod(m))

UPDATE:

I have modified your code and added the lambda function. Check and let me know if it works fine.

import tkinter, os, random

colors = ['Green', 'Red', 'Blue','Yellow', 'Pink', 'Orange', 'Purple', 'Grey', 'Brown', 'Black']

window = tkinter.Tk()
os.chdir(os.path.dirname(os.path.abspath(__file__)))


def populateMethod(method):
    print ("method:", method)

def color(color):
    colors.remove(color)
    text = random.choice(colors)
    label = tkinter.Label(window, text=color, fg = text, highlightthickness = 20)
    label.config(font=("Calibri", 44))
    buttonT = tkinter.Button(window, text=text,command=lambda m=text: populateMethod(m))
    buttonF = tkinter.Button(window, text=color,command=lambda m=color: populateMethod(m))
    colors.append(color)
    label.pack()
    buttonT.pack()
    buttonF.pack()

os.chdir(os.path.dirname(os.path.abspath(__file__)))

window.title('Color Game')
window.geometry('250x250')
instructions = tkinter.Label(window, text = 'Select word, not color!')
instructions.pack()
# window.iconbitmap('icon.ico')
color(random.choice(colors))

window.mainloop()

Upvotes: 4

marxin
marxin

Reputation: 3922

You should use command parameter on button, like this:

def callback():
    print('button t clicked')

buttonT = tkinter.Button(window, text=text, command=callback)

Upvotes: 1

Related Questions