charlesalexanderlee
charlesalexanderlee

Reputation: 387

Tkinter: How to check which button was clicked with one function?

I've been messing around with Tkinter and came up with this:

enter image description here

from tkinter import *

root = Tk()

def red_color_change():
    color_label.configure(fg="red")

def blue_color_change():
    color_label.configure(fg="blue")

red_button = Button(root, text="Red", fg="red", font="Arial, 20", 
command=red_color_change)
red_button.grid(row=0, column=0)

blue_button = Button(root, text="Blue", fg="blue", font="Arial, 20", 
command=blue_color_change)
blue_button.grid(row=0, column=1)

color_label = Label(root, text="Color", font="Arial, 20")
color_label.grid(row=1, columnspan=2)

root.mainloop()

I'm wondering how I can simplify red_color_change and blue_color_change into one function. The goal of this is to change the color of the color text with one function.

Upvotes: 2

Views: 1627

Answers (3)

Reblochon Masque
Reblochon Masque

Reputation: 36652

You can simplify your program to use only one button, and one function, to toggle the color:

import tkinter as tk


def toggle_color():
    global color_index
    color_index = (color_index + 1) % 2
    color_label.configure(fg=colors[color_index])


if __name__ == '__main__':

    root = tk.Tk()

    colors = ['blue', 'red']
    color_index = 0

    toggle_button = tk.Button(root, text="toggle", fg="black", font="Arial, 20",
                              command=toggle_color)
    toggle_button.grid(row=0, column=0)

    color_label = tk.Label(root, text="Color", font="Arial, 20")
    color_label.grid(row=1, column=0)

    root.mainloop()

Upvotes: 0

cylee
cylee

Reputation: 570

Why not use lambda expression?

def color_change(color):
    color_label.configure(fg=color)

red_button = Button(root, text="Red", fg="red", font="Arial, 20")
red_button.grid(row=0, column=0)
red_button.bind('<Button-1>', lambda e: color_change('red'))

blue_button = Button(root, text="Blue", fg="blue", font="Arial, 20")
blue_button.grid(row=0, column=1)
blue_button.bind('<Button-1>', lambda e: color_change('blue'))

This will do.

Upvotes: 3

Rohan
Rohan

Reputation: 563

You can use true/false, or numbers (to provide another way).

def color_change(which): #can be integer or boolean
    if which == 1: #can be changed to true
        color_label.configure(fg='red')
    elif which == 2: #can be changed to false
        color_label.configure(fg='blue')

red_button = Button(root, text="Red", fg = "red", font="Arial, 20", command = lambda: color_change(1))

blue_button = Button(root, text="Blue", fg = "blue", font="Arial, 20", command = lambda: color_change(2))

Though using integers is better because you can support many more colors (not just 2, with true/false)

Upvotes: 0

Related Questions