早上好,
我有一点疑问,似乎无法在堆栈溢出中看到任何可以回答我的问题的内容。我在下面附上了一个测试脚本。我想要发生的是当我循环中的“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()
答案 0 :(得分:1)
您应该将按钮实例而不是索引传递给您的 CommandFunc
。然后您可以使用 button['text']
来检查是否按下了 shift 键。
这是一个例子
import tkinter as tk
window = tk.Tk()
command_list = ["BckSpace", "Shift", "Space", "Enter"]
ShiftKey = False
for i in command_list:
commandBtn = tk.Button(window, width= 5, height = 1, text = i)
commandBtn.config(command= lambda x=commandBtn: CommandFunc(x))
commandBtn.pack()
def CommandFunc(btn):
global ShiftKey
if btn['text'] == command_list[1]:
if ShiftKey == False: # or btn['bg'] == 'red'
ShiftKey = True
btn['bg'] = 'red'
else:
ShiftKey = False
btn['bg'] = 'white' # or 'SystemButtonFace' if you want the orginal color
window.mainloop()
一个小建议是按照 PEP 指南命名变量和函数