Home > Net >  how to assign the variable for python tkinter entry?
how to assign the variable for python tkinter entry?

Time:10-23

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

CodePudding user response:

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).

  • Related