如何使 Button() 的状态连续?
How to make a Button()s state continuous?
我有一个 for 循环启动网格中的按钮,我希望按钮状态可切换,而不是在不再按住鼠标按钮后关闭。我还需要知道哪个按钮调用了按钮的功能,因为我在同一个 for 循环中初始化了多个按钮,这意味着它们一旦被激活就会调用相同的功能,有人知道如何帮助我吗?
编辑:
最小工作示例:
import tkinter as gui
def createWindow():
window = gui.Tk()
window.title("GoL")
icon = gui.PhotoImage(file='Not showing ya\'ll my files.png')
window.iconphoto(True, icon)
window.config(background="black")
label = gui.Label(window,\
text="Generation:",\
bg="black",\
fg="white",\
font=("Consolas",20))
label.pack()
return window
def newBoard(x = 10,y = 10):
window = createWindow()
for i in range(0, y):
for j in range(1, x+1):
button = gui.Button(window,bg="black",height=1,width=2,command=changeState)
button.place(x=23*(j-1),y=23*(i+2))
window.mainloop()
我想要的是函数changeState
来改变
您可以通过保留按钮列表 (buttons
) 来实现此目的,然后使用 lambda 函数将 row/column 数字传递给按钮命令函数,然后您可以更改所选按钮的属性。在这种情况下,它会在黑色和白色背景颜色之间切换。
def changeState(i, j):
global buttons
b = buttons[i][j]
b.config(bg = "white") if b.cget("bg") != "white" else b.config(bg = "black")
def newBoard(x = 10,y = 10):
global buttons
window = createWindow()
buttons = []
for i in range(0, y):
row = []
for j in range(1, x+1):
button = gui.Button(window,bg="black",height=1,width=2,command=lambda i=i, j=j-1: changeState(i,j))
row.append(button)
button.place(x=23*(j-1),y=23*(i+2))
buttons.append(row)
window.mainloop()
我有一个 for 循环启动网格中的按钮,我希望按钮状态可切换,而不是在不再按住鼠标按钮后关闭。我还需要知道哪个按钮调用了按钮的功能,因为我在同一个 for 循环中初始化了多个按钮,这意味着它们一旦被激活就会调用相同的功能,有人知道如何帮助我吗?
编辑:
最小工作示例:
import tkinter as gui
def createWindow():
window = gui.Tk()
window.title("GoL")
icon = gui.PhotoImage(file='Not showing ya\'ll my files.png')
window.iconphoto(True, icon)
window.config(background="black")
label = gui.Label(window,\
text="Generation:",\
bg="black",\
fg="white",\
font=("Consolas",20))
label.pack()
return window
def newBoard(x = 10,y = 10):
window = createWindow()
for i in range(0, y):
for j in range(1, x+1):
button = gui.Button(window,bg="black",height=1,width=2,command=changeState)
button.place(x=23*(j-1),y=23*(i+2))
window.mainloop()
我想要的是函数changeState
来改变
您可以通过保留按钮列表 (buttons
) 来实现此目的,然后使用 lambda 函数将 row/column 数字传递给按钮命令函数,然后您可以更改所选按钮的属性。在这种情况下,它会在黑色和白色背景颜色之间切换。
def changeState(i, j):
global buttons
b = buttons[i][j]
b.config(bg = "white") if b.cget("bg") != "white" else b.config(bg = "black")
def newBoard(x = 10,y = 10):
global buttons
window = createWindow()
buttons = []
for i in range(0, y):
row = []
for j in range(1, x+1):
button = gui.Button(window,bg="black",height=1,width=2,command=lambda i=i, j=j-1: changeState(i,j))
row.append(button)
button.place(x=23*(j-1),y=23*(i+2))
buttons.append(row)
window.mainloop()