Home > Blockchain >  How to run through a list a variables within a loop? - python
How to run through a list a variables within a loop? - python

Time:12-30

I am working on a project that solves sudoku puzzles. To gather the inputs I am using a GUI called "Tkinter" with 81 separate input(entry) boxes. I also have a submit button. When I press submit I would like to create a series of objects that contain atribues like cell value, row, and column. the code below does this, but I would have to copy and paste this code 81 times only adjusting the variable names and position by one each time(within the submit function). Is there any way to create a loop that could iterate these lines of code 81 times while altering the number part of the variable names?

class Cell:
    def __init__(self,number,location):
        self.number = number
        self.row = (location // 9)   1
        self.column = (location % 9)   1

def submit():
    cell1 = Cell(c1.get(),0)
    cell2 = Cell(c2.get(),1)
    cell3 = Cell(c3.get(),2)
    ...

*the .get() method is how I am retrieving the numbers from the input boxes(called c1,c2,c3...) once the button is pressed.

**location is just a number(0-80) that I use to find the row and column info.

CodePudding user response:

The simplest I could think of was to use nested for loops to create the widgets and grid them (btw row and column start at 0) and append to a list, from where they can be later referenced. So when you press the button, it goes over each of the Entrys in that list and calls their get method (and prints the value):

import tkinter as tk


def submit():
    for e in entry_list:
        print(e.get())


root = tk.Tk()

entry_list = []
for col in range(9):
    for row in range(9):
        entry = tk.Entry(root, width=2, font=('Calibri', 20))
        entry.grid(row=row, column=col, sticky='news')
        entry_list.append(entry)

btn = tk.Button(root, text='Submit', command=submit)
btn.grid(row=9, column=0, columnspan=9)

root.mainloop()
  • Related