taking multiple user inputs from entries created in a function using tkinter in python

46 Views Asked by At

My goal is to create a list of the inputs from all boxes when you press the solve button. I have tried to take a user input but when i use focus_set() it will only focus on 1 box at a time. Is there a way to focus on all boxes and if not is there a way to take it from each box individually when the button is pressed once and stores it in a list?

import tkinter as tk

#create screen
root = tk.Tk()
root.geometry("780x400")

#create frame
frame = tk.Frame(root)

#divide into columns
frame.columnconfigure(0, weight=4)
for i in range(9):
  frame.columnconfigure(i+1, weight=1)
frame.columnconfigure(10, weight=4)

#create a title
title = tk.Label(root, text = "Sudoku Solver", height =3, font =("Arial",14))
title.pack()

#a function for creating an input box which can take spacing as well
def createBox(rowID,columnID,Xpad1,Xpad2,Ypad1,Ypad2):
  box1 = tk.Entry(frame, width =2)
  box1.grid(row=rowID, column=columnID, padx=(Xpad1,Xpad2), pady=(Ypad1,Ypad2))
  return box1

#input function
def enter():
  global Test
  string = Test.get()
  return string

#variables for padx and pady
Xpad1 = 0
Xpad2 = 0
Ypad1 = 0
Ypad2 = 0
#loops for creating the 81 input boxes with the right spacing
for i in range(9):
  for j in range(9):
    #on the 3rd column it adds a wider space for sudoku grid
    if i == 3:
      Xpad1 = 5
    #on the 6th column it adds a wider space for sudoku grid
    elif i == 5:
      Xpad2 = 5
    #on the 3rd row it adds a wider vertical space
    if j == 3:
      Ypad1 = 5
    #on the 6th row it adds a wider vertical space
    elif j == 5:
      Ypad2 = 5
    #after sorting out what spacing is needed it uses the function to create the input boxes
    Test = createBox(j,i,Xpad1,Xpad2,Ypad1,Ypad2)
    Test.focus_set()
    #the spacing variables are reset after each loop
    Xpad1 = 0
    Xpad2 = 0
    Ypad1 = 0
    Ypad2 = 0


#create a solve button
solveButton = tk.Button(root,text="Solve",command=enter)
solveButton.pack()

#the frame is then packed 
frame.pack()
root.mainloop()
1

There are 1 best solutions below

0
On BEST ANSWER

You don't need the widget to be focused in order to get its value.

You can use frame.winfo_children() to get all of the children of the frame (all of your entries) and then add the content from each entry to the list:

#input function
def enter():
    in_lst = []
    for entry in frame.winfo_children(): # all children of 'frame' are entries
        in_lst.append(entry.get()) # add the content of the entry to the list
    print(in_lst)
    return in_lst