Python&;特金特。我想要我的循环中的一个按钮改变红色&;按下一次时保持红色

Python&;特金特。我想要我的循环中的一个按钮改变红色&;按下一次时保持红色,python,tkinter,Python,Tkinter,早上好 我有一个小小的疑问&似乎看不到任何关于堆栈溢出的信息来回答我的问题。我在下面附上了一个测试脚本。我希望发生的是,当按下循环中的“Shift”按钮时,“Shift”按钮的背景变为红色并保持红色。但是,如果再次按下shift按钮,我希望“shift”按钮的背景恢复为白色 提前感谢您,请参阅下面的测试代码 import tkinter as tk window = tk.Tk() CommandList = ["BckSpace", "Shift",

早上好

我有一个小小的疑问&似乎看不到任何关于堆栈溢出的信息来回答我的问题。我在下面附上了一个测试脚本。我希望发生的是,当按下循环中的“Shift”按钮时,“Shift”按钮的背景变为红色并保持红色。但是,如果再次按下shift按钮,我希望“shift”按钮的背景恢复为白色

提前感谢您,请参阅下面的测试代码

import tkinter as tk

window = tk.Tk()
CommandList = ["BckSpace", "Shift", "Space", "Enter"]
ShiftKey = False

for i in range (len(CommandList)):
    CommandBtn = tk.Button(window, width= 5, height = 1, text = CommandList[i], command = lambda x = i: CommandFunc(x))
    CommandBtn.pack()


def CommandFunc(x):
    global ShiftKey
    if x == 0:
        pass

    if x == 1:
        if ShiftKey == False:
            ShiftKey = True
            #Background of only button "shift" to go red and stay red
            

        else:
            ShiftKey = False
            # Backgroud of button "shift" to go back to white

    if x == 2:
        pass

    if x == 3:
        pass



window.mainloop()

您应该将按钮实例not索引传递给您的
CommandFunc
。然后,您可以使用
按钮['text']
检查是否按下了shift键

这里有一个例子

将tkinter作为tk导入
window=tk.tk()
命令列表=[“BckSpace”、“Shift”、“Space”、“Enter”]
ShiftKey=False
对于命令列表中的i:
commandBtn=tk.按钮(窗口,宽度=5,高度=1,文本=i)
commandBtn.config(command=lambda x=commandBtn:CommandFunc(x))
commandBtn.pack()
def命令函数(btn):
全局移位键
如果btn['text']==命令列表[1]:
如果ShiftKey==False:#或btn['bg']==red'
ShiftKey=True
btn['bg']='red'
其他:
ShiftKey=False
btn['bg']='white'#或'SystemButtonFace'如果您想要原始颜色
window.mainloop()

一个小建议是按照PEP指南命名变量和函数

非常感谢。我会看看政治公众人物指南。