0

I am trying to create a simple 'SOS' puzzle game from Tkinter. I am creating an entry widgets grid using the grid method. Now I want an assigned variables for each entry. I try to do it using for loops but I can't use that variable the proper way. Can you help me? My question idea explain given below digram,

enter image description here

Code

for i in range(5):
    for j in range(5):
        self.entry=Entry(root,textvariable=f'{i}{j}')
        self.entry.grid(row=i,column=j)
        self.position.update({f"{i}-{j}":f"{i}{j}"})
enter code here
1
  • 3
    You don't want individual variables, you want a single container holding all of them. Could be a 25-element list, could be a 5-element list of 5-element lists, could be a dictionary where the keys are (row, column) tuples. Commented Oct 21, 2021 at 13:41

1 Answer 1

2

Instead of creating variables on the go, you should store the widgets made into a list or a dictionary. The list seems more reasonable as you can index it more easily.

Below is a simple, but full example that shows how you can make a 2-D list as well as search this list for the entry object:

from tkinter import * # You might want to use import tkinter as tk

root = Tk()

def searcher():
    row = int(search.get().split(',')[0]) # Parse the row out of the input given
    col = int(search.get().split(',')[1]) # Similarly, parse the column
    
    obj = lst[row][col] # Index the list with the given values
    print(obj.get()) # Use the get() to access its value.

lst = []
for i in range(5):
    tmp = [] # Sub list for the main list
    for j in range(5):
        ent = Entry(root)
        ent.grid(row=i,column=j)
        tmp.append(ent)
    lst.append(tmp)

search = Entry(root)
search.grid(row=99,column=0,pady=10) # Place this at the end

Button(root,text='Search',command=searcher).grid(row=100,column=0)

root.mainloop()

You have to enter some row and column like 0,0 which refers to 1st row, 1st column and press the button. Make sure there are no spaces in the entry. You should not worry much about the searching part, as you might require some other logic. But instead of making variables on the go, you should use this approach and store it in a container.

Also a note, you do not have to use textvariable as here the need of those are totally none. You can do whatever you want with the original object of Entry itself. Just make sure you have the list indexing start from 0 rather than 1(or subtract 1 from the given normal values).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.