Tkinter: How To Check Which Button Was Clicked With One Function?
I've been messing around with Tkinter and came up with this: from tkinter import * root = Tk() def red_color_change(): color_label.configure(fg='red') def blue_color_change
Solution 1:
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.
Solution 2:
You can use true/false, or numbers (to provide another way).
def color_change(which): #can be integer or booleanifwhich == 1: #can be changed to true
color_label.configure(fg='red')
elifwhich == 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)
Solution 3:
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()
Post a Comment for "Tkinter: How To Check Which Button Was Clicked With One Function?"