[英]Python & Tkinter. I would like one of my buttons in my loop to change red & stay red when pressed once
Good morning,早上好,
I have have a little query & don't seem to be able to see anything on stack overflow which answers my question.我有一个小问题,似乎无法在堆栈溢出上看到任何回答我的问题的东西。 I have attached a test script below.我在下面附上了一个测试脚本。 What I would like to happen is when the "Shift" button in my loop is pressed the background of the "Shift" button goes red & stays red.我想要发生的是当按下循环中的“Shift”按钮时,“Shift”按钮的背景变为红色并保持红色。 However if the shift button is pressed again I would like the background of the "Shift" button to go back to white.但是,如果再次按下 shift 按钮,我希望 go 的“Shift”按钮的背景变回白色。
Thank you in advance, see the test code below.在此先感谢您,请参阅下面的测试代码。
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()
You should be passing the button instance not index to your CommandFunc
.您应该将按钮实例而不是索引传递给您的CommandFunc
。 Then you can use button['text']
to check if the shift key was pressed.然后您可以使用button['text']
检查是否按下了 shift 键。
Here is an example这是一个例子
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()
A small suggestion would be to name your variables and function following PEP guidelines一个小建议是按照 PEP 指南命名您的变量和 function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.