Tkinter:如何检查使用一个功能单击了哪个按钮? [英] Tkinter: How to check which button was clicked with one function?

查看:35
本文介绍了Tkinter:如何检查使用一个功能单击了哪个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搞 Tkinter 并想出了这个:

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():
    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()

我想知道如何将 red_color_changeblue_color_change 简化为一个函数.这样做的目的是用一个函数改变彩色文本的颜色.

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.

推荐答案

为什么不使用 lambda 表达式?

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'))

这就行了.

这篇关于Tkinter:如何检查使用一个功能单击了哪个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆